@Inherited
表示注释类型自动继承。 如果在注释类型声明中存在继承的元注释,并且用户在类声明上查询注释类型,并且类声明没有此类型的注释,则该类的超类将自动查询注释类型。 将重复此过程,直到找到此类型的注释,或者达到类层次结构(Object)的顶部。 如果没有超类具有此类型的注释,则查询将指示所讨论的类没有这样的注释。
请注意,如果使用注释类型来注释除类之外的任何内容,则此元注释类型不起作用。 还要注意,这个元注释只会导致从超类继承注释; 已实现的接口上的注释无效。
@Documented
@Retention(value=RUNTIME)
@Target(value=ANNOTATION_TYPE)
public @interface Inherited
示例
/**
* 声明的此注解使用了Inherited元注解,表示此注解用在类上时,会被子类所继承
* @author crazy
*/
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface InheritedTest {
String value();
}
/**
* 声明的此注解没有使用Inherited元注解,表示此注解用在类上时,不会被子类所继承
* @author crazy
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface InheritedTest2 {
String value();
}
/**
* 父类
* @author crazy
*/
@InheritedTest("使用Inherited的注解 class")
@InheritedTest2("未使用Inherited的注解 class")
public class Parent {
@InheritedTest("使用Inherited的注解 method")
@InheritedTest2("未使用Inherited的注解 method")
public void method(){
}
@InheritedTest("使用Inherited的注解 method2")
@InheritedTest2("未使用Inherited的注解 method2")
public void method2(){
}
@InheritedTest("使用Inherited的注解 field")
@InheritedTest2("未使用Inherited的注解 field")
public String a;
}
/**
* 子类 只继承了一个method方法
* @author crazy
*/
public class Child extends Parent {
@Override
public void method() {
}
}
/**
* 通过反射进行测试
* @author crazy
*/
public class test {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, NoSuchFieldException {
Class<Child> clazz = Child.class;
//对类进行测试
System.out.println("对类进行测试");
if(clazz.isAnnotationPresent(InheritedTest.class)){
System.out.println(clazz.getAnnotation(InheritedTest.class).value());
}
if(clazz.isAnnotationPresent(InheritedTest2.class)){
System.out.println(clazz.getAnnotation(InheritedTest2.class).value());
}
System.out.println();
//对方法 进行测试
System.out.println("对方法进行测试");
Method method = clazz.getMethod("method", null);
if(method.isAnnotationPresent(InheritedTest.class)){
System.out.println(method.getAnnotation(InheritedTest.class).value());
}
if(method.isAnnotationPresent(InheritedTest2.class)){
System.out.println(method.getAnnotation(InheritedTest2.class).value());
}
System.out.println();
//对方法2 进行测试
System.out.println("对方法2进行测试");
Method method2 = clazz.getMethod("method2", null);
if(method2.isAnnotationPresent(InheritedTest.class)){
System.out.println(method2.getAnnotation(InheritedTest.class).value());
}
if(method2.isAnnotationPresent(InheritedTest2.class)){
System.out.println(method2.getAnnotation(InheritedTest2.class).value());
}
System.out.println();
//对属性测试
System.out.println("对属性进行测试");
Field field = clazz.getField("a");
if(field.isAnnotationPresent(InheritedTest.class)){
System.out.println(field.getAnnotation(InheritedTest.class).value());
}
if(field.isAnnotationPresent(InheritedTest2.class)){
System.out.println(field.getAnnotation(InheritedTest2.class).value());
}
}
}
对类进行测试
使用Inherited的注解 class
对方法进行测试
对方法2进行测试
使用Inherited的注解 method2
未使用Inherited的注解 method2
对属性进行测试
使用Inherited的注解 field
未使用Inherited的注解 field
通过对注解上使用元注解Inherited声明出的注解,在使用时用在类上,可以被子类所继承,对属性或方法无效