1、 写一个方法,此方法可将obj对象中名为propertyName的属性的值设置为value.
public void setProperty(Object obj, String propertyName, Object value){
}
public class Main {
public static void main(String[] args) throws NoSuchFieldException,
SecurityException, IllegalArgumentException, IllegalAccessException {
Person p = new Person();
Person.setProperty(p, "propertyName", "value");
}
}
class Person extends Object {
private String propertyName = "abc";
public String toString() {
return propertyName;
}
public static void setProperty(Object obj, String propertyName, Object value)
throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {
//反射
Class c = obj.getClass();
//得到需要的量
Field f = c.getDeclaredField("propertyName");
// Method m = c.getDeclaredMethod(name, parameterTypes);
//语言校验
f.setAccessible(true);
f.set(obj, value);
System.out.println(obj.toString());
}
} |
|