Java 註解(Annotation)本質是一個實現 java.lang.annotation.Annotation 介面的特殊介面。每個註解類型必須關聯:
SOURCE(僅原始碼)、CLASS(預設,編譯進 class)、RUNTIME(運行時可讀)。ElementType 枚舉值,如 TYPE、METHOD、FIELD、PARAMETER 等,可組合。@Documented
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value() default "defaultValue";
int count() default 1;
String[] tags() default {};
}
使用方式:@MyAnnotation(value="test", count=3, tags={"a","b"})
| 註解 | @Target | @Retention | 用途 |
|---|---|---|---|
| @Override | METHOD | SOURCE | 編譯期檢查方法是否正確覆寫父類 |
| @Deprecated | 所有 | RUNTIME | 標記不建議使用,編譯器產生警告 |
| @SuppressWarnings | TYPE/FIELD/METHOD/… | SOURCE | 抑制特定編譯警告(unchecked、deprecation 等) |
| @SafeVarargs | METHOD/CONSTRUCTOR | RUNTIME | 標記可變參數泛型安全(Java 7+) |
| @FunctionalInterface | TYPE | RUNTIME | 標記函數式介面,編譯器驗證單一抽象方法(Java 8+) |
| @Inherited | ANNOTATION_TYPE | RUNTIME | 使被標註的註解具備繼承性(子類自動擁有) |
@Inherited @Retention(RUNTIME) @Target(TYPE)
@interface Marker {}
@Marker class Parent {}
class Child extends Parent {}
// Child.class.isAnnotationPresent(Marker.class) → true
// 若移除 @Inherited → false
@SuppressWarnings("unchecked") // 泛型未檢查轉換
@SuppressWarnings("deprecation") // 使用過時 API
@SuppressWarnings("rawtypes") // 使用原始類型而非參數化類型
@SuppressWarnings({"unchecked","deprecation"}) // 組合
@Retention(RUNTIME) @Target(METHOD)
@interface Action { String name(); }
class Service {
@Action(name="save")
public void save() {}
}
public class Demo {
public static void main(String[] args) throws Exception {
Method m = Service.class.getMethod("save");
if (m.isAnnotationPresent(Action.class)) {
Action a = m.getAnnotation(Action.class);
System.out.println("Action: " + a.name()); // 輸出 save
}
// 獲取所有註解
for (Annotation an : m.getAnnotations()) {
System.out.println(an);
}
}
}
編譯期掃描註解並生成程式碼/資源檔(如 Lombok、MapStruct、Dagger、Room)。實作 javax.annotation.processing.Processor,配置 META-INF/services/javax.annotation.processing.Processor 註冊。屬於進階主題,此處不展開。
@Retention(RUNTIME) 方便反射讀取;若僅編譯期處理用 SOURCE。@Target 盡量精確限定,避免濫用。value() 作為單一主屬性,支援單值簡寫 @Anno("val")。Annotation 是「元數據」的載體,配合 Retention、Target、Inherited 三大元註解定義生命週期與作用域。內建註解解決編譯檢查、警告抑制、過時標記;自訂註解+反射實現框架級功能(路由映射、參數驗證、ORM 映射、API 文檔生成等)。深入理解其保留策略與目標限制,是設計優雅 API 與框架的關鍵。