代码:
import java.lang.reflect.Field;
public class Test43 {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Obj obj = new Obj();
setProp(obj);
System.out.println(obj);
}
public static void setProp(Object obj) throws NoSuchFieldException, IllegalAccessException {
Class<?> aClass = obj.getClass();
Field propertyame = aClass.getDeclaredField("propertyame");
propertyame.setAccessible(true);
propertyame.set(obj, "value");
}
}
public class Obj {
private String propertyame;
@Override
public String toString() {
return "Obj{" +
"propertyame='" + propertyame + '\'' +
'}';
}
public String getPropertyame() {
return propertyame;
}
public void setPropertyame(String propertyame) {
this.propertyame = propertyame;
}
}