Annotation(註解)自 Java 5 起廣泛應用於各大框架與專案中。本文從內建註解入手,深入解析 Annotation 核心概念,並完整示範如何設計、實作與解析自訂註解,助你快速掌握這項關鍵技術。
設計自訂註解需理解四個關鍵元註解(位於 java.lang.annotation 套件):
@Target(ElementType.METHOD)
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR})
ElementType 列舉定義 8 種目標類型:TYPE(類別/介面/列舉/註解)、FIELD(屬性)、METHOD(方法)、PARAMETER(參數)、CONSTRUCTOR(建構子)、LOCAL_VARIABLE(區域變數)、ANNOTATION_TYPE(註解類型)、PACKAGE(套件)。未指定 @Target 則預設適用所有元素。
public enum RetentionPolicy {
SOURCE, // 僅原始碼保留,編譯後移除
CLASS, // 編譯至 .class 檔,但不載入 JVM(預設)
RUNTIME // 執行期透過反射可讀取
}
範例:@Override 設為 SOURCE(編譯後無需保留),@Deprecated 設為 RUNTIME(執行期仍可檢測)。
加上此註解的 Annotation 類型資訊會出現在生成的 API 文件中。
標示此註解的 Annotation 類型可被子類別繼承。
@interface 關鍵字定義(非 class/interface)。public 或預設權限,型別限制為:8 種基本型別、String、Enum、Class、Annotation 及其陣列。value,使用時可省略參數名。@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Description {
String value();
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Name {
String originate();
String community();
}
@Description("javaeye,做最棒的軟體開發交流社群")
public class JavaEyer {
@Name(originate="創始人:robbin", community="javaEye")
public String getName() { return null; }
@Name(originate="創始人:江南白衣", community="springside")
public String getName2() { return "借用兩位的 id 一用..."; }
}
public class TestAnnotation {
public static void main(String[] args) throws Exception {
Class test = Class.forName("lighter.javaeye.com.JavaEyer");
// 解析類別級註解
if (test.isAnnotationPresent(Description.class)) {
Description des = test.getAnnotation(Description.class);
System.out.println("描述:" + des.value());
}
// 解析方法級註解
for (Method m : test.getMethods()) {
if (m.isAnnotationPresent(Name.class)) {
Name name = m.getAnnotation(Name.class);
System.out.println(name.originate());
System.out.println("創建的社群:" + name.community());
}
}
}
}
描述:javaeye,做最棒的軟體開發交流社群 ----------------- 創始人:robbin 創建的社群:javaEye 創始人:江南白衣 創建的社群:springside
java.lang.annotation.Annotation 介面的特殊介面isAnnotationPresent、getAnnotation)在執行期動態讀取註解資訊掌握自訂 Annotation 設計,不僅能簡化配置、增強程式碼可讀性,更是實現框架級功能(如依賴注入、AOP、ORM 映射)的基石技能。