java内省的使用_Java内省IntroSpector应用

//使用BeanUtils工具包操作JavaBean28 String userName=BeanUtils.getProperty(userInfo, propertyName);29 System.out.println("userName="+userName);30 BeanUtils.setProperty(userInfo, propertyName,"linjiqin");31 userName=BeanUtils.getProperty(userInfo, propertyName);32 System.out.println("userName="+userName);33 }34 35 /**36 * 设置属性37 *38 *@paramclazz 对象名39 *@parampropertyName 属性名40 *@paramvalue 属性值41 */42 privatestaticvoidsetProperty(Object clazz, String propertyName, Object value)43 throwsIntrospectionException,IllegalAccessException, InvocationTargetException{44 //方法一45 /*PropertyDescriptor pd=new PropertyDescriptor(propertyName, clazz.getClass());46 Method methodSet=pd.getWriteMethod();47 methodSet.invoke(clazz, value);*/48 49 //方法二50 BeanInfo beanInfo=Introspector.getBeanInfo(clazz.getClass());51 PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors();52 for(PropertyDescriptor pd:pds){53 if(propertyName.equals(pd.getName())){54 Method methodSet=pd.getWriteMethod();55 methodSet.invoke(clazz, value);56 break;57 }58 }59 }60 61 /**62 * 获取属性63 *64 *@paramclazz 对象名65 *@parampropertyName 属性名66 *@return67 *@throwsIntrospectionException68 *@throwsInvocationTargetException69 *@throwsIllegalAccessException70 *@throwsIllegalArgumentException71 */72 privatestaticObject getProperty(Object clazz, String propertyName)73 throwsIntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{74 //方法一75 /*PropertyDescriptor pd=new PropertyDescriptor(propertyName, clazz.getClass());76 Method methodGet=pd.getReadMethod();77 return methodGet.invoke(clazz);*/78 79 //方法二80 Object retVal=null;81 BeanInfo beanInfo=Introspector.getBeanInfo(clazz.getClass());82 PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors();83 for(PropertyDescriptor pd:pds){84 if(propertyName.equals(pd.getName())){85 Method methodGet=pd.getReadMethod();86 retVal=methodGet.invoke(clazz);87 break;88 }89 }90 returnretVal;91 }92 93 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值