I'm looking to implement something in Java along the lines of:
class Foo{
private int lorem; //
private int ipsum;
public setAttribute(String attr, int val){
//sets attribute based on name
}
public static void main(String [] args){
Foo f = new Foo();
f.setAttribute("lorem",1);
f.setAttribute("ipsum",2);
}
public Foo(){}
}
...where a variable is set based on the variable name without the variable names hard-coded and without using any other data structures. Is this possible?
解决方案
Here's how you might implement setAttribute using reflection (I've renamed the function; there are different reflection functions for different field types):
public void setIntField(String fieldName, int value)
throws NoSuchFieldException, IllegalAccessException {
Field field = getClass().getDeclaredField(fieldName);
field.setInt(this, value);
}