@Target:
@Target說明了Annotation所修飾的對象範圍:Annotation可被用於 packages、types(類、接口、枚舉、Annotation類型)、類型成員(方法、構造方法、成員變量、枚舉值)、方法參數和本地變量(如循環變量、catch參數)。在Annotation類型的聲明中使用了target可更加明晰其修飾的目標。
作用:用於描述註解的使用範圍(即:被描述的註解可以用在什麼地方)
取值(ElementType)有
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
1 |
|
@Target(ElementType.TYPE_PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface TypeParameterAnnotation {
}
// 如下是該註解的使用例子
public class TypeParameterClass<@TypeParameterAnnotation T> {
public <@TypeParameterAnnotation U> T foo(T t) {
return null;
}
}
ElementType.TYPE_USE(Use of a type) 能標註任何類型名稱,包括上面這個(ElementType.TYPE_PARAMETER的),栗子如下:
public class TestTypeUse {
@Target(ElementType.TYPE_USE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TypeUseAnnotation {
}
public static @TypeUseAnnotation class TypeUseClass<@TypeUseAnnotation T> extends @TypeUseAnnotation Object {
public void foo(@TypeUseAnnotation T t) throws @TypeUseAnnotation Exception {
}
}
// 如下註解的使用都是合法的
@SuppressWarnings({ "rawtypes", "unused", "resource" })
public static void main(String[] args) throws Exception {
TypeUseClass<@TypeUseAnnotation String> typeUseClass = new @TypeUseAnnotation TypeUseClass<>();
typeUseClass.foo("");
List<@TypeUseAnnotation Comparable> list1 = new ArrayList<>();
List<? extends Comparable> list2 = new ArrayList<@TypeUseAnnotation Comparable>();
@TypeUseAnnotation String text = (@TypeUseAnnotation String)new Object();
java.util. @TypeUseAnnotation Scanner console = new java.util.@TypeUseAnnotation Scanner(System.in);
}
}