通过反射执行get、set方法

Class clazz = sourceObj.getClass();

1、获取所有属性

BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();

2、获取指定属性
PropertyDescriptor pd = new PropertyDescriptor(fieldName, clazz);

Method getMethod = pd.getReadMethod();// 获得get方法
Object val = getMethod.invoke(sourceObj);// 执行get方法返回值

Method setMethod = pd.getWriteMethod();//获得set方法

setMethod .invoke(sourceObj, newVal);

 

posted @ 2015-04-08 10:43  涂墨留香  阅读(1145)  评论(0编辑  收藏  举报