@Inherited
是一个元注解,专门用来修饰注解,被 @Inherited
修饰的注解具备继承传递性。
通过代码来验证,首先创建一个自定义注解,但是不加 @Inherited
修饰
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Version {
String value() default "1";
}
创建一个父类,使用 @Version
注解
@Version
public class TestParentBean {
public void sayHello() {
System.out.println("Hello parent bean");
}
}
创建一个子类,不使用注解
public class TestBean extends TestParentBean {
public void sayHello() {
System.out.println("Hello bean");
}
}
通过反射查找注解并打印
public class AnnotationTest {
public static void main(String[] args) throws Exception {
// 读取当前类及父类的注解
Annotation[] annotations = TestBean.class.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
System.out.println("-----------");
// 读取当前类的注解
annotations = TestBean.class.getDeclaredAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
}
}
输出结果如下,说明不管是通过 getAnnotations()
方法或者是 getDeclaredAnnotations()
方法,都不能获取到父类的注解。
-----------
现在为 Version
添加 @Inherited
元注解
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Version {
String value() default "1";
}
再次执行输出结果如下,可以看到 getAnnotations()
是可以获取到父类的有 @Inherited
修饰的注解的,而 getDeclaredAnnotations()
则只能获取当前类的注解。
@test.annotation.Version(value=1)
-----------
注意:@Inherited 的适用范围
1、在接口上使用
@Inherited
修饰的注解,其实现类不会继承这个注解
2、父类的方法上使用@Inherited
修饰的注解,其子类不会继承这个注解