Java Annotation之應用篇 – 運行期動態解析annotation (3)

來源:互聯網
上載者:User

我們在前2篇文章中:

分別介紹了annotation的基本概念,以及怎麼樣自訂annotation。
本文介紹怎麼在運行期(runtime)動態解析annotation。
上面我們介紹過,annotation只是附加在代碼裡的附加資訊,annotation本身不會對代碼的執行產生任何影響。

這樣說來,annotation到底能起什麼作用呢?
1,    編譯工具或其他工具可以根據被附加在代碼裡的annotation資訊自動組建組態檔案或文檔等外部檔案。
比如,sun公司就提供了apt(Annotation Processing Tool)工具,apt工具是一個可以處理annotation的命令列工具,apt提供了在編譯期針對原始碼層級的解析,並可以在解析時產生新的原始碼和其他檔案,同時還可以對產生的原始碼進行編譯。
2,    其他程式可以在運行時動態解析將要被執行的程式裡的annotation資訊,並根據被附加的annotation資訊來執行不同的操作。
比如,EJB3規範就比較廣泛地使用了annotation特性。比如只要在POJO為class註明@Stateless注釋,EJB容器便會根據此annotation把該POJO註冊為無狀態的Session Bean。EJB3使用了annotation大大地簡化了EJB的開發和配置過程。我們會在其他文章裡專門介紹EJB Annotation的原理與使用方法,這裡不做詳述。

本文通過一個簡單地例子來說明怎麼在運行期動態解析annotation。Apt工具的使用我們會在近期其他文章裡對其加以介紹。

比如,我們定義了MyAnnotation3注釋:
MyAnnotation3.java

  

Java代碼  
  1. package com.test.annotation;  
  2. import java.lang.annotation.Annotation;  
  3. import java.lang.annotation.Inherited;  
  4. import java.lang.annotation.Retention;  
  5. import java.lang.annotation.RetentionPolicy;  
  6. @Retention(RetentionPolicy.RUNTIME)  
  7. public @interface MyAnnotation3 {  
  8.  public String value();  
  9.  public String[] multiValues();  
  10.  int number() default 0;  
  11. }  

 

上面定義了一個名為MyAnnotation3的注釋。
我們再定義一個GetMyAnnotation類,該類使用了MyAnnotation3注釋:
GetMyAnnotation.java:

 

 

Java代碼  
  1. package com.test.annotation.test;  
  2.   
  3. import java.lang.annotation.Annotation;  
  4. import java.lang.reflect.Field;  
  5. import java.lang.reflect.Method;  
  6. import javax.ejb.EJB;  
  7. import javax.naming.InitialContext;  
  8. import javax.naming.NamingException;  
  9. import com.test.annotation.MyAnnotation3;  
  10.   
  11. // 為GetMyAnnotation類附加MyAnnotation3 注釋     
  12. @MyAnnotation3(value = "Class GetMyAnnotation", multiValues = { "1", "2" })  
  13. public class GetMyAnnotation {  
  14.   
  15.     // 為testField1屬性附加MyAnnotation3 注釋  
  16.     @MyAnnotation3(value = "call testField1", multiValues = { "1" }, number = 1)  
  17.     private String testField1;  
  18.   
  19.     // 為testMethod1方法附加MyAnnotation3 注釋  
  20.     @MyAnnotation3(value = "call testMethod1", multiValues = { "1", "2" }, number = 1)  
  21.     public void testMethod1() {  
  22.     }  
  23.   
  24.     @Deprecated  
  25.     @MyAnnotation3(value = "call testMethod2", multiValues = { "3", "4", "5" })  
  26.     public void testMethod2() {  
  27.     }  
  28. }  

  

上面的例子GetMyAnnotation非常簡單,裡面沒有任何功能,但是分別為類(class),屬性(field),方法(method)申明(附加)了MyAnnotation3 注釋。
下面我們用程式TestMyAnnotation3對GetMyAnnotation裡MyAnnotation3注釋進行解析。
運行時解析annotation
TestMyAnnotation3.java

 

 

 

