下面的代码打印
@MyTestAnnotation():foo
对于 B 类和 C 类,MyTestAnnotation 是否指定为 @Inherited。 我认为只有指定 @Inherited 时注释才会被继承,并且默认注释继承行为是它们不会被继承。这里发生了什么?
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
public class AnnotationTest {
public static void main(String[] args) {
B b = new B();
C c = new C();
printMethdodsAndAnotations(b);
printMethdodsAndAnotations(c);
}
public static void printMethdodsAndAnotations(Object obj) {
Method[] methods = obj.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
Annotation[] annotations = methods[i].getAnnotations();
if (annotations.length > 0)
{
for (int j = 0; j < annotations.length; j++) {
System.out.println(annotations[j].toString() + ":" + methods[i].getName());
}
}
}
}
}
//@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyTestAnnotation {
}
abstract class A {
public abstract void foo();
}
class B extends A {
@MyTestAnnotation
public void foo() {
System.out.println("B's foo()");
}
}
class C extends B {
public void foo2() {
System.out.println("C's foo()");
}
}
最佳答案
由于 C
不会重写 B#foo()
,因此它继承了它。它还继承了它附带的一切,即。注释。如果添加
public void foo() {
System.out.println("C's foo()");
}
到C
,它不会有注释。
如果您打印出来,您会注意到
System.out.println(annotations[j].toString() + ":" + methods[i]); // instead of methods[i].getName()
它打印
@MyTestAnnotation():public void com.sc.B.foo()
该方法是B
的方法。 B#foo
大量使用 @MyTestAnnotation
进行注释。
此外,@Inherited
用于类注释。正如 javadoc 所说
Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class.
关于java - 注释继承表现得很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21606709/