元注解(注解的注解)

元注解(注解的注解)

  a. @Retention 
   它是被定义在一个注解类的前面,用来说明该注解的生命周期。
   它有以下参数: 
      RetentionPolicy.SOURCE:指定注解只保留在源文件当中。
      RetentionPolicy.CLASS:指定注解只保留在class文件中。(缺省)
      RetentionPolicy.RUNTIME:指定注解可以保留在程序运行期间。
   b. @Target 
   它是被定义在一个注解类的前面,用来说明该注解可以被声明在哪些元素前。(默认可以放在任何元素之前)
   它有以下参数: 
    ElementType.TYPE:说明该注解只能被声明在一个类、接口、枚举前。 
    ElementType.FIELD:说明该注解只能被声明在一个类的字段前。
    ElementType.METHOD:说明该注解只能被声明在一个类的方法前。
    ElementType.PARAMETER:说明该注解只能被声明在一个方法参数前。 
    ElementType.CONSTRUCTOR:说明该注解只能声明在一个类的构造方法前。
    ElementType.LOCAL_VARIABLE:说明该注解只能声明在一个局部变量前。
    ElementType.ANNOTATION_TYPE:说明该注解只能声明在一个注解类型前。
    ElementType.PACKAGE:说明该注解只能声明在一个包名前。

  c. @Inherited 表明该注解将会被子类继承。

     需要说明的是,加上该元注解的注解,只有用在类元素上才有效果。这是在JDK总的原话:

    Note that this meta-annotation type has no effect if the annotated
    type is used to annotate anything other than a class. Note also
    that this meta-annotation only causes annotations to be inherited
    from superclasses; annotations on implemented interfaces have no
    effect

    但是在其他元素上的注解,只要你没有覆盖父类中的元素,是会继承过来的。这就是为什么有getDeclaredAnnotations()和getAnnotations()的原因。

   d. @Documented

    表明在生成JavaDoc文档时,该注解也会出现在javaDoc文档中。

posted @ 2018-12-19 09:55  9102_Struggle  阅读(1699)  评论(0编辑  收藏  举报