gpt4 book ai didi

java - Java 方法注释如何与方法覆盖结合使用?

转载 作者:IT老高 更新时间:2023-10-28 13:53:36 24 4
gpt4 key购买 nike

我有一个父类 Parent 和一个子类 Child,定义如下:

class Parent {
@MyAnnotation("hello")
void foo() {
// implementation irrelevant
}
}
class Child extends Parent {
@Override
foo() {
// implementation irrelevant
}
}

如果我获得 Child::fooMethod 引用,childFoo.getAnnotation(MyAnnotation.class) 会给我 @MyAnnotation?还是null

我对注解如何或是否适用于 Java 继承更感兴趣。

最佳答案

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 the MyAnnotation annotation, and Sub.foo() is not an @Oneway method, despite the fact that it overrides Super.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 the MyAnnotation type had the @Inherited attribute, then Sub would have the MyAnnotation 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.

关于java - Java 方法注释如何与方法覆盖结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10082619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com