Java Code Examples for java.lang.reflect.Method

The following are top voted examples for showing how to use java.lang.reflect.Method. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: lettuce   File: PooledConnectionInvocationHandler.java View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {

    if (DISABLED_METHODS.contains(method.getName())) {
        throw new UnsupportedOperationException("Calls to " + method.getName() + " are not supported on pooled connections");
    }

    if (connection == null) {
        throw new RedisException("Connection is deallocated and cannot be used anymore.");
    }

    if (method.getName().equals("close")) {
        pool.freeConnection((T) proxy);
        return null;
    }

    Method targetMethod = methodCache.get(method);

    try {
        return targetMethod.invoke(connection, args);
    } catch (InvocationTargetException e) {
        throw e.getTargetException();
    }
}
 
Example 2
Project: TinyProtocolAPI   File: Overlay.java View source code 6 votes vote down vote up
public void addListener(PacketListener listener) {
	List<Method> out = Lists.newArrayList(), in = Lists.newArrayList();
	for (Method method : listener.getClass().getDeclaredMethods()) {

		Class<?>[] value = method.getParameterTypes();
		if (value.length != 1 || !PacketEvent.class.equals(value[0]))
			continue;

		PacketHandler type = method.getAnnotation(PacketHandler.class);
		if (type == null)
			continue;

		if (type.packet().hasOut())
			out.add(method);
		else if (type.packet().hasIn())
			in.add(method);

		else
			continue;
	}
	if (!out.isEmpty())
		OUT.put(listener, out);
	if (!in.isEmpty())
		IN.put(listener, in);
}
 
Example 3
Project: jentrata-msh   File: MessageHistoryPageletAdaptorTest.java View source code 6 votes vote down vote up
public void testCheckEmptyAndReturnNull() throws Exception {
	Method m = Class.forName("hk.hku.cecid.ebms.admin.listener.MessageHistoryPageletAdaptor").
		getDeclaredMethod("checkEmptyAndReturnNull", new Class[] {String.class});
	m.setAccessible(true);
	TestCase.assertEquals("abcdefg", (String)m.invoke(adaptor, new Object[] {"abcdefg"}));
	TestCase.assertEquals(null, (String)m.invoke(adaptor, new Object[] {""}));
}
 
Example 4
Project: TinyProtocolAPI   File: TinyProtocol.java View source code 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
		throws Exception {
	final Channel channel = ctx.channel();
	handleLoginStart(channel, msg);

	for (Entry<PacketListener, List<Method>> listener : IN.entrySet()) {
		for (Method method : listener.getValue()) {
			PacketHandler ann = method
					.getAnnotation(PacketHandler.class);
			if (!ann.packet().getName()
					.equals(msg.getClass().getSimpleName()))
				continue;

			PacketEvent evt = new PacketEvent(player, msg);
			method.setAccessible(true);
			method.invoke(listener.getKey(), evt);
			method.setAccessible(false);
			msg = evt.getPacket();
		}
	}
	if (msg != null) {
		super.channelRead(ctx, msg);
	}
}
 
Example 5
Project: elasticsearch-osem   File: OsemReflectionUtils.java View source code 6 votes vote down vote up
public static Class getGenericType(Method method) {
    if (!Collection.class.isAssignableFrom(method.getReturnType())) {
        return method.getReturnType();
    }
    ParameterizedType type = (ParameterizedType) method.getGenericReturnType();
    return (Class) type.getActualTypeArguments()[0];
}
 
Example 6
Project: tapestry-model   File: HibernateSearchDescriptorDecorator.java View source code 6 votes vote down vote up
private boolean isAnnotationPresent(PropertyDescriptor[] descriptors,
	final TynamoPropertyDescriptor tynamoPropertyDescriptor,
	Class<? extends Annotation> annotation) {
	// copied from TynamoDecorator. Perhaps the right thing to do would be to push to implement PropertyAccess.getAnnotation()?
	try {

		PropertyDescriptor beanPropDescriptor = F.flow(descriptors).filter(new Predicate<PropertyDescriptor>() {
			public boolean accept(PropertyDescriptor descriptor) {
				return descriptor.getName().equals(tynamoPropertyDescriptor.getName());
			}
		}).first();
		if (beanPropDescriptor == null) return false;

		Method readMethod = beanPropDescriptor.getReadMethod();
		return readMethod.isAnnotationPresent(annotation);

	} catch (Exception ex) {
		LOGGER.warn(ExceptionUtils.getRootCauseMessage(ex));
	}
	return false;
}
 
Example 7
Project: wampspring   File: InvocableWampHandlerMethod.java View source code 6 votes vote down vote up
/**
 * Assert that the target bean class is an instance of the class where the given
 * method is declared. In some cases the actual controller instance at request-
 * processing time may be a JDK dynamic proxy (lazy initialization, prototype beans,
 * and others). [email protected] @Controller}'s that require proxying should prefer class-based
 * proxy mechanisms.
 */
private void assertTargetBean(Method method, Object targetBean, Object[] args) {
	Class<?> methodDeclaringClass = method.getDeclaringClass();
	Class<?> targetBeanClass = targetBean.getClass();
	if (!methodDeclaringClass.isAssignableFrom(targetBeanClass)) {
		String msg = "The mapped controller method class '"
				+ methodDeclaringClass.getName()
				+ "' is not an instance of the actual controller bean instance '"
				+ targetBeanClass.getName()
				+ "'. If the controller requires proxying "
				+ "(e.g. due to @Transactional), please use class-based proxying.";
		throw new IllegalStateException(getInvocationErrorMessage(msg, args));
	}
}
 
Example 8
Project: richfaces   File: DependencyInjectorImpl.java View source code 6 votes vote down vote up
private void verifyPostConstructMethod(Method method) {
    // TODO - allow FacesContext to be passed
    if (method.getParameterTypes().length != 0) {
        throw new IllegalStateException(MessageFormat.format("Post-construction method {0} has one or more parameters",
            method.toString()));
    }

    if (!Void.TYPE.equals(method.getReturnType())) {
        throw new IllegalStateException(MessageFormat.format("Post-construction method {0} has incorrect return type",
            method.toString()));
    }

    if ((method.getModifiers() & Modifier.STATIC) != 0) {
        throw new IllegalStateException(MessageFormat.format("Post-construction method {0} is static", method.toString()));
    }

    Class<?>[] exceptionTypes = method.getExceptionTypes();
    for (Class<?> exceptionType : exceptionTypes) {
        if (isUncheckedException(exceptionType)) {
            continue;
        }

        throw new IllegalStateException(MessageFormat.format("Post-construction method {0} throws checked exception",
            method.toString()));
    }
}
 
Example 9
Project: jeql   File: ManCommand.java View source code 6 votes vote down vote up
private void genFunction(String funcName, Method meth, 
    int index, ArrayRowList funcRL, ArrayRowList funcParamRL)
{
  String moduleName = FunctionRegistry.moduleName(funcName);
  String name = ClassUtil.classname(funcName);
  Class retTypeClz = meth.getReturnType();
  String retType = ClassUtil.classname(retTypeClz);
  
  funcRL.add(new BasicRow(new Object[] {
      moduleName,
      index,
      name,
      retType,
      ManUtil.description(meth)
  }));
  
  Class[] param = meth.getParameterTypes();
  Annotation[][] panno = meth.getParameterAnnotations();
  
  for (int i = 0; i < param.length; i++) {
    String pname = ManUtil.name(panno[i]);
    funcParamRL.add(new BasicRow(new Object[] {
        moduleName,
        index,
        name,
        retType,
        ManUtil.description(meth),
        i,
        pname,
        ClassUtil.classname(param[i].getName())
    }));
  }
}
 
