import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.*;
public class IntrospectionTest {
public static void main(String[] args)
throws IntrospectionException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException{
Person p = new Person(300, "Panda", 20);
String property ="name"; //这里是要设置的名称,与类中的
//某个域名称要一值,因为只是你需要修改的域
getMethod(p, property); //获得name的域的值
Object name = "Tiger";
setMethod(p, property, name); //修改name的值为Tiger
}
/**
* 此方法是用javabean内省方式,修改域中的数据
* 步骤:
* 1、利用 PropertyDescriptor(String propertyName, Class<?> beanClass)
通过调用 getFoo 和 setFoo 存取方法,为符合标准 Java 约定的属性构造一个
PropertyDescriptor。
第一个参数传递 需要修改的名称,第二个参数传递需要修改类的Class,不需要实例化
2、使用getWriteMethod()得到一个类中的get方法,对应构造中propertyName的域
3、使用 Object invoke(Object obj, Object... args)对带有指定参数的指定对象
调用由此 Method 对象表示的底层方法。
第一个参数是实例化以后需要修改的对象,第二个参数是需要修改的值。
* @param p 代表实例化的一个person类
* @param property 需要修改的域
* @param name 修改后的域
* @throws IntrospectionException
* @throws IllegalAccessException
* @throws InvocationTargetException
*
*/
private static void setMethod(Person p, String property, Object name)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor prop = new PropertyDescriptor(property, Person.class);
Method setMth = prop.getWriteMethod();
setMth.invoke(p, name);
getMethod(p, property);
}
/**
* 与上述方法类似,invoke方法更简单,因为get方法,只是获取,所以不需要传递更新值
* @param p
* @param property
* @throws IntrospectionException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private static void getMethod(Person p, String property)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor prop = new PropertyDescriptor(property, Person.class);
Method readMth = prop.getReadMethod();
Object retVal = readMth.invoke(p);
System.out.println(retVal);
}
}
下面是一个普通的JavaBean文件,提供3个域:
public class Person {
private int age;
private String name;
private long id;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(int age, String name, long id) {
super();
this.age = age;
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}