我有一个父类Parent
和一个子类Child
,定义如下:
class Parent {
@MyAnnotation("hello")
void foo() {
// implementation irrelevant
}
}
class Child extends Parent {
@Override
foo() {
// implementation irrelevant
}
}
如果我获得一个对Child::foo
的Method
引用,childFoo.getAnnotation(MyAnnotation.class)
会给我@MyAnnotation
吗?或者它会是null
我更感兴趣的是注解如何或是否与Java继承一起工作。
发布于 2012-05-20 21:20:44
您已经找到了答案: JDK中没有提供方法注释继承。
但是,在超类链中搜索带注释的方法也很容易实现:
/**
* Climbs the super-class chain to find the first method with the given signature which is
* annotated with the given annotation.
*
* @return A method of the requested signature, applicable to all instances of the given
* class, and annotated with the required annotation
* @throws NoSuchMethodException If no method was found that matches this description
*/
public Method getAnnotatedMethod(Class<? extends Annotation> annotation,
Class c, String methodName, Class... parameterTypes)
throws NoSuchMethodException {
Method method = c.getMethod(methodName, parameterTypes);
if (method.isAnnotationPresent(annotation)) {
return method;
}
return getAnnotatedMethod(annotation, c.getSuperclass(), methodName, parameterTypes);
}
发布于 2015-05-08 21:07:00
使用Spring Core,您可以通过
发布于 2013-06-25 01:08:49
虽然问题的答案是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;
}
}
https://stackoverflow.com/questions/10082619
复制相似问题