java.lang.reflect.Method Java Examples

The following examples show how to use java.lang.reflect.Method. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LogTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * 引数に存在しないファイルパスを渡した場合_レスポンスボディに空文字列が入ったSC_OKレスポンスが返る.
 */
@Test
public void 引数に存在しないファイルパスを渡した場合_レスポンスボディに空文字列が入ったSC_OKレスポンスが返る() {
    TestLogResource logResource = new TestLogResource();

    try {
        Method method = LogResource.class.getDeclaredMethod("getLog", new Class[] {String.class, String.class });
        method.setAccessible(true);

        String filename = "/non-existing-file-path";
        Object result = method.invoke(logResource, new Object[] {"current", filename });

        assertNotNull(result);
        assertTrue(result instanceof Response);
        assertEquals(HttpStatus.SC_OK, ((Response) result).getStatus());
        assertTrue(((Response) result).getEntity() instanceof String);
        assertEquals(0, ((String) ((Response) result).getEntity()).length());
    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
}
 
Example #2
Source File: EntityContainer.java    From tomee with Apache License 2.0 6 votes vote down vote up
protected void removeEJBObject(final Method callMethod, final Object[] args, final ThreadContext callContext, final InterfaceType type) throws OpenEJBException {
    callContext.setCurrentOperation(Operation.REMOVE);

    final BeanContext beanContext = callContext.getBeanContext();
    final TransactionPolicy txPolicy = createTransactionPolicy(beanContext.getTransactionType(callMethod, type), callContext);

    EntityBean bean = null;
    try {

        bean = instanceManager.obtainInstance(callContext);

        ejbLoad_If_No_Transaction(callContext, bean);
        bean.ejbRemove();
        didRemove(bean, callContext);
        instanceManager.poolInstance(callContext, bean, callContext.getPrimaryKey());
    } catch (final Throwable e) {
        handleException(txPolicy, e, callContext, bean);
    } finally {
        afterInvoke(txPolicy, callContext);
    }
}
 
Example #3
Source File: AggFunctionTestBase.java    From flink with Apache License 2.0 6 votes vote down vote up
protected ACC accumulateValues(List<T> values)
		throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
	AggregateFunction<T, ACC> aggregator = getAggregator();
	ACC accumulator = getAggregator().createAccumulator();
	Method accumulateFunc = getAccumulateFunc();
	for (T value : values) {
		if (accumulateFunc.getParameterCount() == 1) {
			accumulateFunc.invoke(aggregator, (Object) accumulator);
		} else if (accumulateFunc.getParameterCount() == 2) {
			accumulateFunc.invoke(aggregator, (Object) accumulator, (Object) value);
		} else {
			throw new TableException("Unsupported now");
		}
	}
	return accumulator;
}
 
Example #4
Source File: EventDispatcher.java    From document-viewer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Processes a method invocation on a proxy instance and returns the
 * result.
 * 
 * @param proxy
 *            the proxy instance that the method was invoked on
 * @param method
 *            the <code>Method</code> instance corresponding to
 *            the interface method invoked on the proxy instance.
 * @param args
 *            an array of objects containing the values of the
 *            arguments passed in the method invocation on the proxy
 *            instance.
 * @return the value to return from the method invocation on the
 *         proxy instance.
 * @throws Throwable
 *             the exception to throw from the method
 *             invocation on the proxy instance.
 * @see InvocationHandler#invoke(Object, Method, Object[])
 */
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    final Class<?> listenerClass = method.getDeclaringClass();
    final List<Object> targets = m_listeners.get(listenerClass);
    if (LengthUtils.isNotEmpty(targets)) {
        final Task task = new Task(targets, method, args);
        switch (m_type) {
            case AsyncUI:
                m_base.runOnUiThread(task);
                break;
            case SeparatedThread:
                new Thread(task).start();
                break;
            case Direct:
            default:
                task.run();
                break;
        }
    }
    return null;
}
 
Example #5
Source File: ForwardingChannelBuilderTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void allMethodsForwarded() throws Exception {
  ForwardingTestUtil.testMethodsForwarded(
      ManagedChannelBuilder.class,
      mockDelegate,
      testChannelBuilder,
      Collections.<Method>emptyList(),
      new ForwardingTestUtil.ArgumentProvider() {
        @Override
        public Object get(Method method, int argPos, Class<?> clazz) {
          if (method.getName().equals("maxInboundMetadataSize")) {
            assertThat(argPos).isEqualTo(0);
            return 1; // an arbitrary positive number
          }
          return null;
        }
      });
}
 
Example #6
Source File: Rx2RetrofitInterceptorTest.java    From Mockery with Apache License 2.0 6 votes vote down vote up
@Test public void When_Call_OnIllegalMock_Response_With_Custom_Response_Adapter_Adapt_It()
    throws NoSuchMethodException, IOException {
  Method method = Providers.class.getDeclaredMethod("singleResponseMock");
  Rx2Retrofit annotation =
      PlaceholderRetrofitErrorResponseAdapterAnnotation.class.getAnnotation(Rx2Retrofit.class);
  Metadata<Rx2Retrofit> metadata = new Metadata(Providers.class,
      method, null, annotation, method.getGenericReturnType());

  Single single =
      (Single) rx2RetrofitInterceptor.onIllegalMock(new AssertionError("BOOM!"), metadata);
  TestObserver<Response<Mock>> subscriber = single.test();
  subscriber.awaitTerminalEvent();
  subscriber.assertNoErrors();
  subscriber.assertValueCount(1);

  Response<Mock> response = subscriber.values().get(0);
  assertNull(response.body());
  assertThat(response.errorBody().string(), is("{'message':'BOOM!'}"));
}
 
Example #7
Source File: GpeMockTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
private File getClientLib(String discoveryDocString) throws Exception {
  Class<?> clientLibGenerator =
      loader.loadClass("com.google.api.server.spi.tools.CloudClientLibGenerator");
  Method clientLibGeneratorMethod = null;
  clientLibGeneratorMethod = clientLibGenerator.getMethod("generateClientLib",
      String.class, /* discoveryDoc */
      String.class, /* language */
      String.class, /* languageVersion */
      String.class, /* layout */
      File.class /* file */);
  File destFile =
      File.createTempFile("client_lib", ".zip", tmpFolder.getRoot().getAbsoluteFile());
  ArrayList<Object> methodArgs = new ArrayList<Object>();
  methodArgs.add(discoveryDocString);
  methodArgs.add("JAVA");
  methodArgs.add("1.18.0-rc");
  methodArgs.add(null);
  methodArgs.add(destFile);
  Object clientLibGeneratorInstance =
      clientLibGenerator.getMethod("using", String.class).invoke(null, CLIENT_LIB_GENERATOR);
  clientLibGeneratorMethod.invoke(clientLibGeneratorInstance, methodArgs.toArray());
  return destFile;
}
 
Example #8
Source File: NewNamesFormat.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static void checkRes(String resName) throws Exception {
    System.out.println("Checking " + resName + "...");
    Class clazz = Class.forName(resName);
    Method m = clazz.getMethod("getContents");
    Object[][] contents = (Object[][])m.invoke(clazz.newInstance());
    Set<String> keys = new HashSet<String>();
    for (Object[] pair: contents) {
        String key = (String)pair[0];
        if (keys.contains(key)) {
            System.out.println("Found dup: " + key);
            throw new Exception();
        }
        checkKey(key);
        keys.add(key);
    }
}
 
Example #9
Source File: SoInstaller.java    From GiraffePlayer2 with Apache License 2.0 6 votes vote down vote up
private static Method findMethod(Object instance, String name, Class<?>... parameterTypes)
        throws NoSuchMethodException {
    for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
        try {
            Method method = clazz.getDeclaredMethod(name, parameterTypes);


            if (!method.isAccessible()) {
                method.setAccessible(true);
            }

            return method;
        } catch (NoSuchMethodException e) {
            // ignore and search next
        }
    }

    throw new NoSuchMethodException("Method " + name + " with parameters " +
            Arrays.asList(parameterTypes) + " not found in " + instance.getClass());
}
 
Example #10
Source File: InvocableHandlerMethodTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void illegalArgumentException() {
	this.resolvers.add(stubResolver(1));
	Method method = ResolvableMethod.on(TestController.class).mockCall(o -> o.singleArg(null)).method();
	Mono<HandlerResult> mono = invoke(new TestController(), method);

	try {
		mono.block();
		fail("Expected IllegalStateException");
	}
	catch (IllegalStateException ex) {
		assertNotNull("Exception not wrapped", ex.getCause());
		assertTrue(ex.getCause() instanceof IllegalArgumentException);
		assertTrue(ex.getMessage().contains("Controller ["));
		assertTrue(ex.getMessage().contains("Method ["));
		assertTrue(ex.getMessage().contains("with argument values:"));
		assertTrue(ex.getMessage().contains("[0] [type=java.lang.Integer] [value=1]"));
	}
}
 
Example #11
Source File: TmfTestHelper.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Calls the {@link TmfAbstractAnalysisModule#executeAnalysis} method of an
 * analysis module. This method does not return until the analysis is
 * completed and it returns the result of the method. It allows to execute
 * the analysis without requiring an Eclipse job and waiting for completion.
 *
 * Note that executing an analysis using this method will not automatically
 * execute the dependent analyses module. The execution of those modules is
 * left to the caller.
 *
 * @param module
 *            The analysis module to execute
 * @return The return value of the
 *         {@link TmfAbstractAnalysisModule#executeAnalysis} method
 */
public static boolean executeAnalysis(IAnalysisModule module) {
    if (module instanceof TmfAbstractAnalysisModule) {
        try {
            Class<?>[] argTypes = new Class[] { IProgressMonitor.class };
            Method method = TmfAbstractAnalysisModule.class.getDeclaredMethod("executeAnalysis", argTypes);
            method.setAccessible(true);
            Boolean result = (Boolean) method.invoke(module, new NullProgressMonitor());
            // Set the module as completed, to avoid another call creating a job
            method = TmfAbstractAnalysisModule.class.getDeclaredMethod("setAnalysisCompleted", new Class[] { } );
            method.setAccessible(true);
            method.invoke(module);
            return result;
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
            fail(e.toString());
        }
    }
    throw new RuntimeException("This analysis module does not have a protected method to execute. Maybe it can be executed differently? Or it is not supported yet in this method?");
}
 
Example #12
Source File: AbstractMarshallerFactory.java    From faster-framework-project with Apache License 2.0 6 votes vote down vote up
/**
 * 检查方法是否包含一个参数,为StreamObserver
 *
 * @param methodCallProperty 方法
 */
private void checkOneParamHasStreamObServer(MethodCallProperty methodCallProperty) {
    Method method = methodCallProperty.getMethod();
    //判断当前方法是否仅包含一个参数,为StreamObserver。如果不是,抛出异常。
    Type[] types = method.getGenericParameterTypes();
    if (types == null || types.length != 1) {
        throw new GRpcMethodNoMatchException(method.getDeclaringClass().getName(), method.getName(), methodCallProperty.getMethodType().name(),
                "You should use one param [StreamObserver] in your method.Please check it.");
    }
    //检查第一个参数是否为StreamObserver
    Type type = Utils.safeElement(types, 0);
    if (type instanceof ParameterizedType) {
        if (!((ParameterizedType) type).getRawType().getTypeName().equals(StreamObserver.class.getName())) {
            throw new GRpcMethodNoMatchException(method.getDeclaringClass().getName(), method.getName(), methodCallProperty.getMethodType().name(),
                    "You should use one param [StreamObserver] in your method.Please check it.");
        }
    } else {
        if (!type.getTypeName().equals(StreamObserver.class.getName())) {
            throw new GRpcMethodNoMatchException(method.getDeclaringClass().getName(), method.getName(), methodCallProperty.getMethodType().name(),
                    "You should use one param [StreamObserver] in your method.Please check it.");
        }
    }
}
 
Example #13
Source File: ReflectUtilsTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetPropertySetterMethod() throws Exception {
    Method method = TestReflect.class.getMethod("setS", int.class);
    Assert.assertEquals(method, getPropertySetterMethod(TestReflect.class, "s", int.class));

    method = TestReflect.class.getMethod("setB", boolean.class);
    Assert.assertEquals(method, getPropertySetterMethod(TestReflect.class, "b", boolean.class));

    boolean error = false;
    try {
        getPropertySetterMethod(TestReflect.class, "xxx", String.class);
    } catch (Exception e) {
        error = true;
    }
    Assert.assertTrue(error);
}
 
Example #14
Source File: IndexResource.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static JsonObject getResourceMethodIndexNode(String pathPrefix, Collection<Method> methods, ArgsUriPart args, boolean addPsfQueryParams) throws Exception {
	JsonObject indexNode = new JsonObject();
	if (methods != null) {
		Iterator<Method> it = methods.iterator();
		while (it.hasNext()) {
			Method field = it.next();
			JsonObject methodNode = new JsonObject();
			String resource = joinUri(pathPrefix, args.getMethodTransfilter().transform(field.getName()));
			Set<NamedParameter> queryParams = args.getNamedParameters(field.getName(), true);
			if (addPsfQueryParams) {
				queryParams.addAll(PSFUriPart.SLURPED_NAMED_QUERY_PARAMETERS);
			}
			methodNode.add(JS_QUERY_PARAMS_FIELD, createQueryParameterNode(queryParams));
			methodNode.add(JS_OUT_VO_FIELD, createVOReturnTypeNode(field.getReturnType(), field.getGenericReturnType()));
			indexNode.add(resource, methodNode);
		}
	}
	return indexNode;
}
 
Example #15
Source File: EventSetDescriptor.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates an <TT>EventSetDescriptor</TT> assuming that you are
 * following the most simple standard design pattern where a named
 * event &quot;fred&quot; is (1) delivered as a call on the single method of
 * interface FredListener, (2) has a single argument of type FredEvent,
 * and (3) where the FredListener may be registered with a call on an
 * addFredListener method of the source component and removed with a
 * call on a removeFredListener method.
 *
 * @param sourceClass  The class firing the event.
 * @param eventSetName  The programmatic name of the event.  E.g. &quot;fred&quot;.
 *          Note that this should normally start with a lower-case character.
 * @param listenerType  The target interface that events
 *          will get delivered to.
 * @param listenerMethodName  The method that will get called when the event gets
 *          delivered to its target listener interface.
 * @exception IntrospectionException if an exception occurs during
 *              introspection.
 */
public EventSetDescriptor(Class<?> sourceClass, String eventSetName,
            Class<?> listenerType, String listenerMethodName)
            throws IntrospectionException {
    this(sourceClass, eventSetName, listenerType,
         new String[] { listenerMethodName },
         Introspector.ADD_PREFIX + getListenerClassName(listenerType),
         Introspector.REMOVE_PREFIX + getListenerClassName(listenerType),
         Introspector.GET_PREFIX + getListenerClassName(listenerType) + "s");

    String eventName = NameGenerator.capitalize(eventSetName) + "Event";
    Method[] listenerMethods = getListenerMethods();
    if (listenerMethods.length > 0) {
        Class[] args = getParameterTypes(getClass0(), listenerMethods[0]);
        // Check for EventSet compliance. Special case for vetoableChange. See 4529996
        if (!"vetoableChange".equals(eventSetName) && !args[0].getName().endsWith(eventName)) {
            throw new IntrospectionException("Method \"" + listenerMethodName +
                                             "\" should have argument \"" +
                                             eventName + "\"");
        }
    }
}
 
Example #16
Source File: CachePointCutTest.java    From jetcache with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatches4() throws Exception {
    Method m1 = I4.class.getMethod("foo");
    Method m2 = C4.class.getMethod("foo");
    Assert.assertTrue(pc.matches(m1, C4.class));
    Assert.assertTrue(pc.matches(m2, C4.class));
    Assert.assertTrue(pc.matches(m1, I4.class));
    Assert.assertTrue(pc.matches(m2, I4.class));

    Assert.assertFalse(map.getByMethodInfo(CachePointcut.getKey(m1, I4.class)).isEnableCacheContext());
    Assert.assertNotNull(map.getByMethodInfo(CachePointcut.getKey(m1, I4.class)).getCachedAnnoConfig());

    Assert.assertTrue(map.getByMethodInfo(CachePointcut.getKey(m1, C4.class)).isEnableCacheContext());
    Assert.assertNotNull(map.getByMethodInfo(CachePointcut.getKey(m1, C4.class)).getCachedAnnoConfig());

    Assert.assertTrue(map.getByMethodInfo(CachePointcut.getKey(m2, I4.class)).isEnableCacheContext());
    Assert.assertNotNull(map.getByMethodInfo(CachePointcut.getKey(m2, I4.class)).getCachedAnnoConfig());

    Assert.assertTrue(map.getByMethodInfo(CachePointcut.getKey(m2, C4.class)).isEnableCacheContext());
    Assert.assertNotNull(map.getByMethodInfo(CachePointcut.getKey(m2, C4.class)).getCachedAnnoConfig());

}
 
Example #17
Source File: Class.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
private Method getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods)
        throws NoSuchMethodException {
    if (name == null) {
        throw new NullPointerException("name == null");
    }
    if (parameterTypes == null) {
        parameterTypes = EmptyArray.CLASS;
    }
    for (Class<?> c : parameterTypes) {
        if (c == null) {
            throw new NoSuchMethodException("parameter type is null");
        }
    }
    Method result = recursivePublicMethods ? getPublicMethodRecursive(name, parameterTypes)
                                           : getDeclaredMethodInternal(name, parameterTypes);
    // Fail if we didn't find the method or it was expected to be public.
    if (result == null ||
        (recursivePublicMethods && !Modifier.isPublic(result.getAccessFlags()))) {
        throw new NoSuchMethodException(name + " " + Arrays.toString(parameterTypes));
    }
    return result;
}
 
Example #18
Source File: CertifiedDataAbstractTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
protected Double getProperty(Object bean, String name) {
    try {
        // Get the value of prop
        String prop = "get" + name.substring(0,1).toUpperCase() + name.substring(1);
        Method meth = bean.getClass().getMethod(prop, new Class[0]);
        Object property = meth.invoke(bean, new Object[0]);
        if (meth.getReturnType().equals(Double.TYPE)) {
            return (Double) property;
        } else if (meth.getReturnType().equals(Long.TYPE)) {
            return Double.valueOf(((Long) property).doubleValue());
        } else {
            fail("wrong type: " + meth.getReturnType().getName());
        }
    } catch (NoSuchMethodException nsme) {
        // ignored
    } catch (InvocationTargetException ite) {
        fail(ite.getMessage());
    } catch (IllegalAccessException iae) {
        fail(iae.getMessage());
    }
    return null;
}
 
Example #19
Source File: SharedClassObject.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Read resolve to the read object.
 * We give chance to actual instance to do its own resolution as well. It
 * is necessary for achieving back compatability of certain types of settings etc.
 */
private Object readResolve() throws ObjectStreamException {
    SharedClassObject resolved = object;

    Method resolveMethod = findReadResolveMethod(object.getClass());

    if (resolveMethod != null) {
        // invoke resolve method and accept its result
        try {
            // make readResolve accessible (it can have any access modifier)
            resolveMethod.setAccessible(true);

            return resolveMethod.invoke(object);
        } catch (Exception ex) {
            // checked or runtime does not matter - we must survive
            String banner = "Skipping " + object.getClass() + " resolution:"; //NOI18N
            err.log(Level.WARNING, banner, ex);
        } finally {
            resolveMethod.setAccessible(false);
        }
    }

    return resolved;
}
 
Example #20
Source File: Test4508780.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    for (String name : this.names) {
        Object bean;
        try {
            bean = this.loader.loadClass(name).newInstance();
        } catch (Exception exception) {
            throw new Error("could not instantiate bean: " + name, exception);
        }
        if (this.loader != bean.getClass().getClassLoader()) {
            throw new Error("bean class loader is not equal to default one");
        }
        PropertyDescriptor[] pds = getPropertyDescriptors(bean);
        for (PropertyDescriptor pd : pds) {
            Class type = pd.getPropertyType();
            Method setter = pd.getWriteMethod();
            Method getter = pd.getReadMethod();

            if (type.equals(String.class)) {
                executeMethod(setter, bean, "Foo");
            } else if (type.equals(int.class)) {
                executeMethod(setter, bean, Integer.valueOf(1));
            }
            executeMethod(getter, bean);
        }
    }
}
 
Example #21
Source File: ActionUtils.java    From aws-sdk-java-resources with Apache License 2.0 6 votes vote down vote up
private static Method tryFindClientMethod(Object client, String name) {
    // TODO: Cache me.
    for (Method method : client.getClass().getMethods()) {
        if (!method.getName().equals(name)) {
            continue;
        }

        Class<?>[] parameters = method.getParameterTypes();
        if (parameters.length != 1) {
            continue;
        }

        // This is the inverse of the normal approach of findMethod() -
        // we're looking for a method which will accept a specific subtype
        // of AmazonWebServiceRequest, without worrying overmuch about
        // what subtype it is. We'll create an object of the appropriate
        // type and fill it in.
        if (AmazonWebServiceRequest.class.isAssignableFrom(parameters[0])) {
            return method;
        }
    }

    return null;
}
 
Example #22
Source File: WindupAdjacencyMethodHandler.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
@RuntimeType
public static List getVertexes(@This final VertexFrame thiz, @Origin final Method method, @RuntimeType @Argument(0) final Class type) {
    assert thiz instanceof CachesReflection;
    final Adjacency annotation = ((CachesReflection) thiz).getReflectionCache().getAnnotation(method, Adjacency.class);
    final Direction direction = annotation.direction();
    final String label = annotation.label();
    final TypeResolver resolver = thiz.getGraph().getTypeResolver();

    return thiz.traverse(input -> {
        switch(direction) {
            case IN:
                return resolver.hasType(input.in(label), type);
            case OUT:
                return resolver.hasType(input.out(label), type);
            case BOTH:
                return resolver.hasType(input.both(label), type);
            default:
                throw new IllegalStateException("Direction not recognized.");
        }
    }).toList(type);
}
 
Example #23
Source File: AbstractClassFactory.java    From anno4j with Apache License 2.0 5 votes vote down vote up
private Collection<Method> getMethods(Class<?> c) {
	List<Method> methods = new ArrayList<Method>();
	methods.addAll(Arrays.asList(c.getMethods()));
	HashMap<Object, Method> map = new HashMap<Object, Method>();
	Map<Object, Method> pms = getProtectedMethods(c, map);
	methods.addAll(pms.values());
	return methods;
}
 
Example #24
Source File: TestHelper.java    From butterfly with MIT License 5 votes vote down vote up
@BeforeMethod
public void beforeMethod(Method method) throws URISyntaxException, IOException {
    transformedAppFolder = new File(appFolder.getParentFile(), String.format("test-app_%s_%s_%s", method.getDeclaringClass().getSimpleName(), method.getName(), System.currentTimeMillis()));
    FileUtils.copyDirectory(appFolder, transformedAppFolder);
    System.out.printf("Transformed app folder: %s\n", transformedAppFolder.getAbsolutePath());
    transformationContext = Mockito.mock(TransformationContext.class);
}
 
Example #25
Source File: ThriftCodecByteCodeGenerator.java    From drift with Apache License 2.0 5 votes vote down vote up
private static boolean needsCastAfterRead(ThriftFieldMetadata field, Method readMethod)
{
    Class<?> methodReturn = readMethod.getReturnType();
    Class<?> fieldType;
    if (field.getCoercion().isPresent()) {
        fieldType = field.getCoercion().get().getFromThrift().getParameterTypes()[0];
    }
    else {
        fieldType = TypeToken.of(field.getThriftType().getJavaType()).getRawType();
    }
    return !fieldType.isAssignableFrom(methodReturn);
}
 