Java代碼  
  1. public class TestMyAnnotation3 {  
  2.   
  3.     public static void main(String[] args) {  
  4.   
  5.         System.out.println("--Class Annotations--");  
  6.   
  7.         if (GetMyAnnotation.class.isAnnotationPresent(MyAnnotation3.class)) {  
  8.             System.out.println("[GetMyAnnotation].annotation:");  
  9.   
  10.             MyAnnotation3 classAnnotation = GetMyAnnotation.class  
  11.                     .getAnnotation(MyAnnotation3.class);  
  12.             printMyAnnotation3(classAnnotation);  
  13.         }  
  14.         System.out.println("--Fields Annotations--");  
  15.   
  16.         Field[] fields = GetMyAnnotation.class.getDeclaredFields();  
  17.   
  18.         for (Field field : fields) {  
  19.   
  20.             if (field.isAnnotationPresent(MyAnnotation3.class)) {  
  21.   
  22.                 System.out.println("[GetMyAnnotation." + field.getName()  
  23.                         + "].annotation:");  
  24.   
  25.                 MyAnnotation3 fieldAnnotation = field  
  26.                         .getAnnotation(MyAnnotation3.class);  
  27.   
  28.                 printMyAnnotation3(fieldAnnotation);  
  29.             }  
  30.         }  
  31.         System.out.println("--Methods Annotations--");  
  32.   
  33.         Method[] methods = GetMyAnnotation.class.getDeclaredMethods();  
  34.   
  35.         for (Method method : methods) {  
  36.   
  37.             System.out.println("[GetMyAnnotation." + method.getName()  
  38.                     + "].annotation:");  
  39.   
  40.             if (method.isAnnotationPresent(MyAnnotation3.class)) {  
  41.   
  42.                 MyAnnotation3 methodAnnotation = method  
  43.                         .getAnnotation(MyAnnotation3.class);  
  44.   
  45.                 printMyAnnotation3(methodAnnotation);  
  46.             }  
  47.         }  
  48.     }  
  49.   
  50.     private static void printMyAnnotation3(MyAnnotation3 annotation3) {  
  51.   
  52.         if (annotation3 == null) {  
  53.             return;  
  54.         }  
  55.         System.out.println("{value=" + annotation3.value());  
  56.         String multiValues = "";  
  57.   
  58.         for (String value : annotation3.multiValues()) {  
  59.             multiValues += "," + value;  
  60.         }  
  61.   
  62.         System.out.println("multiValues=" + multiValues);  
  63.   
  64.         System.out.println("number=" + annotation3.number() + "}");  
  65.     }  
  66. }  

 

 

輸出:

 

 

--Class Annotations--
[GetMyAnnotation].annotation:
{value=Class GetMyAnnotation
multiValues=,1,2
number=0}
--Fields Annotations--
[GetMyAnnotation.testField1].annotation:
{value=call testField1
multiValues=,1
number=1}
--Methods Annotations--
[GetMyAnnotation.testMethod1].annotation:
{value=call testMethod1
multiValues=,1,2
number=1}
[GetMyAnnotation.testMethod2].annotation:
{value=call testMethod2
multiValues=,3,4,5
number=0}

JDK1.5以後的版本提供的跟annotation有關的介面:

 

Java代碼  
  1. interface java.lang.reflect.AnnotatedElement {     
  2.   
  3.     boolean isAnnotationPresent(Class<? extends Annotation> annotationClass);     
  4.   
  5.    <T extends Annotation> T getAnnotation(Class<T> annotationClass);     
  6.   
  7.    Annotation[] getAnnotations();     
  8.   
  9.    Annotation[] getDeclaredAnnotations();     
  10.   
  11. }     

 

 

該介面主要用來取得附加在類(class),構造方法(constructor),屬性(field),方法(method),包(package)上的annotation資訊。
JDK1.5與此有關的幾個類都實現了AnnotatedElement介面:  

 

所以可以利用反射(reflection)功能在程式裡動態解析附加的annotation資訊。
總結:
本文通過舉例簡單地說明了怎麼動態解析annotation,大家可以舉一反三,利用Java的annotation特性,完成更複雜功能等。    

 

聯繫我們

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