黑马程序员技术交流社区
标题:
propertyName的属性的值设置为value.
[打印本页]
作者:
www851903307
时间:
2015-2-20 13:02
标题:
propertyName的属性的值设置为value.
写一个方法,此方法可将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); 这行报错 ,,,请教下高人
作者:
wf111sxwf
时间:
2015-2-20 20:12
版主已经回答你了, getDeclaredField() 参数里是字段的名称 要传字符串的
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2