[英]Java annotations
我在Java中創建了簡單的注釋
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Column {
String columnName();
}
和班級
public class Table {
@Column(columnName = "id")
private int colId;
@Column(columnName = "name")
private String colName;
private int noAnnotationHere;
public Table(int colId, String colName, int noAnnotationHere) {
this.colId = colId;
this.colName = colName;
this.noAnnotationHere = noAnnotationHere;
}
}
我需要迭代所有字段,這些字段用Column
注釋並獲取字段和注釋的名稱和值 。 但是我獲得每個字段的值都有問題,因為它們都是不同的數據類型 。
是否有任何東西可以返回具有特定注釋的字段集合? 我設法用這個代碼做了,但我不認為反射是解決它的好方法。
Table table = new Table(1, "test", 2);
for (Field field : table.getClass().getDeclaredFields()) {
Column col;
// check if field has annotation
if ((col = field.getAnnotation(Column.class)) != null) {
String log = "colname: " + col.columnName() + "\n";
log += "field name: " + field.getName() + "\n\n";
// here i don't know how to get value of field, since all get methods
// are type specific
System.out.println(log);
}
}
我是否必須在object中包裝每個字段,這將實現getValue()
類的方法,或者有更好的解決方法嗎? 基本上我需要的是每個注釋字段的字符串表示。
編輯: field.get(table)
有效,但僅適用於public
領域,有沒有辦法如何為private
字段做到這一點? 或者我必須制作吸氣劑並以某種方式調用它?
每個對象都應該定義toString()。 (並且您可以為每個類重寫此項以獲得更有意義的表示)。
所以你在“//這里我不知道”評論的地方,你可以:
Object value = field.get(table);
// gets the value of this field for the instance 'table'
log += "value: " + value + "\n";
// implicitly uses toString for you
// or will put 'null' if the object is null
反思正是解決問題的方法。 在執行時找出關於類型及其成員的事情幾乎就是反射的定義! 你做的方式看起來很好。
要查找字段的值,請使用field.get(table)
反射正是查看注釋的方式。 它們是附加到類或方法的“元數據”形式,Java注釋旨在以這種方式進行檢查。
反射是處理對象的一種方法(如果字段是私有的並且沒有任何類型的存取方法,則可能是唯一的方法)。 你需要看看Field.setAccessible也許Field.getType 。
另一種方法是使用編譯時注釋處理器生成另一個用於枚舉帶注釋字段的類。 這需要Java 5中的com.sun API,但在Java 6 JDK中支持更好(像Eclipse這樣的IDE可能需要特殊的項目配置)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.