在定义Annotation型态时,您使用java.lang.annotation.Target可以定义其适 用之时机,在定义时可以指定java.lang.annotation.ElementType的列举值:
package java.lang.annotation;
public enum ElementType {
TYPE, // 适用 class, interface, enum
FIELD, // 适用 field
METHOD, // 适用 method
PARAMETER, // 适用 method 上之 parameter
CONSTRUCTOR, // 适用 constructor
LOCAL_VARIABLE, // 适用区域变量
ANNOTATION_TYPE, // 适用 annotation 型态
PACKAGE // 适用 package
}
举个例子来说,假设您定义Annotation只能适用于constructor与method:
package onlyfun.caterpillar;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD})
public @interface Debug {}
如果您尝试将Debug用于class上:
package onlyfun.caterpillar;
@Debug
public class SomeObject {
public void doSomething() {?
// ....?
}
}
则在编译时会发生以下的错误:
SomeObject.java:3: annotation type not applicable to this kind of declaration @Debug ^ 1 error