java基礎鞏固筆記(6)-註解

來源:互聯網
上載者:User

java基礎鞏固筆記(6)-註解
註解(Annotation),也叫中繼資料。一種代碼層級的說明。它是JDK1.5及以後版本引入的一個特性,與類、介面、枚舉是在同一個層次。它可以聲明在包、類、欄位、方法、局部變數、方法參數等的前面,用來對這些元素進行說明,注釋。

API

註解的應用結構圖

調用/結構關係:A<–B<–C

A,B,C解釋如下:

A:註解類

@interface A{}

B:應用了“註解類”的類

@AClass B{}

C:對“應用了註解類的類”進行反射操作的類

Class C{   public void f(){     B.class.isAnnotationPresent(A.class);     A a = B.class.getAnnotion(A.class);   }}
元註解

元註解的作用就是負責註解其他註解。四個元註解分別是:@Target,@Retention,@Documented,@Inherited

@Retention

表示在什麼層級儲存該註解資訊。可選的參數值在枚舉類型 RetentionPolicy中,包括RetentionPolicy.SOURCE,RetentionPolicy.CLASS(預設),RetentionPolicy.RUNTIME分別對應:java源檔案–>class檔案–>記憶體中的位元組碼

RetentionPolicy.SOURCE 註解將被編譯器丟棄 RetentionPolicy.CLASS 註解在class檔案中可用,但會被VM丟棄RetentionPolicy.RUNTIME VM將在運行期也保留注釋,因此可以通過反射機制讀取註解的資訊。 
@Target

表示該註解用於什麼地方,可能的值在枚舉類ElemenetType中,包括

ElemenetType.CONSTRUCTOR 構造器聲明 ElemenetType.FIELD 域聲明(包括 enum 執行個體) ElemenetType.LOCAL_VARIABLE 局部變數聲明 ElemenetType.METHOD 方法聲明 ElemenetType.PACKAGE 包聲明 ElemenetType.PARAMETER 參數聲明 ElemenetType.TYPE 類,介面(包括註解類型)或enum聲明 
@Documented

將此註解包含在javadoc中 ,它代表著此註解會被javadoc工具提取成文檔。在doc文檔中的內容會因為此註解的資訊內容不同而不同。相當於@see,@param

@Inherited

允許子類繼承父類中的註解

自訂註解

使用@interface自訂註解時,自動繼承了java.lang.annotation.Annotation介面,由編譯器自動完成其他細節。在定義註解時,不能繼承其他的註解或介面。@interface用來聲明一個註解,其中的每一個方法實際上是聲明了一個配置參數。方法的名稱就是參數的名稱,傳回值類型就是參數的類型(傳回值類型只能是基本類型、Class、String、enum)。可以通過default來聲明參數的預設值。

定義註解格式:

public @interface 註解名 {定義體}

註解參數的可支援資料類型:

1.所有基礎資料型別 (Elementary Data Type)(int,float,boolean,byte,double,char,long,short)
2.String類型
3.Class類型
4.enum類型
5.Annotation類型
6.以上所有類型的數組

範例程式碼

下面的樣本,是上文提到的A<–B<–C的擴充版本。自訂了一個註解@A,然後在B類中使用了註解@A,最後在類C中利用反射讀取@A中的資訊

A.java
package com.iot.annotation;import java.lang.annotation.*;/** * Created by brian on 2016/2/20. */@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD,ElementType.CONSTRUCTOR})@Retention(RetentionPolicy.RUNTIME)public @interface A {    String name();    int id() default 0;    Class gid();}
B.java
package com.iot.annotation;import java.util.HashMap;import java.util.Map;/** * Created by brian on 2016/2/20. */@A(name="type",gid=Long.class)//類註解public class B {    @A(name="param",id=1,gid=Long.class) //類成員註解    private Integer age;    @A(name="construct",id=2,gid=Long.class) //構造方法註解    public B(){}    @A(name="public method",id=3,gid=Long.class) //類方法註解    public void a(){    }    @A(name="protected method",id=4,gid=Long.class) //類方法註解    protected void b(){        Map m = new HashMap(0);    }    @A(name="private method",id=5,gid=Long.class) //類方法註解    private void c(){        Map m = new HashMap(0);    }    public void b(Integer a){    }}
C.java
package com.iot.annotation;import java.lang.annotation.Annotation;import java.lang.reflect.Constructor;import java.lang.reflect.Method;/** * Created by brian on 2016/2/20. */public class C {    /**     * 簡單列印出B類中所使用到的類註解     * 該方法只列印了 Type 類型的註解     * @throws ClassNotFoundException     */    public static void parseTypeAnnotation() throws ClassNotFoundException{        Class clazz = Class.forName("com.iot.annotation.B");        Annotation[] annotations = clazz.getAnnotations();        for(Annotation annotation :annotations){            A a = (A)annotation;            System.out.println("id = "+a.id()+" ;name = "+a.name()+" ;gid = "+a.gid());        }    }    /**     * 簡單列印出B類中所使用到的方法註解     * 該方法只列印了 Method 類型的註解     */    public static void parseMethodAnnotation() {        Method[] methods = B.class.getDeclaredMethods();        for (Method method : methods) {            /*             * 判斷方法中是否有指定註解類型的註解             */            boolean hasAnnotation = method.isAnnotationPresent(A.class);            if (hasAnnotation) {                /*                 * 根據註解類型返回方法的指定類型註解                 */                A annotation = method.getAnnotation(A.class);                System.out.println("method = " + method.getName()                        + " ; id = " + annotation.id() + " ; description = "                        + annotation.name() + "; gid= " + annotation.gid());            }        }    }    /**     * 簡單列印出B類中所使用到的方法註解     * 該方法只列印了 Method 類型的註解     */    public static void parseConstructAnnotation(){        Constructor[] constructors = B.class.getConstructors();        for (Constructor constructor : constructors) {            /*             * 判斷構造方法中是否有指定註解類型的註解             */            boolean hasAnnotation = constructor.isAnnotationPresent(A.class);            if (hasAnnotation) {                /*                 * 根據註解類型返回方法的指定類型註解                 */                A annotation =(A) constructor.getAnnotation(A.class);                System.out.println("constructor = " + constructor.getName()                        + " ; id = " + annotation.id() + " ; description = "                        + annotation.name() + "; gid= "+annotation.gid());            }        }    }    public static void main(String[] args) throws ClassNotFoundException {        parseTypeAnnotation();        parseMethodAnnotation();        parseConstructAnnotation();    }}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.