Inherited元注释:普通注释没有继承功能。 @Inherited元注释允许单个注释具有世袭(继承)。 这个评论比较简单。
定义生命周期为RUNTIME的普通注释
package annotation.inherits; import Java.lang.annotation.inherited; import Java.lang.annotation.retention; import Java.lang.annotation.retention policy; @ retention (retention policy.runtime ) public @ interfacecommonanotation { }定义生命周期在runtime中具有继承功能的注释。
package annotation.inherits; import Java.lang.annotation.inherited; import Java.lang.annotation.retention; import Java.lang.annotation.retention policy; @ retention (retention policy.runtime ) inherited public @ interfaceinheritanotation { }定义了一般的father类、son类。 father类由CommonAnotation注释限定,son类继承父类。
//father _ com.javapackageannotation.inherits; @ commonanotationpublicclassfather _ com { }//son _ com.javapackageannotation.inherits; public class son _ comextendsfather _ com { }定义继承father类、son类。 father类由InheritAnotation注释限定,son类继承父类。
//father _ in.javapackageannotation.inherits; @ inheritanotationpublicclassfather _ in { }//son _ in.javapackageannotation.inherits; public class son _ inextendsfather _ in { }创建测试类,并使用反射机制获取这些类在运行时的注释
package annotation.inherits; import Java.lang.annotation.annotation; 公共类主(publicstaticvoidmain (string [ ] args ) throwsexception ) annotation ) f_c=class.forname ) 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 meta注释,而子类继承了父类。 在反射加载时也可以获取此注释。