首先,元注解是指标注在注解上的注解...有点拗口
@Retention :定义该注解的保留级别
其中@Retention(RetentionPolicy.*)的RetentionPolicy是该元注解的枚举属性,有三个值
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
}
三个值对应三个级别:
1.SOURCE 即该注解只存在于源码中,编译成class文件的时候就被转换成响应的代码了...
2.CLASS 即该注解存在于源码和class文件中,运行时不存在
3.RUNTIME 即该注解存在于源码、class文件、运行时
三者的lifecycle:SOURCE<CLASS<RUNTIME 即后者能作用到的范围,前者亦可。
注:利用反射机制获取Class的注解时,只有RUNTIME的注解才能被获取到。