本帖最后由 xuemeng 于 2013-5-23 11:10 编辑
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//操作bean的指定属性
class Demo {
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException,
NoSuchFieldException, SecurityException, IntrospectionException {
test();
}
public static void test() throws ClassNotFoundException,
IntrospectionException, InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException, NoSuchFieldException, SecurityException {
Class c = Class.forName("cn.itcast.demo.Person");
Object obj = c.newInstance();
// 创建一个属性描述起对象, 并与指定bean属性的名称关联
PropertyDescriptor pd = new PropertyDescriptor("age", c);
// 获取指定bean属性的set方法
Method m1 = pd.getWriteMethod();
// 设置age属性的值为25
m1.invoke(obj, 25);
// 获取属性对象
Field f = c.getField("age");
// 暴力访问
f.setAccessible(true);
// 获取该属性对应的值
int age = (int) f.get(obj);
System.out.println(age);
}
}
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getA() {
return null;
}
晕, 原来方法用错了, 获取的是公共属性
|
|