Tra*_*ebb 63 java inheritance overriding annotations
我有一个父类Parent
和一个子类Child
,由此定义:
class Parent {
@MyAnnotation("hello")
void foo() {
// implementation irrelevant
}
}
class Child {
@Override
foo() {
// implementation irrelevant
}
}
Run Code Online (Sandbox Code Playgroud)
如果我获得Method
参考Child::foo
,childFoo.getAnnotation(MyAnnotation.class)
会给我@MyAnnotation
吗?还是会的null
?
我更感兴趣的是注释如何或是否与Java继承一起使用.
tru*_*ity 76
从http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations.html#annotation-inheritance逐字复制:
注释继承
理解与注释继承相关的规则很重要,因为它们基于注释的存在与否而对连接点匹配产生影响.
默认情况下,不会继承注释.鉴于以下计划
@MyAnnotation
class Super {
@Oneway public void foo() {}
}
class Sub extends Super {
public void foo() {}
}
Run Code Online (Sandbox Code Playgroud)
然后
Sub
没有MyAnnotation
注释,并且Sub.foo()
不是一个@Oneway
方法,尽管它覆盖了Super.foo()
哪个是.如果注释类型具有元注释,
@Inherited
则类上的该类型的注释将导致注释被子类继承.因此,在上面的示例中,如果MyAnnotation
类型具有@Inherited
属性,那么Sub
将具有MyAnnotation
注释.
@Inherited
当用于注释除类型之外的任何内容时,注释不会被继承.实现一个或多个接口的类型永远不会从它实现的接口继承任何注释.
Sai*_*ali 11
您已经找到了答案: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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
30467 次 |
最近记录: |