Is it possible to get the variable name of the current instance in the object's setter?
Something like this
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;
}
}
}
If it's not possible using standard utilities then it's possible to create some kind of annotation to store there variable name and then use it in setter?
When I try to do like this - the annotation is null. I create annotation
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface FieldName {
String fieldName();
}
Then I add it to field
public class Class {
@FieldName(fieldName = "dataType")
private DataType dataType;
}
And when I try to get it in the getter
of DataType
- the annotation FieldName
is null.
private String wrapGetter(String requiredFieldName, String dataTypeField) {
FieldName fieldName = this.getClass().getAnnotation(FieldName.class);
if (fieldName.fieldName().equals(requiredFieldName)) {
return dataTypeField;
} else {
return dataTypeField;
}
}