close

  都快發行JDK 7了,JDK 5的annotation在survey Guice才知道怎麼回事。Guice怎麼使用anntation做Module bind留待後面。原來annotation是一個介面啊!如下寫一個interface:

public @interface Debug{}

  就可以用@Debug在method之上。interface的定字前就得加個@。再根據Guice的飯粒這麼定義@Blue這個annotation當解說:

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR})
@Retention ( RetentionPolicy.RUNTIME )
@Documented

@BindingAnnotation
public @interface Blue {}

  上例紅字的annotation皆出自java.lang.annotation:

  • @Target:指@Blue這個anntoation可以修飾哪些層級,上例有FIELD(廣域變數)、METHOD和建構子。此外,還有TYPE(修餘class、interface和enum)、PARAMETER(METHOD上的參數)、LOCAL_VARIABLE(區域變數)、ANNOTATION_TYPE(Annotation)和PACKAGE。
  • @Retention:指@Blue在什麼時期有作用,RUNTIME(執行期能被reflection用)、CLASS(預設,Runtime)和SOURCE(編譯時期)
  • @Document:將@Blue產出JavaDoc。
  • @Inherited:宣告該@annotation所注釋的類別若被繼承,其子類別亦被注釋。

  而通常annotion括號內設計內賦值,也是在@interface裡設計,例如像@Retention,應該是這樣:

public @interface Retention {
    public enum RentionPolicy {SOURCE, CLASS, RUNTIME};
    RentionPolicy rentionPolcy() default RentionPolicy.CLASS;
    // 以下是說明傳回其它型態的賦值舉例
    String op1();   // @Retention(op1=”Jemmy”), 若只有op1,可能連method name都可省略了
    String[] op2(); // @Retention(op1={”Jemmy”,Tsai”})
    boolean op3();  // @Retention(op3=true)

    /* 或是像這樣
    @Retention(
        op1=”Jemmy”, op2={“Jemmy”,Tsai”}, op3=true
    )
    */
}
arrow
arrow
    全站熱搜

    Jemmy 發表在 痞客邦 留言(0) 人氣()