java.lang.annotation.RetentionPolicy 学习记录(翻译解析)
注意:以下文章仅作为个人学习记录。相关翻译和个人理解描述正确性仍需斟酌,文章仅供参考。
1.概念
概念:注解保留策略。枚举类型常量描述了保留注解的一些策略。它们被用来与元注解类型组合使用,标明注解将会被保留多久。
SOURCE
:
注解将会被编译器丢弃。(编译完成丢弃)
CLASS
:
注解将会被编译器记录在类文件中。但是在运行时,不会被虚拟机保留。这是默认行为(编译完成保留,运行时丢弃)
RUNTIME
:
注解将会被编译器记录在类文件中,同时在运行时会被虚拟机保留,所以它们可以被反射地读取。(编译,运行都保留,可反射获取)
2.用途
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
boolean required() default true;
}
源码:
package java.lang.annotation;
/**
* Annotation retention policy. The constants of this enumerated type
* describe the various policies for retaining annotations. They are used
* in conjunction with the {@link Retention} meta-annotation type to specify
* how long annotations are to be retained.
*
* @author Joshua Bloch
* @since 1.5
*/
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
}