使用BeanUtils工具包操作JavaBean-2

在操作之前就先下Apache官网上下载相就的工具,这里我们要下载commons-beanutils 和commons-logging,我下载的版本是commons-beanutils-1.8.3和commons-logging-1.1.1,然后我选择的是commons-beanutils-1.8.3.jar和commons-logging-1.1.1.jar这两个jar包

 

演示用Eclipse如何加入jar包,先只是引入beanutils包,等程序运行出错后再引入logging

在前面的内省例子的基础上,用BeanUtils类先get原来设置好的属性,再将其set为一个新值。

get属性时返回的结果为该属性本来的类型,set属性时只接受该属性本来的类型。、

 

 

 

BeanUtils.setProperty(pt1, "x","9"); //这里的9String类型

PropertyUtils.setProperty(pt1, "x", 9); //这里的是int类型

//这两个类BeanUtilsPropertyUtils,前者能自动将int类型转化,后者不能

import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.PropertyUtils; public class IntroSpectorTest { public static void main(String[] args) throws Exception{ ReflectPoint1 pt1 = new ReflectPoint1(3,5); String propertyName = "x"; Object retval = getProperty(pt1, propertyName); System.out.println(retval); Object value = 7; setProperty(pt1, propertyName, value); System.out.println(BeanUtils.getProperty(pt1, "x")); //这里使用了Apache公司开发的BeanUtils工具包 BeanUtils.setProperty(pt1, "x","9"); //这里的9是String类型 PropertyUtils.setProperty(pt1, "x", 9); //这里的是int类型 //这两个类BeanUtils和PropertyUtils,前者能自动将int类型转化,后者不能 System.out.println(pt1.getX()); BeanUtils.setProperty(pt1, "birthday.time", "111"); //一级一级调用实现 System.out.println(BeanUtils.getProperty(pt1, "birthday.time")); // Map map = {name:"xxx",age:18}; java 7新特性 // BeanUtils.setProperty(map, "name", "zzz"); 可以实现map功能 } private static void setProperty(Object pt1, String propertyName, Object value) throws IntrospectionException, IllegalAccessException, InvocationTargetException { PropertyDescriptor pd2 = new PropertyDescriptor(propertyName, pt1.getClass()); //propertyName为字段名 //javaBean的操作方式 Method methodSetx = pd2.getWriteMethod(); //调用该字段的setxxx方法 methodSetx.invoke(pt1, value); } private static Object getProperty(Object pt1, String propertyName) throws IntrospectionException, IllegalAccessException, InvocationTargetException { /* PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt1.getClass()); Method methodGetX = pd.getReadMethod();//调用该字段的getxxxx方法 Object retval = methodGetX.invoke(pt1); return retval; */ BeanInfo beaninfo = Introspector.getBeanInfo(pt1.getClass()); PropertyDescriptor[] pds = beaninfo.getPropertyDescriptors(); Object retVal = null; for (PropertyDescriptor pd: pds) { if (pd.getName().equals(propertyName)) { Method methodGetX = pd.getReadMethod(); retVal = methodGetX.invoke(pt1); break; } } return retVal; } }

 

 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值