雖然作爲問問題的答案是Java的Method.getAnnotation()
不考慮替代的方法,有時是有用的找到這些註釋。下面是我目前使用的Saintali的回答更完整的版本:
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;
}
}
此外,trutheality,* I *搜索之前,我問,我想出了這個頁面。恭喜,您現在已成爲搜索結果的一部分。這就是爲什麼這個網站在這裏。 :)另外,您的答案比翻閱該文檔要簡潔得多。 – Tustin2121 2013-03-26 15:10:58
有一個問題需要進一步...如果一個框架找到基於註解的方法,然後調用它,哪個版本的方法被調用?子類的方法應該重寫父類,但是是否需要使用反射調用? – 2014-08-21 13:53:55