写一个方法,此方法可将obj对象中名为propertyName的属性的值设置为value.
* @author Administrator
*
*/
public class Text1 {
public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
Person p = new Person("ss", 12);
String pnameString = "dsd";
String value="ssss";
setPro(p, pnameString,value);
}
public static void setPro(Object object, String propertyName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException{
Class clazz = object.getClass();
Field field =clazz.getDeclaredField(propertyName);
field.setAccessible(true);
field.set(object, value);
}
}
class Person{
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String toString() {
return "Person[name=" + name + ", age=" + age + "]";
}
}
//Exception in thread "main" java.lang.NoSuchFieldException: dsd
Field field =clazz.getDeclaredField(propertyName); 这行报错 ,,,请教下高人 |