定义
用来约束注解生命周期的元注解。
@Retention(RetentionPolicy.RUNTIME)
@Retention的值分为:
源码级别(source)、类文件级别(class)、运行时级别(runtime) 等三个级别。
注释生命周期的使用情景
- SOURCE:注释将被编译器丢弃。
如@Override只存在于源码,不参与编译- CLASS:注释由编译器记录在类文件中,但是不需要在运行时被VM保留。
- RUNTIME:注释由编译器和在类文件中记录,虚拟机在运行时保留它们,因此可以反射地读取它们。 如SpringMvc中的@Autowired、@RequestMapping等注解;源码、class文件和执行的时候都有注解的信息。
源码
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
/**
* 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,
/**
* 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
}