首頁  >  文章  >  Java  >  09.Java 基礎 - 註解

09.Java 基礎 - 註解

黄舟
黄舟原創
2017-02-27 10:38:121185瀏覽

基本概念

Annotion (註解)是一個接口,程式可以透過反射來取得指定程式元素的Annotion 對象,然後透過Annotion 物件來取得註解裡面的元資料。

根據註解的使用方法和用途,我們可以將 Annotation 分為三類:系統註解,元註解,自訂註解。


系統註解

系統註解,也就是 JDK 內建的註解,主要有:@Override,@Deprecated,@SuppressWarnnings。

1.@Override

修飾方法時表示方法覆寫了父類別的方法,或實作介面的方法

interface Demo{    public void print();
}public class Test implements Demo{
    @Override
    public void print() {
    }
}

2.@Deprecated

修飾已經過時的方法

Alt text


3.@SuppressWarnnings

抑制編譯器警告,即移除警告。

常見的參數值有:

rawtypes表示傳參時也要傳遞帶泛型的參數#deprecation使用了不贊成使用的類別或方法時的警告unchecked執行了未檢查的轉換時的警告,例如使用集合時沒有用泛型(Generics) 來指定集合保存的類型fallthrough當Switch 程式區塊直接通往下一個情況而沒有Break 時的警告;path 在類別路徑、來源檔案路徑等中有不存在的路徑時的警告;#serial當在可序列化的類上缺少serialVersionUID 定義時的警告;finally任何finally 子句不能正常完成時的警告; all關於以上所有情況的警告。
名稱 #作用


實例如下:
// 抑制单类型@SuppressWarnings("unchecked")public void print() {    @SuppressWarnings("rawtypes")
    List list = new ArrayList(); 
    list.add("a");
}// 抑制多类型@SuppressWarnings({ "unchecked", "rawtypes" })public void print() {
    List list = new ArrayList(); 
    list.add("a");
}// 抑制所有类型@SuppressWarnings({ "all" })public void print() {
    List list = new ArrayList(); 
    list.add("a");
}

#元註解

元註解的功能就是負責註解其他註解。 Java5.0 定義了4  個標準的

meta-annotation

類型,它們被用來提供對其它 annotation 類型作說明。

定義的元註解如下:@Target,@Retention,@Documented,@Inherited。

1.@Target


@Target 定義了Annotation所修飾的物件範圍,具體的修飾範圍如下:
public enum ElementType {    // 用于描述类、接口(包括注解类型) 或enum声明
    TYPE,    // 用于描述域(即变量)
    FIELD,    // 用于描述方法
    METHOD,    // 用于描述参数
    PARAMETER,    // 用于描述构造器
    CONSTRUCTOR,    // 用于描述局部变量
    LOCAL_VARIABLE,    // 用于描述注解类型
    ANNOTATION_TYPE,    // 用于描述包
    PACKAGE
}

2.@Retention


@Retention 定義了該Annotation 被保留的時間長短,即指明了Annotation 的生命週期。
public enum RetentionPolicy {    // 在源文件中有效(编译器要丢弃的注解)
    SOURCE,    // class 文件中有效(默认,编译器将把注解记录在类文件中,但在运行时 VM 不需要保留注解)
    CLASS,    // 在运行时有效(编译器将把注解记录在类文件中,在运行时 VM 将保留注解,因此可以反射性地读取)
    RUNTIME
}

3.@Documented

#@Documented 定義 Annotation ,表示某一類型的註解將透過 javadoc 和類似的預設工具進行文件化。

如果類型宣告是用 Documented 來註解的,則其註解將成為註解元素的公共 API 的一部分。

4.@Inherited

  • @Inherited 定義Annotation ,表示註解類型被自動繼承,即一個使用了@Inherited 修飾的annotation 類型被用於一個class,則這個annotation 將會被用於該class的子類別。

  • 使用註解類型註解 class 以外的任何事物,@Inherited 都是無效的。

  • 此元註解僅促成從父類別繼承註解;對已實作介面的註解無效。