Example 10
Project: xapi   File: AnnotationTests.java View source code 6 votes vote down vote up
@Test
public void testAnnotationsKeepAll() throws Exception {
  final Class<?> testCase = magicClass(ReflectionCaseHasAllAnnos.class);
  final Field field = testCase.getDeclaredField("field");
  final Method method = testCase.getDeclaredMethod("method", Long.class);
  final Constructor<?> ctor = testCase.getDeclaredConstructor(long.class);
  Annotation[] annos = testCase.getAnnotations();
  assertHasAnno(testCase, annos, RuntimeRetention.class);
  if (GWT.isScript()) {
    // Gwt Dev can only access runtime level retention annotations
    assertHasAnno(testCase, annos, CompileRetention.class);
  }
  annos = field.getAnnotations();
  assertHasAnno(testCase, annos, RuntimeRetention.class);
  if (GWT.isScript()) {
    // Gwt Dev can only access runtime level retention annotations
    assertHasAnno(testCase, annos, CompileRetention.class);
  }

  annos = method.getAnnotations();
  assertHasAnno(testCase, annos, RuntimeRetention.class);
  if (GWT.isScript()) {
    // Gwt Dev can only access runtime level retention annotations
    assertHasAnno(testCase, annos, CompileRetention.class);
  }

  annos = ctor.getAnnotations();
  assertHasAnno(testCase, annos, RuntimeRetention.class);
  if (GWT.isScript()) {
    // Gwt Dev can only access runtime level retention annotations
    assertHasAnno(testCase, annos, CompileRetention.class);
  }

}
 
Example 11
Project: ilarkesto   File: ReflectionComponentReflector.java View source code 6 votes vote down vote up
@Override
public void handle(Annotation annotation, Method method, Object object) {
	if (annotation.annotationType() != Init.class) return;

	log.debug("Calling initialization method:", object.getClass().getSimpleName() + "." + method.getName()
			+ "()");
	try {
		if (!method.isAccessible()) method.setAccessible(true);
		method.invoke(object);
	} catch (Throwable ex) {
		throw new InitializationFaildException(object, method.getName(), ex);
	}
}
 
Example 12
Project: virgo.kernel   File: AnnotationBasedCommandResolverTests.java View source code 6 votes vote down vote up
private void assertCommandEquals(Method expectedMethod, String expectedCommandName, String expectedSubCommandName,
    List<CommandDescriptor> commands) {
    boolean found = false;
    for (CommandDescriptor commandDescriptor : commands) {
        if (expectedMethod.equals(commandDescriptor.getMethod())) {
            found = true;
            assertEquals(expectedCommandName, commandDescriptor.getCommandName());
            assertEquals(expectedSubCommandName, commandDescriptor.getSubCommandName());
        }
    }
    assertTrue("Method not found '" + expectedMethod + "'", found);
}
 
Example 13
Project: airlift   File: AnnotationUtils.java View source code 6 votes vote down vote up
/**
 * Find methods that are tagged with the given annotation somewhere in the hierarchy.
 *
 * @param clazz the class to analyze
 * @param annotation the annotation to find
 * @return the annotated methods
 */
public static Collection<Method> findAnnotatedMethods(Class<?> clazz, Class<? extends Annotation> annotation)
{
    Collection<Method> result = newArrayList();

    // gather all publicly available methods, including those declared in a parent
    for (Method method : clazz.getMethods()) {
        // skip methods that are used internally by the vm for implementing covariance, etc.
        if (method.isSynthetic() || method.isBridge()) {
            continue;
        }
        if (Modifier.isStatic(method.getModifiers())) {
            continue;
        }

        // look for annotations recursively in super-classes or interfaces
        Method managedMethod = findAnnotatedMethod(clazz, annotation, method.getName(), method.getParameterTypes());
        if (managedMethod != null) {
            result.add(managedMethod);
        }
    }

    return result;
}
 
