java元注解

 
Retention注解
 
Retention(保留)注解说明,这种类型的注解会被保留到那个阶段. 有三个值:
1.RetentionPolicy.SOURCE —— 这种类型的Annotations只在源代码级别保留,编译时就会被忽略
2.RetentionPolicy.CLASS —— 这种类型的Annotations编译时被保留,在class文件中存在,但JVM将会忽略
3.RetentionPolicy.RUNTIME —— 这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用.
 
Java注解的示例1:
代码如下:
 @Retention(RetentionPolicy.RUNTIME)
 public @interface Test_Retention {
    String doTestRetention();
 }
 
在这个示例中, @Retention(RetentionPolicy.RUNTIME)注解表明 Test_Retention注解将会由虚拟机保留,以便它可以在运行时通过反射读取.
 
Documented 注解
 
Documented 注解表明这个注解应该被 javadoc工具记录. 默认情况下,javadoc是不包括注解的. 但如果声明注解时指定了 @Documented,则它会被 javadoc 之类的工具处理, 所以注解类型信息也会被包括在生成的文档中. 示例6进一步演示了使用 @Documented:
 
Java注解的示例2:
 
 
复制代码 代码如下:
 
 
 @Documented
 public @interface Test_Documented {
    String doTestDocument();
 }
接下来,像下面这样修改TestAnnotations类:
代码如下:
public class TestAnnotations {
    public static void main(String arg[]) {
       new TestAnnotations().doSomeTestRetention();
       new TestAnnotations().doSomeTestDocumented();
    }
    @Test_Retention (doTestRetention="保留注解信息测试")
    public void doSomeTestRetention() {
       System.out.printf("测试注解类型 'Retention'");
    }
    @Test_Documented(doTestDocument="Hello document")
    public void doSomeTestDocumented() {
       System.out.printf("测试注解类型 'Documented'");
    }
 }
 
现在,如果你使用 javadoc命令生成 TestAnnotations.html文件
从截图可以看到,文档中没有 doSomeTestRetention() 方法的 annotation-type信息()方法. 但是, doSomeTestDocumented() 方法的文档提供了注解的描述信息. 这是因为 @Documented标签被加到了Test_Documented注解上. 之前的注解Test_Retention并没有指定 @Documented 标记(tag).
 
Inherited作用是,使用此注解声明出来的自定义注解,在使用此自定义注解时,如果注解在类上面时,子类会自动继承此注解,否则的话,子类不会继承此注解。这里一定要记住,使用Inherited声明出来的注解,只有在类上使用时才会有效,对方法,属性等其他无效。
 

@Target:

   @Target说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了target可更加明晰其修饰的目标。

  作用:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
原文地址:https://www.cnblogs.com/yidiandhappy/p/7267985.html