1. 程式人生 > >java元註解 @Target註解用法

java元註解 @Target註解用法

@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

  

ElementType.TYPE_PARAMETER(Type parameter declaration) 用來標註型別引數, 栗子如下:
@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 
[email protected]
Scanner(System.in); } }