Example 14
Project: powerunit   File: ParametersValidator.java View source code 6 votes vote down vote up
default void checkParametersAnnotationForMethod(Method m) {
    if (!Modifier.isStatic(m.getModifiers())) {
        throw new InternalError("@Parameters method is not static "
                + m.toString());
    }
    if (!Modifier.isPublic(m.getModifiers())) {
        throw new InternalError("@Parameters method is not public "
                + m.toString());
    }
    if (!Stream.class.isAssignableFrom(m.getReturnType())) {
        throw new InternalError("@Parameters method is not Stream<...> "
                + m.toString());
    }
    if (m.getParameterCount() != 0
            && !m.getDeclaringClass().isAnnotationPresent(
                    TestDelegator.class)) {
        throw new InternalError("@Parameters method is not 0-parameter "
                + m.toString());
    }
    if (m.getParameterCount() != 1
            && m.getDeclaringClass().isAnnotationPresent(
                    TestDelegator.class)) {
        throw new InternalError("@Parameters method is not 1-parameter "
                + m.toString() + " with test delegator.");
    }
}
 
Example 15
Project: JerseyTest   File: ControllerInvocationHandler.java View source code 6 votes vote down vote up
/**
 * Finds an annotation annotated with @HttpMethod in the
 * controller class (such as @GET, @PUT, etc.) or any of
 * its superclasses.
 */
private String getHttpMethod(Class<?> ctrlClass, Method method) {
    // Find annotation in this class
    for (Annotation annot : method.getDeclaredAnnotations()) {
        HttpMethod httpMethod =
                annot.annotationType().getAnnotation(HttpMethod.class);
        if (httpMethod != null) {
            return httpMethod.value();
        }
    }

    // Try super interfaces then
    Class<?>[] superInterfaces = ctrlClass.getInterfaces();
    for (Class<?> superInterface : superInterfaces) {
        for (Method superMethod : superInterface.getDeclaredMethods()) {
            if (superMethod.getName().equals(method.getName())
                    && superMethod.getReturnType() == method.getReturnType()
                    && Arrays.equals(superMethod.getParameterTypes(),
                                     method.getParameterTypes())) {
                return getHttpMethod(superInterface, superMethod);
            }
        }
    }

    // Not found
    return null;
}
 
Example 16
Project: dashbuilder   File: AnnotationProxy.java View source code 6 votes vote down vote up
private Map<String, Object> getAnnotationValues(AnnotationDescriptor descriptor) {
	Map<String, Object> result = new HashMap<String, Object>();
	int processedValuesFromDescriptor = 0;
	final Method[] declaredMethods = ReflectionHelper.getMethods( annotationType );
	for ( Method m : declaredMethods ) {
		if ( descriptor.containsElement( m.getName() ) ) {
			result.put( m.getName(), descriptor.valueOf( m.getName() ) );
			processedValuesFromDescriptor++;
		}
		else if ( m.getDefaultValue() != null ) {
			result.put( m.getName(), m.getDefaultValue() );
		}
		else {
			throw new IllegalArgumentException( "No value provided for " + m.getName() );
		}
	}
	if ( processedValuesFromDescriptor != descriptor.numberOfElements() ) {
		throw new RuntimeException( "Trying to instantiate " + annotationType + " with unknown parameters." );
	}
	return result;
}
 
Example 17
Project: spring4-showcase   File: CacheAspectSupport.java View source code 6 votes vote down vote up
private Object[] extractArgs(Method method, Object[] args) {
    if (!method.isVarArgs()) {
        return args;
    }
    Object[] varArgs = (Object[]) args[args.length - 1];
    Object[] combinedArgs = new Object[args.length - 1 + varArgs.length];
    System.arraycopy(args, 0, combinedArgs, 0, args.length - 1);
    System.arraycopy(varArgs, 0, combinedArgs, args.length - 1, varArgs.length);
    return combinedArgs;
}
 
Example 18
Project: xapi   File: ModelUtil.java View source code 6 votes vote down vote up
/**
 * @param method
 * @return
 */
