一、Target目标
@Target:作用:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
Annotations 注解
public enum ElementType {
/**用于描述类、接口(包括注解类型) 或enum声明 Class, interface (including annotation type), or enum declaration */
TYPE,
/** 用于描述域 Field declaration (includes enum constants) */
FIELD,
/**用于描述方法 Method declaration */
METHOD,
/**用于描述参数 Formal parameter declaration */
PARAMETER,
/**用于描述构造器 Constructor declaration */
CONSTRUCTOR,
/**用于描述局部变量 Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/**用于描述包 Package declaration */
PACKAGE,
/**
* 用来标注类型参数 Type parameter declaration
* @since 1.8
*/
TYPE_PARAMETER,
/**
*能标注任何类型名称 Use of a type
* @since 1.8
*/
TYPE_USE
}
例如:
@Target(ElementType.TYPE_PARAMETER) //用来标注类型参数
@Retention(RetentionPolicy.RUNTIME)
public @interface TypeParameterAnnotation {
}
例如:
public class TestTypeUse {
@Target(ElementType.TYPE_USE) // 能标注任何类型名称
@Retention(RetentionPolicy.RUNTIME)
public @interface TypeUseAnnotation {
}
二、@Retention保留
@Retention定义了该Annotation被保留的时间长短:
1.某些Annotation(注解)仅出现在源代码中,而被编译器丢弃;
2.另一些却被编译在class文件中,注解保留在class文件中,在加载到JVM虚拟机时丢弃,这是默认行为,所以没有用Retention注解的注解,都会采用这种策略
3.而另一些在class被装载时将被读取,注解保留在程序运行期间,此时可以通过反射获得定义在某个类上的所有注解
作用:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(即:被描述的注解在什么范围内有效)
取值(RetentionPoicy)有:
1.SOURCE:在源文件中有效(即源文件保留)
2.CLASS:在class文件中有效(即class保留)
3.RUNTIME:在运行时有效(即运行时保留)
Retention meta-annotation类型有唯一的value作为成员
RateLimit 注解的的RetentionPolicy的属性值是RUNTIME,这样注解处理器可以通过反射,获取到该注解的属性值,从而去做一些运行时的逻辑处理