回顧java Annotation(註解)

來源:互聯網
上載者:User

最近在學習中發現相當多的架構是通過註解來實現的。為了加深記憶,把註解重新做一下回顧。


首先註解不是注釋。——但因為java語言內建了三個註解:@Override、@Deprecated、@SuppressWarnnings。第一個是通知編譯器做方法覆蓋檢查;第二個是提醒程式員使用了過時的方法;第三個是通知編譯器忽略警告。這三個內建註解用起來給人的感覺就象注釋一樣。而實際上註解的用法遠不止這麼簡單,通過使用自訂註解有助於加深我們的理解。


使用自訂註解目的是為了給程式加上某些標記(這種標記也可稱之為中繼資料),這些標記是給有關注需要的其他程式使用的。不關注的就直接忽略過去了。所以使用註解的完整過程包括三步:定義註解、使用註解、解析註解。和我們定義類、建立對象、使用對象是一樣的。下面結合一個小例子分別說明:

第一步,定義註解

Annotation(註解)其實是一個介面,但不是用interface關鍵字而是用@interface,以示區別。因為的確和普通介面有區別——Annotation類型的方法必須是無參數、無異常拋出的;預設繼承自java.lang.annotation.Annotation


先定義一個用於類的註解

package com.annotation.zjc;import java.lang.annotation.*;//以下三行是“元註解”,用於指明此註解的生命週期、使用範圍和可被文檔化@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@Documentedpublic @interface Description {String value();}

再定義一個用於建構函式和方法的註解

package com.annotation.zjc;import java.lang.annotation.*;@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.CONSTRUCTOR,ElementType.METHOD})@Documentedpublic @interface Resource {int id();String name();String type() default "Object";  //可以給出預設值}

第二步,使用註解

註解可以使用在包,類,欄位,方法,方法的參數以及局部變數上(最多見就是用在類和方法上,其他位置比較罕見)。使用了註解也就相當於建立了一個註解類的執行個體。

package com.annotation.zjc;@Description("Inject use annotation")//等同於@Description(value="Inject use annotation"),欄位名稱為value,可以用以上簡寫入模式public class ApplyAnnotation {@Resource(id=1,name="zhang",type="person")public ApplyAnnotation(){//init...}public void execute(Resource r){System.out.println(r.id()+"  "+r.name()+"  "+r.type());}}

第三步,解析註解

package com.annotation.zjc;import java.lang.reflect.Constructor;public class testMain {public static void main(String[] args){ApplyAnnotation aa=new ApplyAnnotation();Class<?> objclass=null;try{objclass = Class.forName("com.annotation.zjc.ApplyAnnotation");}catch(Exception e){}if(objclass!=null&&objclass.isAnnotationPresent(Description.class)){Description des=objclass.getAnnotation(Description.class);//擷取“註解對象”System.out.println(des.value());}Resource r=null;if(objclass!=null){Constructor<?> cons[]=objclass.getConstructors();//反射取得類的建構函式for(Constructor<?> con:cons){if(con.isAnnotationPresent(Resource.class)){r=(Resource)con.getAnnotation(Resource.class);//擷取“註解對象”}}}if(r!=null)aa.execute(r);}}

在實際情況中,往往是第一步、第三步都由架構或工具程式做了,我們只需要在自己的程式中使用註解即可。當然使用前要import相應的包檔案。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.