public class Test2 {
public static void main(String[] args) {
Point p = new Point();
p.setX(1);
p.setY(2);
System.out.println("原始的p:"+p);
setProperty(p, "x", 5);
System.out.println("设值的p:"+p);
}
/**
* 给某个对象的属性设置某个值,属性名为propertyName,值是value,设置的对象是obj
* @param obj
* @param propertyName
* @param value
*/
public static void setProperty(Object obj, String propertyName, Object value) {
try {
// 获取属性对象Field
Field field = obj.getClass().getDeclaredField(propertyName);
// 设置可以访问
field.setAccessible(true);
// 设值
field.set(obj, value);
} catch (Exception e) {
e.printStackTrace();
System.out.println("修改失败!");
}
}
}
class Point {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return "x = "+x+", y = "+y;
}
}
|
|