In most of the cases java reflection solves the problem:
Example:
public class Foo {
/**
* Gets the name Field.
*
* @return the name
*/
public final String getName() {
return name;
}
/**
* Sets the name Field with the name input value.
*
* @param name the name to set
*/
public final void setName(String name) {
this.name = name;
}
private String name;
}
Now the Reflection Code:
import java.lang.reflect.Field;
....
Foo foo = new Foo();
foo.setName("old Name");
String fieldName = "name";
Class class1 = Foo.class;
try {
System.out.println(foo.getName());
Field field = class1.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(foo, "My New Name");
System.out.println(foo.getName());
} catch (NoSuchFieldException e) {
System.out.println("FieldNotFound: " + e);
} catch (IllegalAccessException e) {
System.out.println("Ilegal Access: " + e);
}
UPDATE:
It's worth mentioning that this approach can be thwarted by a SecurityManager. – Dan Dyer