如何Java方法的注释与方法重载一起工作? [英] How do Java method annotations work in conjunction with method overriding?
问题描述
我有一个父类父
和一个子类儿童
,这样定义的:
类父{
@MyAnnotation(你好)
无效美孚(){
//执行无关
}
}
类儿童{
@覆盖
富(){
//执行无关
}
}
如果我获得方法
参照儿童:: foo的
,将 childFoo。 getAnnotation(MyAnnotation.class)
给我 @MyAnnotation
?还是会空
?
我有兴趣更加广泛的如何或者是否标注适用于Java继承。
我用谷歌搜索Java注释继承,我发现(从逐字复制<一个href=\"http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations.html#annotation-inheritance\">http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations.html#annotation-inheritance):
注释继承
明白与注释的继承规则,因为这些对基于注释的presence或无连接点匹配的轴承是非常重要的。
在默认情况下的注解是不能继承。考虑下面的程序
块引用>@MyAnnotation
类超级{
@OneWay公共无效美孚(){}
} 子类扩展超级{
公共无效美孚(){}
}
然后
子
不具有MyAnnotation
注释和Sub.foo()
不是@Oneway
方法,尽管它覆盖的事实Super.foo()
是
如果注释类型有元注释
@Inherited
那么该类型的类的注释将导致标注由子类继承。因此,在上面的例子中,如果MyAnnotation
类型有@Inherited
属性,那么子
将有MyAnnotation
注释。
用来注释不是类型以外的任何时候
@Inherited
注释不继承。从未实现一个或多个接口,A型继承它实现了接口的任何注解。
块引用>你问之前,请搜索。
I have a parent class
Parent
and a child classChild
, defined thus:class Parent { @MyAnnotation("hello") void foo() { // implementation irrelevant } } class Child { @Override foo() { // implementation irrelevant } }
If I obtain a
Method
reference toChild::foo
, willchildFoo.getAnnotation(MyAnnotation.class)
give me@MyAnnotation
? Or will it benull
?I'm interested more generally in how or whether annotation works with Java inheritance.
解决方案I Googled "Java annotation inheritance" and I found (copied verbatim from http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations.html#annotation-inheritance):
Annotation Inheritance
It is important to understand the rules relating to inheritance of annotations, as these have a bearing on join point matching based on the presence or absence of annotations.
By default annotations are not inherited. Given the following program
@MyAnnotation class Super { @Oneway public void foo() {} } class Sub extends Super { public void foo() {} }
Then
Sub
does not have theMyAnnotation
annotation, andSub.foo()
is not an@Oneway
method, despite the fact that it overridesSuper.foo()
which is.If an annotation type has the meta-annotation
@Inherited
then an annotation of that type on a class will cause the annotation to be inherited by sub-classes. So, in the example above, if theMyAnnotation
type had the@Inherited
attribute, thenSub
would have theMyAnnotation
annotation.
@Inherited
annotations are not inherited when used to annotate anything other than a type. A type that implements one or more interfaces never inherits any annotations from the interfaces it implements.Please search before you ask.
这篇关于如何Java方法的注释与方法重载一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!