package com.itheima;
import java.lang.reflect.Field;
/*
* 2、 写一个方法,此方法可将obj对象中名为propertyName的属性的值设置为value.
public void setProperty(Object obj, String propertyName, Object value){
}
*/
class obj {
public String propertyName;
}
public class Test2 {
public static void setProperty(Object obj, String propertyName, Object value)
throws IllegalArgumentException, IllegalAccessException,
NoSuchFieldException, SecurityException, InstantiationException {
Class clazz = obj.getClass();
Field f = clazz.getDeclaredField(propertyName);
obj o = (obj)clazz.newInstance();
f.set(o, value);
}
public static void main(String[] args) throws IllegalArgumentException,
IllegalAccessException, NoSuchFieldException, SecurityException,
InstantiationException {
obj o = new obj();
setProperty(o, "propertyName", "vlaue");
System.out.println(o.propertyName);
}
}
|