是否可以在對象的setter中獲取當前實例的變量名稱?獲取有關實例變量名稱的內部setter信息
像這樣的事情
public class Class {
private DataType dataType;
}
public class DataType {
public void setValue(String value) {
if (variableName is 'dataType') {
this.value = value;
} else {
this.value = null;
}
}
}
如果使用標準的實用工具則可以創建某種註解存儲有變量名,然後在二傳手使用它是不可能的?
當我嘗試這樣做 - 註釋爲空。 創建註釋
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface FieldName {
String fieldName();
}
然後我把它添加到現場
public class Class {
@FieldName(fieldName = "dataType")
private DataType dataType;
}
當我設法得到它在DataType
的getter
- 註釋FieldName
爲空。
private String wrapGetter(String requiredFieldName, String dataTypeField) {
FieldName fieldName = this.getClass().getAnnotation(FieldName.class);
if (fieldName.fieldName().equals(requiredFieldName)) {
return dataTypeField;
} else {
return dataTypeField;
}
}
的可能重複[Java反射:如何獲得一個變量的名稱(HTTP://計算器.com/questions/744226/java-reflection-how-to-get-the-name-of-variable) – Batty 2015-03-13 09:15:39
什麼是變量名? – SMA 2015-03-13 09:16:17
@SMA呃......更確切地說,我的意思是字段名稱 - 在這種情況下是'dataType'。 – lapots 2015-03-13 09:18:53