public static boolean isFluent(final Method method) {
  final Class<?> methodType = method.getDeclaringClass();
  final Class<?> returnType = method.getReturnType();
  if (returnType == null || returnType == void.class) {
    return false;
  }
  if (
      areAssignable(methodType, returnType)
      ) {
    // Returning this would be allowed.
    // However, we should guard against methods that may actually want to return a field
    // that is the same type as itself.
    final Fluent fluent = method.getAnnotation(Fluent.class);
    if (fluent != null) {
      return fluent.value();
    }
    if (method.getParameterTypes().length > 0) {
      // check if there is a single parameter type which is also compatible,
      // and throw an error telling the user that they must specify @Fluent(true) or @Fluent(false)
      // Because the method signature is ambiguous
      if (areAssignable(methodType, method.getParameterTypes()[0])) {
        throw new NotConfiguredCorrectly("Method "+method.toGenericString()+" in "+methodType
            +" has ambiguous return type; cannot tell if this method is Fluent. Please annotate "
            + "this method with @Fluent(true) if the method is supposed to `return this;` or "
            + "use @Fluent(false) if this method is supposed to return the first parameter.");
      }
    }
    return true;
  }
  return false;
}
 
Example 19
Project: Chronicle-Values   File: Generators.java View source code 6 votes vote down vote up
static MethodSpec.Builder methodBuilder(Method m, List<String> paramNames) {
    MethodSpec.Builder builder = MethodSpec.methodBuilder(m.getName())
            .addAnnotation(Override.class)
            .addModifiers(PUBLIC);
    builder.returns(m.getReturnType());
    Parameter[] parameters = m.getParameters();
    for (int i = 0; i < parameters.length; i++) {
        Parameter p = parameters[i];
        builder.addParameter(ParameterSpec.builder(p.getType(), paramNames.get(i)).build());
    }
    return builder;
}
 
Example 20
Project: fluent-http   File: MethodAnnotationsFactory.java View source code 6 votes vote down vote up
private <T extends Annotation> T findAnnotationOnMethodOrClass(Class<T> annotationType, Method method) {
  T annotation = method.getDeclaredAnnotation(annotationType);
  if (annotation != null) {
    return annotation;
  }

  annotation = method.getDeclaringClass().getDeclaredAnnotation(annotationType);
  if (annotation != null) {
    return annotation;
  }

  return null;
}
 
Example 21
Project: sisu-guice   File: TypeLiteral.java View source code 6 votes vote down vote up
/**
 * Returns the resolved generic exception types thrown by [email protected] constructor}.
 *
 * @param methodOrConstructor a method or constructor defined by this or any supertype.
 * @since 2.0
 */
public List<TypeLiteral<?>> getExceptionTypes(Member methodOrConstructor) {
  Type[] genericExceptionTypes;

  if (methodOrConstructor instanceof Method) {
    Method method = (Method) methodOrConstructor;
    checkArgument(method.getDeclaringClass().isAssignableFrom(rawType),
        "%s is not defined by a supertype of %s", method, type);
    genericExceptionTypes = method.getGenericExceptionTypes();

  } else if (methodOrConstructor instanceof Constructor) {
    Constructor<?> constructor = (Constructor<?>) methodOrConstructor;
    checkArgument(constructor.getDeclaringClass().isAssignableFrom(rawType),
        "%s does not construct a supertype of %s", constructor, type);
    genericExceptionTypes = constructor.getGenericExceptionTypes();

  } else {
    throw new IllegalArgumentException("Not a method or a constructor: " + methodOrConstructor);
  }

  return resolveAll(genericExceptionTypes);
}
 
Example 22
Project: phantom-pojos   File: DispatchingInvocationHandler.java View source code 6 votes vote down vote up
@Override
default Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (method.isDefault())
    {
        return ReflectionUtils.invokeDefault(proxy, method, args);
    }

    if (method.getDeclaringClass().isAssignableFrom(getClass())) {
        return method.invoke(this, args);
    }

    return invokeMissing(proxy, method, args);
}
 
