Inherited元注解:普通注解并没有继承功能,@Inherited元注解可以让一个注解具有世袭制(继承),这个注解相对比较简单。
-
定义一个生命周期为RUNTIME的普通注解
package annotation.inherits; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface CommonAnotation { }
-
定义一个生命周期为RUNTIME、具有继承功能的注解。
package annotation.inherits; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface InheritAnotation { }
-
定义普通father类、son类。father类使用CommonAnotation注解修饰,son类继承父类。
//Father_Com.java package annotation.inherits; @CommonAnotation public class Father_Com { } //Son_Com.java package annotation.inherits; public class Son_Com extends Father_Com { }
-
定义继承father类、son类。father类使用InheritAnotation注解修饰,son类继承父类。
//Father_In.java package annotation.inherits; @InheritAnotation public class Father_In { } //Son_In.java package annotation.inherits; public class Son_In extends Father_In{ }
-
编写测试类,利用反射机制获取运行时这几个类的注解
package annotation.inherits; import java.lang.annotation.Annotation; public class Main { public static void main(String[] args) throws Exception{ Annotation[] f_c = Class.forName("annotation.inherits.Father_Com").getAnnotations(); Annotation[] s_c = Class.forName("annotation.inherits.Son_Com").getAnnotations(); System.out.println(f_c.length); System.out.println(s_c.length); Annotation[] f_i = Class.forName("annotation.inherits.Father_In").getAnnotations(); Annotation[] s_i = Class.forName("annotation.inherits.Son_In").getAnnotations(); System.out.println(f_i.length); System.out.println(s_i.length); } }
分析:可以看到父类实现了Inherited元注解,子类继承该父类。反射加载时也能获得到这个注解。