Java魔法堂:自定義和解析注解


一、前言                            

  注解(Annotation)作為元數據的載體,為程序代碼本身提供額外的信息,使用過MyBatis等ORM框架的朋友對 @Insert 的注解應該不陌生了,這是MyBatis自定義的注解,顯然我們也可以按需求自定義一些注解,然后對其進行解析獲取元數據,進而實現通過代碼生成代碼的操作。

 

二、自定義注解                         

 只需通過 關鍵字@interface 即可自定義注解

// 標識注解(就是無屬性的注解)
public @interface AnnotationWithoutProperty{
}

// 帶value屬性的注解
public @interface AnnotationWithVal{
  String value();
}

// 帶myVal屬性的注解
public @interface AnnotationWithMyVal{
  String[] myValue();
}

// 帶value和myVal屬性的注解
public @interface AnnotationWith2Val{
  String value();
  String[] myValue();
}

// 帶缺省值的myVal屬性的注解
public @interface AnnotationWithDefaultVal{
  String myVal() default "hello world!";
}

使用方式如下:

@AnnotationWithoutProperty
@AnnotationWithVal("hello world") // value屬性賦值時,不用顯式寫出屬性名
@AnnotationWithMyVal(myValue={"hello", "world"}) // 其他屬性賦值時,必須顯示寫出屬性名
@AnnotationWith2Val(value="hello world", myVal={"hello", "world"})
@AnnotationWithDefaultVal // 屬性擁有缺省值時,不必顯示設置屬性值
@AnnotationWithDefaultVal("new value")
public void test(){}

 

三、注解的注解                              

  注解的注解就是為注解本身提供額外的信息,從而約束或增強注解的能力。其中包含有 @Documented 、 @Inherited 、 @Target 、 Retention 4種注解。

   @Target注解 :用於約束被描述的注解的使用范圍,當被描述的注解超出使用范圍則編譯失敗。

// 約束@MyAnnotation的作用范圍是函數和構造函數
@Target(ElementType.METHOD, ElementType.CONSTRUCTOR)
public @interface MyAnnotation{}

   @Retention注解 :用於約束被描述的注解的作用范圍,注解的作用范圍有三個,分別為

        1.  RetentionPolicy.SOURCE ,作用范圍為源碼,就是僅存在於java文件中,當執行 javac 命令時將會去除該注解。

        2.  RetentionPolicy.CLASS ,作用范圍為二進制碼,就是存在於class文件中,當執行 java 命令時會去除該注解。

        3.  RetentionPolicy.RUNTIME ,作用范圍為運行時,就是我們可以通過反射動態獲取該注解。

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation{}

    @Documented注解 :用於指定javadoc生成API文檔時顯示該注解信息

    @Inherited注解 :用於指定被描述的注解可以被其所描述的類的子類繼承。默認情況

// 默認注解不會被子類繼承
@MyAnnotation
public class Parent{}

// Son並沒有繼承注解MyAnnotation
public class Son extends Parent{}

通過 @Inherited 子類將會繼承父類的 @MyAnnoation注解 。

 

四、讀取注解                                  

  通過反射我們可以獲取類、函數等上的注解信息。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.CLASS)
@Documented
public @interface MyAnnotaion{
  String value() default "hello world";
}

@MyAnnotation
public class Test{
  public static void main(String[] args){
    MyAnnotation ma = Test.class.getAnnotation(MyAnnotation.class);
    System.out.println(ma.value());

    // 獲取自身和從父類繼承的注解
    Annotation[] annotations = Test.class.getAnnotations();
    // 僅獲取自身的注解
    Annotation[] annotations = Test.class.getDeclaredAnnotations();
  }
}    

尊重原創,轉載請注明來自:http://www.cnblogs.com/fsjohnhuang/p/4040929.html ^_^肥仔John

 

五、參考                                

http://www.cnblogs.com/liubiqu/archive/2008/06/01/1211503.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM