Java1.5中的annotation簡介

轉載自:http://www.blogjava.net/livery/articles/203096.html

1、Target
指定所定義的annotation可以用在哪些程序單元上
如果Target沒有指定,則表示該annotation可以使用在任意程序單元上
代碼
    @Target({ElementType.ANNOTATION_TYPE,
             ElementType.CONSTRUCTOR,
             ElementType.FIELD,
            ElementType.LOCAL_VARIABLE,
             ElementType.METHOD,
             ElementType.PACKAGE,
             ElementType.PARAMETER,
             ElementType.TYPE})
    public @interface TODO {}


2 、Retention
指出Java編譯期如何對待annotation
annotation可以被編譯期丟掉,或者保留在編譯過的class文件中
在annotation被保留時,它也指定是否會在JVM加載class時讀取該annotation
代碼
   @Retention(RetentionPolicy.SOURCE)  // Annotation會被編譯期丟棄
   public @interface TODO1 {}
   @Retention(RetentionPolicy.CLASS)   // Annotation保留在class文件中,但會被JVM忽略
   public @interface TODO2 {}
   @Retention(RetentionPolicy.RUNTIME) // Annotation保留在class文件中且會被JVM讀取
   public @interface TODO3 {}


3 、Documented
指出被定義的annotation被視爲所熟悉的程序單元的公開API之一
被@Documented標註的annotation會在javadoc中顯示,這在annotation對它標註的元素被客戶端使用時有影響時起作用
d, Inherited
該meta-annotation應用於目標爲class的annotation類型上,被此annotattion標註的class會自動繼承父類的annotation

4 、Annotation的反射
我們發現java.lang.Class有許多與Annotation的反射相關的方法,如getAnnotations、isAnnotationpresent
我們可以利用Annotation反射來做許多事情,比如自定義Annotation來做Model對象驗證
代碼
    @Retention(RetentionPolicy.RUNTIME)
   @Target({ ElementType.FIELD, ElementType.METHOD })
   public @interface RejectEmpty {
        /** hint title used in error message */
        String value() default "";
    }
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target( { ElementType.FIELD, ElementType.METHOD })
   public @interface AcceptInt {
       int min() default Integer.MIN_VALUE;
       int max() default Integer.MAX_VALUE;
       String hint() default "";
   }
使用@RejectEmpty和@AcceptInt標註我們的Model的field,然後利用反射來做Model驗證


發佈了3 篇原創文章 · 獲贊 2 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章