|
|
在定義Annotation型態時,使用java.lang.annotation.Target可以定義其適用之時機,在定義時可以指定java.lang.annotation.ElementType的列舉值: package java.lang.annotation;
public enum ElementType { TYPE, // 適用 class, interface, enum FIELD, // 適用 field METHOD, // 適用 method PARAMETER, // 適用 method 上之 parameter CONSTRUCTOR, // 適用 constructor LOCAL_VARIABLE, // 適用區域變數 ANNOTATION_TYPE, // 適用 annotation 型態 PACKAGE // 適用 package } 舉個例子來說,假設你定義Annotation只能適用於constructor與method: package cc.openhome;
import java.lang.annotation.Target; import java.lang.annotation.ElementType; @Target({ElementType.CONSTRUCTOR, ElementType.METHOD}) public @interface Debug {} 如果你嘗試將Debug用於class上: package cc.openhome;
@Debug public class SomeObject { public void doSomething() { // .... } } 則在編譯時會發生以下的錯誤: SomeObject.java:3: annotation type not applicable to this kind of declaration
@Debug ^ 1 error 在製作JavaDoc文件時,預設上並不會將Annotation的資料加入到文件中,Annotation用於為程式碼作註解,有時它包括了重要的訊息,你也許會想要使用者製作文件的同時,也一併將Annotation的訊息加入,你可以 使用java.lang.annotation.Documented,例如: package cc.openhome;
import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Documented @Retention(RetentionPolicy.RUNTIME) public @interface Debug {} 使用java.lang.annotation.Documented時,同時的你必須使用Retention指定編譯器將訊 息加入class檔案,並可以由VM讀取,即設定RetentionPolicy為RUNTIME,接著你可以重新產生Java Doc文件,這次可以看到文件中包括了@Debug的訊息。 ![]() 在你定義Annotation型態後並使用於程式碼上時,預設上父類別中的Annotation並不會被繼承至子 類別中,你可以在定義 Annotation時加上java.lang.annotation.Inherited的Annotation,這讓你定義的Annotation型 別被繼承下來。例如: package cc.openhome;
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Inherited; @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface Debug { String value(); String name(); } |