默认情况下,类注释不适用于扩展它们的类型。可以通过将@Inherited注释添加到注释定义中来更改
请考虑以下2个注释:
@Inherited @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface InheritedAnnotationType { }
和
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface UninheritedAnnotationType { }
如果这样注释了三个类:
@UninheritedAnnotationType class A { } @InheritedAnnotationType class B extends A { } class C extends B { }
运行此代码
System.out.println(new A().getClass().getAnnotation(InheritedAnnotationType.class)); System.out.println(new B().getClass().getAnnotation(InheritedAnnotationType.class)); System.out.println(new C().getClass().getAnnotation(InheritedAnnotationType.class)); System.out.println("_________________________________"); System.out.println(new A().getClass().getAnnotation(UninheritedAnnotationType.class)); System.out.println(new B().getClass().getAnnotation(UninheritedAnnotationType.class)); System.out.println(new C().getClass().getAnnotation(UninheritedAnnotationType.class));
将打印与此类似的结果(取决于注释的包):
null @InheritedAnnotationType() @InheritedAnnotationType() _________________________________ @UninheritedAnnotationType() null null
请注意,注释只能从类继承,而不能从接口继承。