brainslug.util.ReflectionUtil Maven / Gradle / Ivy
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 Method getFirstMethodAnnotatedWith(final Class> type, final Class extends Annotation> 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 method;
}
}
// move to the upper class in the hierarchy in search for more methods
klass = klass.getSuperclass();
}
throw new NoSuchMethodError(String.format("annotation %s not found on any method of class %s", annotation.getName(), type.getName()));
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy