注解的继承关键在于 @Inherited 注解
import java.lang.annotation.*;
@Target(value = {ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@Inherited
public @interface HasInherited {
String value() default "";
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value = ElementType.TYPE)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface NotInherited {
String value() default "";
}
@HasInherited("ParentDemo的注解,被@Inherited修饰")
@NotInherited("ParentDemo的注解,没有被@Inherited修饰")
public class ParentDemo {
}
@HasInherited("ChildDemo的注解,被@Inherited修饰")
public class ChildDemo extends ParentDemo{
}
import java.util.Arrays;
public class TestDemo {
public static void main(String[] args) {
System.out.println("ParentDemo类注解");
Arrays.stream(ParentDemo.class.getAnnotations()).forEach(System.out::println);
System.out.println();
System.out.println("childDemo");
Arrays.stream(ChildDemo.class.getAnnotations()).forEach(System.out::println);
}
}
如果,子类 ChildDemo 自身标注了 @HasInherited 注解,那么父类 ParentDemo 的 @HasInherited 注解就不会被继承。