While the answer to the question asked is that Java Method.getAnnotation() does not consider overridden methods, it is sometimes useful to find these annotations. Here is a more complete version of Saintali's answer that I am currently using:
public static <A extends Annotation> A getInheritedAnnotation( Class<A> annotationClass, AnnotatedElement element) { A annotation = element.getAnnotation(annotationClass); if (annotation == null && element instanceof Method) annotation = getOverriddenAnnotation(annotationClass, (Method) element); return annotation; } private static <A extends Annotation> A getOverriddenAnnotation( Class<A> annotationClass, Method method) { final Class<?> methodClass = method.getDeclaringClass(); final String name = method.getName(); final Class<?>[] params = method.getParameterTypes(); // prioritize all superclasses over all interfaces final Class<?> superclass = methodClass.getSuperclass(); if (superclass != null) { final A annotation = getOverriddenAnnotationFrom(annotationClass, superclass, name, params); if (annotation != null) return annotation; } // depth-first search over interface hierarchy for (final Class<?> intf : methodClass.getInterfaces()) { final A annotation = getOverriddenAnnotationFrom(annotationClass, intf, name, params); if (annotation != null) return annotation; } return null; } private static <A extends Annotation> A getOverriddenAnnotationFrom( Class<A> annotationClass, Class<?> searchClass, String name, Class<?>[] params) { try { final Method method = searchClass.getMethod(name, params); final A annotation = method.getAnnotation(annotationClass); if (annotation != null) return annotation; return getOverriddenAnnotation(annotationClass, method); } catch (final NoSuchMethodException e) { return null; } }
Trevor Robinson Jun 24 '13 at 17:08 2013-06-24 17:08
source share