码迷,mamicode.com
首页 > 其他好文 > 详细

通过反射执行get、set方法

时间:2015-04-08 12:27:30      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

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);

 

通过反射执行get、set方法

标签:

原文地址:http://www.cnblogs.com/BensonHe/p/4401752.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!