publicenum ElementType {/** 用于类 接口 枚举 Class, interface (including annotation type), or enum declaration */ TYPE,/** 作用于属性上 例如Spring中的 Autowired Field declaration (includes enum constants) */FIELD,/** Method declaration */METHOD,/** 用于方法的参数上 例如Spring的RequestParamFormal parameter declaration */PARAMETER,/** Constructor declaration */CONSTRUCTOR,/** Local variable declaration */LOCAL_VARIABLE,/** Annotation type declaration */ANNOTATION_TYPE,/** Package declaration */PACKAGE,/*** Type parameter declaration* 用于泛型类的实参上 * @since 1.8*/TYPE_PARAMETER,/**表示该注解可以用于任何地方. * Use of a type** @since 1.8*/TYPE_USE,/*** Module declaration.** @since 9*/MODULE }
3.1.2@Retention的作用
标注注解被保留的时间长短
用于定义注解的生命周期
Retention 的源码
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interfaceRetention{/*** Returns the retention policy.* @return the retention policy*/RetentionPolicy value(); }
RetentionPolicy 的源码, 定义了几种类型
publicenum RetentionPolicy {/**注解能在源文件(java文件)中保留, 编译后在class文件中被去除. 例如Override 也是用的@Retention(RetentionPolicy.SOURCE)进行修饰. * Annotations are to be discarded by the compiler.*/SOURCE,/**注解能在源文件(java文件)中保留, 编译后在class文件中也会保留. * Annotations are to be recorded in the class file by the compiler* but need not be retained by the VM at run time. This is the default* behavior.*/CLASS,/**能够在运行时获取该注解的相关信息. 例如Spring的Autowired注解, 通过反射将用到的bean实例注入进来. * Annotations are to be recorded in the class file by the compiler and* retained by the VM at run time, so they may be read reflectively.** @see java.lang.reflect.AnnotatedElement*/RUNTIME }