承接前文,展示完整的 TXTExportableGenerator 實作,將標記 @Exportable 的欄位依聲明順序匯出為文字檔,支援巢狀物件遞迴匯出。
public class TXTExportableGenerator extends ExportableGenerator {
public TXTExportableGenerator(PrintWriter out) { super(out); }
@Override
protected void outputSimpleField(PrintWriter out, Field f, Object obj) {
out.print(f.getName());
out.print("=");
out.print(value(f, obj)); // 父類處理型別轉換
out.print(";");
out.println();
}
@Override
protected void outputFieldHeader(PrintWriter out, Object e) { /* 無表頭 */ }
@Override
protected void outputFieldFooter(PrintWriter out, Object e) { /* 無表尾 */ }
}
public class TestExportable {
public static void main(String[] args) {
// 建構測試物件圖
Employee emp = new Regular("Catherine", "IBM", "Software Engineer", "82888288", "BJ", new Date());
emp.addMember(new Vendor("Steve", "IBM", "PVC", "8"));
emp.addMember(new Vendor("Steve", "IBM", "PVC", "8"));
emp.addMember(new Contractor("Joe", "IBM"));
emp.addMember(new Supplemental("Linda", "IBM", "8"));
try (PrintWriter pw = new PrintWriter(new FileOutputStream("C:\\test.output", true))) {
ExportableGenerator gen = new TXTExportableGenerator(pw);
gen.genDoc(emp, 0);
gen.flush();
} catch (FileNotFoundException e) { e.printStackTrace(); }
}
}
name=Catherine; company=IBM; title=Software Engineer; phone=82888288; location=BJ; hireDate=2024-01-15; ----------------------------- name=Steve; company=IBM; title=PVC; id=8; ----------------------------- ...

| 維度 | 傳統硬編碼 | 註解驅動 |
|---|---|---|
| 新增欄位 | 修改匯出代碼 | 僅在欄位加 @Exportable |
| 格式變更 | 修改核心邏輯 | 新增 Generator 子類別(如 XML/JSON) |
| 巢狀物件 | 手寫遞迴判斷 | 框架自動偵測 ArrayList 遞迴 |
| 開放封閉原則 | 違反(修改舊代碼) | 符合(擴充新 Generator) |
「元資料」即 Metadata = Data about Data。註解讓開發者在不改變業務邏輯前提下,將補充語義(如「此欄位可匯出」、「此參數不可為 null」、「此方法需交易支援」)直接嵌入原始碼。
apt / javac -processor 產生代碼、配置檔、文件。RetentionPolicy.RUNTIME 註解,驅動動態行為(驗證、序列化、API 文件生成)。許多開發者誤以為註解僅供「框架作者」使用。實際上,應用層同樣受益:
@NotNull、@ValidPhone 驗證規則,配合統一攔截器實現宣告式驗證。@Exportable、@Importable 驅動通用匯入匯出引擎,消除重複 boilerplate。@TestCase、@Benchmark 整合測試與效能分析工具鏈。New → Annotation 快速建立 @interface 骨架。@Target 限制使用位置,違規即時紅線(如 @Override 用於欄位)。@Retention(RUNTIME) 缺失時,反射讀取失敗無編譯錯誤,Eclipse 可配置警告。@Override、@Deprecated、@SuppressWarnings 完整整合編輯器語義分析。註解類型將 Java 從「純指令式語言」推向「宣告式擴充平台」。掌握 @interface 定義、四大元註解(Target、Retention、Documented、Inherited)、保留策略選擇、反射讀取 API、以及以註解替代硬編碼邏輯的架構思維,是現代 Java 開發者的核心素養。配合 Eclipse 3.1 的工具鏈,讓宣告式編程觸手可及。