You can use a map:
Map<String, String> data = new HashMap();
data.put("myVariableName", "200");
String value = data.get("myVariableName");
System.out.println(value); //shows 200
Or, on your own using reflection:
private class Attribute {
public Object target;
public String varName;
public Class clazz;
public Attribute(String varName, Object target, Class clazz) {
this.varName = varName;
this.target = target;
this.clazz = clazz;
}
public void value(String value) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
//Call setter method
Method method = target.getClass().getMethod("set" + varName, clazz);
method.invoke(target, value);
}
}
Example:
public class Person {
private String name;
public String getName() {
return name;
}
//This method must exist
public void setName(String name) {
this.name = name;
}
public void set(String varName) throws Exception {
return new Attribute(varName, this, Person.class);
}
}
And the main:
public static void main(String[] args) throws Exception {
Person p = new Person();
p.set("Name").value("John"); //Notice the first letter uppercase
}
I don't recommend to use this solution, but it is what you are looking for, so... I recommend you to use a wrapped Map
.