- 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
- }
这是一个enum类型,共有三个值,分别是SOURCE,CLASS 和 RUNTIME.
SOURCE代表的是这个Annotation类型的信息只会保留在程序源码里,源码如果经过了编译之后,Annotation的数据就会消失,并不会保留在编译好的.class文件里面。
ClASS的意思是这个Annotation类型的信息保留在程序源码里,同时也会保留在编译好的.class文件里面,在执行的时候,并不会把这一些信息加载到虚拟机(JVM)中去.注意一下,当你没有设定一个Annotation类型的Retention值时,系统默认值是CLASS.
第三个,是RUNTIME,表示在源码、编译好的.class文件中保留信息,在执行的时候会把这一些信息加载到JVM中去的.
- public enum ElementType {
- /** Class, interface (including annotation type), or enum declaration */
- TYPE,
- /** Field declaration (includes enum constants) */
- FIELD,
- /** Method declaration */
- METHOD,
- /** Parameter declaration */
- PARAMETER,
- /** Constructor declaration */
- CONSTRUCTOR,
- /** Local variable declaration */
- LOCAL_VARIABLE,
- /** Annotation type declaration */
- ANNOTATION_TYPE,
- /** Package declaration */
- PACKAGE
- }
另外,从1的源代码可以看出,@Target自己也用了自己来声明自己,只能用在ANNOTATION_TYPE之上.
如果一个Annotation类型没有指明@Target使用在哪些元素上,那么它可以使用在任何元素之上,这里的元素指的是上面的八种类型.