package cn.itcast_01;
import java.lang.reflect.Field;
//这是工具类
//通过一个方法反射为Object obj对象的propertyName属性设置为value;
public class Tool {
public void setProperty(Object obj, String propertyName,Object value)
throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {
// 获取字节码文件对象
Class c = obj.getClass();
// 获取成员变量
Field nameField = c.getDeclaredField("propertyName");
// 取消检查
nameField.setAccessible(true);
// 赋值
nameField.set(obj, value);
}
}
package cn.itcast_01;
//这是测试类
public class ToolDemo {
public static void main(String[] args) throws NoSuchFieldException,
SecurityException, IllegalArgumentException, IllegalAccessException {
Person p=new Person();
Tool t=new Tool();
t.setProperty(p,"name", "林青霞");
t.setProperty(p, "age", 27);
System.out.println(p);
}
}
class Person{
private String name;
private int age;
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
|
|