在使用反射讀取類別欄位上的註解時,許多人習慣用 field.getAnnotations() 取得所有註解再遍歷判斷,這不僅繁瑣,還容易出錯。正確且高效的方式是直接指定註解類型獲取。
// 直接獲取欄位上的 @A 註解實例
A a = field.getAnnotation(A.class);
if (a != null) {
String aId = a.aId();
String aName = a.aName();
// 使用屬性值...
}
instanceof 或比較 annotationType())。getAnnotation 只能取一個,需用 getAnnotationsByType(Java 8+)。Field[] fields = Test.class.getDeclaredFields();
for (Field field : fields) {
// 針對特定註解類型直接獲取
A a = field.getAnnotation(A.class);
B b = field.getAnnotation(B.class);
if (a != null) { /* 處理 A */ }
if (b != null) { /* 處理 B */ }
}
精準獲取,代碼更乾淨、效能更好。