注解的注解就是为注解自己提供额外的信息,从而约束或加强注解的能力。其中包含有 @Documented 、 @Inherited 、 @Target 、 Retention 4种注解。 @Target注解 :用于约束被描述的注解的使用范围,当被描述的注解超出使用范围则编译失败。 // 约束@MyAnnotation的做用范围是函数和构造函数 @Target(ElementType.METHOD, ElementType.CONSTRUCTOR) public @interface MyAnnotation{} @Retention注解 :用于约束被描述的注解的做用范围,注解的做用范围有三个,分别为 1. RetentionPolicy.SOURCE ,做用范围为源码,就是仅存在于java文件中,当执行 javac 命令时将会去除该注解。java
2. RetentionPolicy.CLASS ,做用范围为二进制码,就是存在于class文件中,当执行 java 命令时会去除该注解。函数
3. RetentionPolicy.RUNTIME ,做用范围为运行时,就是咱们能够经过反射动态获取该注解。 @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation{} @Documented注解 :用于指定javadoc生成API文档时显示该注解信息 @Inherited注解 :用于指定被描述的注解能够被其所描述的类的子类继承。默认状况 // 默认注解不会被子类继承 @MyAnnotation public class Parent{} // Son并无继承注解MyAnnotation public class Son extends Parent{} 经过 @Inherited 子类将会继承父类的 @MyAnnoation注解 。.net
4、读取注解 经过反射咱们能够获取类、函数等上的注解信息。 复制代码 @Retention(RetentionPolicy.RUNTIME)继承
@Target(ElementType.CLASS)文档
@Documented public @interface MyAnnotaion{ String value() default "hello world"; } @MyAnnotation public class Test{ public static void main(String[] args){get
MyAnnotation ma = Test.class.getAnnotation(MyAnnotation.class);源码
System.out.println(ma.value());it
// 获取自身和从父类继承的注解io
Annotation[] annotations = Test.class.getAnnotations();编译
// 仅获取自身的注解
Annotation[] annotations = Test.class.getDeclaredAnnotations(); } }