Example #26
Source File: ResponderInterceptor.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void handleMethodException(EnhancedInstance enhancedInstance, Method method, Object[] objects,
    Class<?>[] classes, Throwable throwable) {
    if (ContextManager.isActive()) {
        ContextManager.activeSpan().errorOccurred().log(throwable);
    }
}
 
Example #27
Source File: TestCompilerInlining.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static Method getMethod(Class<?> aClass, String name, Class<?>... params) {
    try {
        return aClass.getDeclaredMethod(name, params);
    } catch (NoSuchMethodException | SecurityException e) {
        throw new Error("TESTBUG : cannot get method " + name + Arrays.toString(params), e);
    }
}
 
Example #28
Source File: BeanUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Obtain a new MethodParameter object for the write method of the
 * specified property.
 * @param pd the PropertyDescriptor for the property
 * @return a corresponding MethodParameter object
 */
public static MethodParameter getWriteMethodParameter(PropertyDescriptor pd) {
	if (pd instanceof GenericTypeAwarePropertyDescriptor) {
		return new MethodParameter(((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodParameter());
	}
	else {
		Method writeMethod = pd.getWriteMethod();
		Assert.state(writeMethod != null, "No write method available");
		return new MethodParameter(writeMethod, 0);
	}
}
 
Example #29
Source File: IdmEngineAutoConfigurationTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private void assertAllServicesPresent(ApplicationContext context, IdmEngine idmEngine) {
    List<Method> methods = Stream.of(IdmEngine.class.getDeclaredMethods())
        .filter(method -> !(method.getName().equals("close") || method.getName().equals("getName")))
        .collect(Collectors.toList());

    assertThat(methods).allSatisfy(method -> {
        try {
            assertThat(context.getBean(method.getReturnType()))
                .as(method.getReturnType() + " bean")
                .isEqualTo(method.invoke(idmEngine));
        } catch (IllegalAccessException | InvocationTargetException e) {
            fail("Failed to invoke method " + method, e);
        }
    });
}
 
Example #30
Source File: ReflectionFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Lookup readResolve or writeReplace on a class with specified
 * signature constraints.
 * @param cl a serializable class
 * @param methodName the method name to find
 * @returns a MethodHandle for the method or {@code null} if not found or
 *       has the wrong signature.
 */
private MethodHandle getReplaceResolveForSerialization(Class<?> cl,
                                                       String methodName) {
    if (!Serializable.class.isAssignableFrom(cl)) {
        return null;
    }

    Class<?> defCl = cl;
    while (defCl != null) {
        try {
            Method m = defCl.getDeclaredMethod(methodName);
            if (m.getReturnType() != Object.class) {
                return null;
            }
            int mods = m.getModifiers();
            if (Modifier.isStatic(mods) | Modifier.isAbstract(mods)) {
                return null;
            } else if (Modifier.isPublic(mods) | Modifier.isProtected(mods)) {
                // fall through
            } else if (Modifier.isPrivate(mods) && (cl != defCl)) {
                return null;
            } else if (!packageEquals(cl, defCl)) {
                return null;
            }
            try {
                // Normal return
                m.setAccessible(true);
                return MethodHandles.lookup().unreflect(m);
            } catch (IllegalAccessException ex0) {
                // setAccessible should prevent IAE
                throw new InternalError("Error", ex0);
            }
        } catch (NoSuchMethodException ex) {
            defCl = defCl.getSuperclass();
        }
    }
    return null;
}