Overview
本小节将会介绍
- Java的四种元注解
四种元注解
1、被@Target修饰的注解,表明了注解的使用范围
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
ElementType[] value();
}
public enum ElementType {
/** 类,接口(包括注解类型)或enum声明 */
TYPE,
/** 域声明(包括 enum 实例) */
FIELD,
/** 方法声明 */
METHOD,
/** 参数声明 */
PARAMETER,
/** 构造器声明 */
CONSTRUCTOR,
/** 局部变量声明 */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** 包声明 */
PACKAGE,
/**
* 类型参数声明
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* 类型的使用
*
* @since 1.8
*/
TYPE_USE
}
2、被@Retention的注解,表明了注解的保存范围
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
RetentionPolicy value();
}
public enum RetentionPolicy {
/**
* 源代码:即此注解只能保存在源代码中
* 当编译时,会被丢弃
*/
SOURCE,
/**
* class文件:即此注解可以在class文件中保留
* 但会被jvm丢弃
*/
CLASS,
/**
* 运行期:即此注解可以在运行时保留
* 可以通过反、反射获得
*/
RUNTIME
}
3、被@Documented修饰的注解,表明可以被javadoc工具提取成文档
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}
4、被@Inherited修饰的注解,表明子类可以继承父类的注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}