Mentre la risposta alla domanda, come ha chiesto è che Java di Method.getAnnotation()
non considera i metodi sostituiti, a volte è utile per trovare queste annotazioni. Ecco una versione più completa della risposta di Saintali che sono attualmente in uso:
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;
}
}
fonte
2013-06-24 17:08:49
Inoltre, trutheality, * io * cercato prima ho chiesto, e ho trovato questa pagina Complimenti, ora fai parte di quei risultati di ricerca. Ecco perché questo sito web è qui. :) Inoltre, la tua risposta è molto più concisa che guardare attraverso quel documento. – Tustin2121
Una domanda per approfondire questo ... se un framework trova il metodo basato sull'annotazione e quindi lo richiama, quale versione del metodo viene invocata? Il metodo della classe figlio dovrebbe sovrascrivere il genitore ma è rispettato con l'invocazione riflessiva? –