元注解可以认为是注解的注解。
(我们在定义注解时,可以通过元注解指定注解的保留策略、作用目标、javadoc包含以及子类继承。)
内置的元注解有4个,具体如下:
1、@Retention
2、@Target
3、@Document
4、@Inherited
一、@Retention:标识注解的保留策略
-
@Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含
-
@Retention(RetentionPolicy.CLASS) // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
-
@Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
-
-
三个阶段生命周期长度 SOURCE < CLASS < RUNTIME,生命周期长的一定能作用到生命周期短的阶段。
-
如果需要在RUNTIME阶段动态获取注解,那只能用RUNTIME注解
-
如果在编译时进行一些预处理操作,就用CLASS注解
-
如果只是做一些检查性操作,比如@Override 和 @SuppressWarnings,可以选用SOURCE注解。
-
❤️ 源码如下:
public @interface Retention {
/**
* Returns the retention policy.
* @return the retention policy
*/
RetentionPolicy value();
}
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,
RUNTIME
}
二、@Target:定义注解的作用目标
@Target(ElementType.TYPE) //接口、类、枚举、注解
@Target(ElementType.FIELD) //字段、枚举的常量
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法参数
@Target(ElementType.CONSTRUCTOR) //构造函数
@Target(ElementType.LOCAL_VARIABLE)//局部变量
@Target(ElementType.ANNOTATION_TYPE)//注解
@Target(ElementType.PACKAGE) ///包
源码如下:
public @interface Target {
/**
* Returns an array of the kinds of elements an annotation type
* can be applied to.
* @return an array of the kinds of elements an annotation type
* can be applied to
*/
ElementType[] value();
}
public enum ElementType {
/** 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
}
三、@Document:说明该注解将被包含在Javadoc中
用法示例:
@Documented
public @interface check {
}
源码:
public @interface Documented {
}
四、@Inherited:说明子类可以继承父类中的该注解
用法示例:
@Inherited
public @interface check {
}
源码:
public @interface Inherited {
}