import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
public class MyTestBean {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
MyBean myBean=new MyBean();
//创建一个描述MyBean name属性的一个对象
PropertyDescriptor propName=new PropertyDescriptor("name", myBean.getClass());
PropertyDescriptor propAge=new PropertyDescriptor("age", myBean.getClass());
//根据propName对象,获得这个属性的些方法
Method methodName=propName.getWriteMethod();
//执行myBean的底层set方法
methodName.invoke(myBean, "zhangsan");
Method methodAge=propAge.getWriteMethod();
methodAge.invoke(myBean, 22);
System.out.println(myBean);
}
}
class MyBean{
private String name;
private int age;
public MyBean(){
}
public MyBean(String name, int age) {
this.name = name;
this.age = 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;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.name+"..."+this.age;
}
}
对JAVA Bean使用PropertyDescriptor反射调用JAVA方法
最新推荐文章于 2024-04-17 11:01:08 发布