是否可以在对象的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