當@Inherited annotation類型標註的annotation的Retention是RetentionPolicy.RUNTIME,則反射API增強了這種繼承性。如果我們使用java.lang.reflect去查詢一個@Inherited annotation類型的annotation時,反射程式碼檢查將展開工作:檢查class和其父類,直到發現指定的annotation類型被發現,或到達類別繼承結構的頂層


實例如下:
// 定义注解@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@Inherited@interface MyAnotation{    
public String name();
}// 作用在类上@MyAnotation(name="parent")
class Parent{

}// 继承 Parent 类public class Test extends Parent{
    public static void main(String[] args) {
        Class<?> cls = Test.class;        // 通过 @Inherited 继承父类的注解
        Annotation annotation = cls.getAnnotation(MyAnotation.class);
        MyAnotation myAnotation = (MyAnotation) annotation;
        System.out.println(myAnotation.name());
    }
}// 输出结果:parent(若注释掉注解,返回异常)

自訂註解


1.類別註解

// 定义注解@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@interface MyAnnotation {    
public String name();    public String age();
}// 调用注解@MyAnnotation(name="cook",age="100")public class Test {
    public static void main(String[] args) {
        Class<?> cls = Test.class;        // 1.取得所有注解
        Annotation[] annotations =cls.getAnnotations();        // 2.取得指定注解
        MyAnnotation annotation = 
            (MyAnnotation)cls.getAnnotation(MyAnnotation.class);
    }
}


2.方法註解

// 定义注解@Retention(RetentionPolicy.RUNTIME)
// 修改作用范围@Target(ElementType.METHOD)@interface MyAnnotation {    public String name();    public String age();
}
// 调用注解public class Test {

    public static void main(String[] args) throws Exception {
        Class cls = Test.class;
        Method method = cls.getDeclaredMethod("print", null);        // 1.取得所有注解
        Annotation[] annotations = method.getDeclaredAnnotations();        // 2.取得指定注解
        MyAnnotation annotation = 
            (MyAnnotation)method.getAnnotation(MyAnnotation.class);
    }


3.參數註解

// 定义注解@Retention(RetentionPolicy.RUNTIME)
// 修改作用范围@Target(ElementType.PARAMETER)@interface MyAnnotation {    public String name();    public String age();
}public class Test {

    public static void main(String[] args) throws Exception {
        Class cls = Test.class;
        Method method = cls.getDeclaredMethod("print", new Class[]{String.class,String.class});
        getAllAnnotations(method);
    }    // 作用在参数上
    public void print(@MyAnnotation(name = "cook", age = "100") 
        String name, String age) { }    public static void getAllAnnotations(Method method) {
        Annotation[][] parameterAnnotions = method.getParameterAnnotations();        
        // 通过反射只能取得所有参数类型,不能取得指定参数
        Class[] paraemterTypes = method.getParameterTypes();        
        int i = 0;        
        for (Annotation[] annotations : parameterAnnotions) {
            Class paraemterType = paraemterTypes[i++];            
            for (Annotation annotation : annotations) {                
            if (annotation instanceof MyAnnotation) {
                    MyAnnotation myAnnotation = (MyAnnotation) annotation;
                    System.out.println(paraemterType.getName());
                    System.out.println(myAnnotation.name());
                    System.out.println(myAnnotation.age());
                }
            }
        }
    }
}

#4.變數註解

// 定义注解@Retention(RetentionPolicy.RUNTIME)
// 修改作用范围@Target(ElementType.FIELD)@interface MyAnnotation {    public String name();    public String age();
}public class Test {
    // 作用在变量上
    @MyAnnotation(name = "cook", age = "100")    
    private String name;    
    public static void main(String[] args) throws Exception {
        Class cls = Test.class;
        Field field = cls.getDeclaredField("name");
        Annotation[] fieldAnnotions = field.getDeclaredAnnotations();
        MyAnnotation annotation = 
            (MyAnnotation) field.getAnnotation(MyAnnotation.class);
    }
}

 以上就是09.Java 基礎- 註解的內容,更多相關內容請關注PHP中文網(www.php.cn)! ##########
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn