All Downloads are FREE. Search and download functionalities are using the official Maven repository.

brainslug.util.ReflectionUtil Maven / Gradle / Ivy

The newest version!
package brainslug.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ReflectionUtil {
  /**
   * taken from http://stackoverflow.com/questions/6593597/java-seek-a-method-with-specific-annotation-and-its-annotation-element
   */
  public static Option getFirstMethodAnnotatedWith(final Class type, final Class annotation) {
    Class klass = type;
    while (klass != Object.class) { // need to iterated thought hierarchy in order to retrieve methods from above the current instance
      // iterate though the list of methods declared in the class represented by klass variable, and add those annotated with the specified annotation
      final List allMethods = new ArrayList(Arrays.asList(klass.getDeclaredMethods()));
      for (final Method method : allMethods) {
        if (annotation == null || method.isAnnotationPresent(annotation)) {
          Annotation annotInstance = method.getAnnotation(annotation);
          return Option.of(method);
        }
      }
      // move to the upper class in the hierarchy in search for more methods
      klass = klass.getSuperclass();
    }
    return Option.empty();
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy