JDK 5提供的注解,除了Retention以外,还有另外三个,即Target 、Inherited 和 Documented。
Target 目标即Target注解用在哪里, 定义了注解使用的时机,即注解所适用的程序元素的种类。如果注解类型声明中不存在 Target 元注解,则声明的类型可以用在任一程序元素上。如果存在这样的元注解,则编译器强制实施指定的使用限制。
Target 定义如下:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
ElementType[] value();
}
可以看到,Target 只有一个value属性,类型为枚举类型ElementType。ElementType 声明如下:
public enum ElementType {
/** 注解可以用在类、接口(包括注解类型)或枚举声明 */
TYPE,
/** 字段声明(包括枚举常量) */
FIELD,
/** 方法声明 */
METHOD,
/** 参数声明 */
PARAMETER,
/** 构造方法声明 */
CONSTRUCTOR,
/** 局部变量声明 */
LOCAL_VARIABLE,
/** 注解类型声明 */
ANNOTATION_TYPE,
/** 包声明 */
PACKAGE
}
Documented注解表明制作javadoc时,是否将注解信息加入文档。如果注解在声明时使用了@Documented,则在制作javadoc时注解信息会加入javadoc。注解声明如下:
@Documented
@Retention(value=RUNTIME)
@Target(value=ANNOTATION_TYPE)//说明该注解只能在声明注解时使用,即元注解
public @interface Documented {}
Inherited 注解同样是元注解,声明如下:
@Documented
@Retention(value=RUNTIME)
@Target(value=ANNOTATION_TYPE)
public @interface Inherited {}
Inherited 注解表明注解是否会被子类继承,缺省情况是不继承的。当注解在声明时,使用了@Inherited注解,则该注解会被使用了该注解的类的子类所继承。
本文地址:https://www.stayed.cn/item/1585
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我