package aa;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class Test {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public static void setValueByField(String field,Object o,Object value) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
Class c = o.getClass();
Field[] fields =c.getDeclaredFields();
for(Field ff :fields)
{
if(ff.getName().equals(field))
{
String medthodName = "set"+field.substring(0,1).toUpperCase()+field.substring(1);
c.getDeclaredMethod(medthodName, ff.getType()).invoke(o, value);
}
}
}
public static void main(String[] args) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Test t = new Test();
System.out.println(t.getId());
setValueByField("id",t,new Integer(10));
System.out.println(t.getId());
}
}