对JAVA Bean使用PropertyDescriptor反射调用JAVA方法

来源:互联网 发布:网络在线兼职教师招聘 编辑:程序博客网 时间:2024/06/06 19:30

import java.beans.PropertyDescriptor;import java.lang.reflect.Method;public class MyTestBean {public static void main(String[] args) throws Exception {// TODO Auto-generated method stubMyBean 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;}@Overridepublic String toString() {// TODO Auto-generated method stubreturn this.name+"..."+this.age;}}


0 0
原创粉丝点击