自定义的注解的存活范围(生命周期):默认是CLASS。
@Target ElementType.class
描述注解的使用范围:
l ElementType.ANNOTATION_TYPE 应用于注释类型
l ElementType.CONSTRUCTOR 应用于构造函数
l ElementType.FIELD 应用于字段或属性
l ElementType.LOCAL_VARIABLE 应用于局部变量
l ElementType.METHOD 应用于方法级
l ElementType.PACKAGE 应用于包声明
l ElementType.PARAMETER 应用于方法的参数
l ElementType.TYPE 应用于类的元素
======================================================
@Retention RetentionPolicy.class
定义了该注解被保留的时间长短,某些注解仅出现在源代码中,而被编译器丢弃;
而另一些却被编译在class文件中; 编译在class文件中的注解可能会被虚拟机忽略,而另一些在class被装载时将被读取。
为何要分有没有呢?没有时,反射就拿不到,从而就无法去识别处理。
l SOURCE 在源文件中有效(即源文件保留)
l CLASS 在class文件中有效(即class保留)
l RUNTIME 在运行时有效(即运行时保留)
代码示例:
package day20200822;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation {
String name() default "fanjia";
int id() default 1;
Class clazz() default Object.class;
}