Example 23
Project: xapi   File: ModelUtil.java View source code 5 votes vote down vote up
public static ModelManifest createManifest(final Class<? extends Model> cls) {
  final ModelManifest manifest = new ModelManifest(cls);
  final Set<Class<?>> allTypes = new LinkedHashSet<>();
  collectAllTypes(allTypes, cls);
  // Collect up all the fields that are user defined...
  for (final Class<?> type : allTypes) {
    if (type == Model.class) {
      continue;
    }
    final IsModel isModel = cls.getAnnotation(IsModel.class);
    String idField = isModel == null ? "id" : isModel.key().value();
    for (final Method method : type.getMethods()) {
      if (method.getDeclaringClass() != Model.class) {
        if (!manifest.hasSeenMethod(method.getName())) {
          final MethodData property = manifest.addProperty(method.getName(), idField, method.getAnnotation(GetterFor.class),
              method.getAnnotation(SetterFor.class), method.getAnnotation(DeleterFor.class));
          property.setIdField(idField);
          final Class<?> dataType;
          final Type genericType;
          if (property.isGetter(method.getName())) {
            // For a getter, we will determine the field type by the return type
            dataType = method.getReturnType();
            genericType = method.getGenericReturnType();
          } else {
            // For setters and deleters, we will determine the field type by the first parameter type.
            // However, a removeAll method may have no parameters, in which case we will have to wait.
            if (method.getParameterTypes().length > 0) {
              dataType = method.getParameterTypes()[0];
              genericType = method.getGenericParameterTypes()[0];
            } else {
              dataType = null;
              genericType = null;
            }
          }
          if (dataType != null) {
            final Class<?> oldType = property.getType();
            if (oldType != null && oldType != dataType) {
              throw new NotConfiguredCorrectly("Field "+property.getName()+" for "+cls+" has data type "
                  + "disagreement; already saw type "+oldType+" but now saw "+dataType+". Get/set/remove methods "
                  + "must have identical type information");
            }
            property.setType(dataType);
            Class[] erasedTypes = getErasedTypeParameters(genericType);
            property.setTypeParams(erasedTypes);
          }

          property.addAnnotations(method.getAnnotations());
        }
      }
    }
  }
  return manifest;
}
 
Example 24
Project: AdminCMD-Bukkit   File: MethodInfo.java View source code 5 votes vote down vote up
/**
 * Wraps a method as a MethodInfo object.
 *
 * @param method - the method to wrap.
 * @return The wrapped method.
 */
public static MethodInfo fromMethod(final Method method) {
        return new MethodInfo() {
                @Override
                public String getName() {
                        return method.getName();
                }

                @Override
                public Class<?>[] getParameterTypes() {
                        return method.getParameterTypes();
                }

                @Override
                public Class<?> getDeclaringClass() {
                        return method.getDeclaringClass();
                }

                @Override
                public Class<?> getReturnType() {
                        return method.getReturnType();
                }

                @Override
                public int getModifiers() {
                        return method.getModifiers();
                }

                @Override
                public Class<?>[] getExceptionTypes() {
                        return method.getExceptionTypes();
                }

                @Override
                public TypeVariable<?>[] getTypeParameters() {
                        return method.getTypeParameters();
                }

                @Override
                public String toGenericString() {
                        return method.toGenericString();
                }

                @Override
                public String toString() {
                        return method.toString();
                }

                @Override
                public boolean isSynthetic() {
                        return method.isSynthetic();
                }

                @Override
                public int hashCode() {
                        return method.hashCode();
                }

                @Override
                public boolean isConstructor() {
                        return false;
                }

                public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
                        //only Java 8
                        return null;
                }

                public Annotation[] getAnnotations() {
                        //only Java 8
                        return null;
                }

                public Annotation[] getDeclaredAnnotations() {
                        //only Java 8
                        return null;
                }
        };
}