元注解

元注解

好,开始!先带入一个熟悉的Java注解。

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

@Target、@Retention这两个注解与 其他*@Documented,@Inherited,@Repeatable,@Native是Java 8.0定义的6个标准元注解,其中@Repeatable@Native*是1.8新加的。

  1. @target 表示这个注解类型适用的上下文,看看枚举类型ElementType的值,以后看注解可以使用在哪些地方,就可以里面的值。
public enum ElementType {
 TYPE,                             //字段
 FIELD,                           //字段声明
 METHOD,                         //方法声明
 PARAMETER,                  //参数声明
 CONSTRUCTOR,             //构造函数声明
 LOCAL_VARIABLE,          //本地变量声明
 ANNOTATION_TYPE,     //注解类型声明
 PACKAGE,                        //包声明 
 TYPE_PARAMETER,       //类型参数声明
 TYPE_USE;                      //类型使用

 private ElementType() {
 }
}
  1. @Rentation 表示这个注解在什么时候存在,值如下,在说明一下,SOURCE值就是编译时候存在上面这个注解就用到,也用于lombok工作原理;CLASS存在的时间就是在编译之后,以及运行之前Dev这段时间;RUNTIME值表示这个注解会存在jvm里面,即可用反射。
public enum RetentionPolicy {
   SOURCE,         //在源文件中
   CLASS,         //在class文件存在
   RUNTIME;      //运行时候存在

   private RetentionPolicy() {
   }
}
  1. @Documented 表示javadoc或者其他简单工具会将该注解类型文档化
  2. @Inherited 表示该注解类型自动继承,比如说注解ZA带有@Inherited,类A有注解ZA,那么凡是A的子类都会有ZA这个注解。
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface InheritedAnnotation {
}
@InheritedAnnotation
public class A {
}
public class B extends A{
}
public class C extends B{
}
 System.out.println(A.class.getAnnotation(InheritedAnnotation.class));
 System.out.println(B.class.getAnnotation(InheritedAnnotation.class));
 System.out.println(C.class.getAnnotation(InheritedAnnotation.class));

输出结果

@importJAVASE.annotation.InheritedAnnotation()
@importJAVASE.annotation.InheritedAnnotation()
@importJAVASE.annotation.InheritedAnnotation()
  1. @Repeatable 这个声明这个注解修饰的类型注解是可以重复的。
@Test(value=1)
@Test(value=2)
private int num;
  1. @Native 声明属性是可以被native代码所引用的。
    Indicates that a field defining a constant value may be referenced from native code. The annotation may be used as a hint by tools that generate native header files to determine whether a header file is required, and if so, what declarations it should contain.

你可能感兴趣的:(注解)