设为首页 收藏本站
查看: 674|回复: 0

[经验分享] BeanUtils--org.apache.commons.beanutils.BeanUtils

[复制链接]

尚未签到

发表于 2017-1-7 09:19:27 | 显示全部楼层 |阅读模式
转自:http://www.blogjava.net/huanzhugege/archive/2007/02/05/97964.html


BeanUtils
BeanUtils是Apache-Commons项目提供的另一个非常方便的类库,通过这个类库能够更方便的使用反射。最常用的类是BeanUtils(org.apache.commons.beanutils包中),使用这个类能通过名字访问一个Bean中的某个属性。
通过BeanUtils.getProperty(person,”age”)能得到person的age属性。此方法还支持内嵌对象,比如BeanUtils.getProperty(person,”manager.name”)就能得到person的manager属性的name属性。还支持List和Map类型的属性,如下面的语法即可取得Order的顾客列表中第一个顾客的名字BeanUtils.getProperty(orderBean, "customers[1].name")。 使用BeanUtils.setProperty方法则可以设置javaBean的属性值。
ConstructorUtils提供了调用构造函数的方法,使用public static Object invokeConstructor(Class klass, Object arg)可以直接调用某个类的构造函数。
MethodUtils提供了调用bean方法的方法,使用MethodUtils.invokeMethod(bean, methodName, parameter);可以直接调用某个类的某个方法。
PropertyUtils提供了更详细的属性访问方法,使用public static Class getPropertyType(Object bean, String name)获取属性的Class类型。
UserInfo userInfo = (UserInfo) ConstructorUtils.invokeConstructor(
    UserInfo.class, new Object[] {});
PersonInfo personInfo = (PersonInfo) ConstructorUtils
    .invokeConstructor(PersonInfo.class, new Object[] {});
BeanUtils.setProperty(personInfo, "age", new Integer(20));
BeanUtils.setProperty(personInfo, "name", "Tom");
BeanUtils.setProperty(userInfo, "number", "admin");
  BeanUtils.setProperty(userInfo, "person", personInfo);
System.out.println(BeanUtils.getProperty(userInfo, "person.name"));
BeanUtils.setProperty(userInfo, "person.name","xdx");
System.out.println(BeanUtils.getProperty(userInfo, "person.name"));
System.out.println(PropertyUtils.getPropertyType(userInfo,"person"));
运行结果:
Tom
xdx
class com.cownew.PIS.basedata.common.PersonInfo



---------------------------------------------------------------------

 
  Beanutils用了魔术般的反射技术,实现了很多夸张有用的功能,都是C/C++时代不敢想的。无论谁的项目,始终一天都会用得上它。我算是后知后觉了,第一回看到它的时候居然错过。
  1.属性的动态getter、setter

在这框架满天飞的年代,不能事事都保证执行getter,setter函数了,有时候属性是要根据名字动态取得的,就像这样:  

BeanUtils.getProperty(myBean,"code");

而Common BeanUtils的更强功能在于可以直接访问内嵌对象的属性,只要使用点号分隔。

BeanUtils.getProperty(orderBean, "address.city");

相比之下其他类库的BeanUtils通常都很简单,不能访问内嵌的对象,所以有时要用Commons BeanUtils来替换它们。

BeanUtils还支持List和Map类型的属性,如下面的语法即可取得Order的顾客列表中第一个顾客的名字

BeanUtils.getProperty(orderBean, "customers[1].name");

其中BeanUtils会使用ConvertUtils类把字符串转为Bean属性的真正类型,方便从HttpServletRequest等对象中提取bean,或者把bean输出到页面。

而PropertyUtils就会原色的保留Bean原来的类型。
  2.BeanCompartor 动态排序

还是通过反射,动态设定Bean按照哪个属性来排序,而不再需要在实现bean的Compare接口进行复杂的条件判断。

List peoples = ...; // Person对象的列表Collections.sort(peoples, new BeanComparator("age"));

  如果要支持多个属性的复合排序,如"Order By lastName,firstName"

ArrayList sortFields = new ArrayList();sortFields.add(new BeanComparator("lastName"));sortFields.add(new BeanComparator("firstName"));ComparatorChain multiSort = new ComparatorChain(sortFields);Collections.sort(rows,multiSort);

  其中ComparatorChain属于jakata commons-collections包。
如果age属性不是普通类型,构造函数需要再传入一个comparator对象为age变量排序。
另外, BeanCompartor本身的ComparebleComparator, 遇到属性为null就会抛出异常, 也不能设定升序还是降序。这个时候又要借助commons-collections包的ComparatorUtils.

   Comparator mycmp = ComparableComparator.getInstance();
   mycmp = ComparatorUtils.nullLowComparator(mycmp);  //允许null
   mycmp = ComparatorUtils.reversedComparator(mycmp); //逆序
   Comparator cmp = new BeanComparator(sortColumn, mycmp);

3.Converter 把Request或ResultSet中的字符串绑定到对象的属性  经常要从request,resultSet等对象取出值来赋入bean中,如果不用MVC框架的绑定功能的话,下面的代码谁都写腻了。

   String a = request.getParameter("a");   bean.setA(a);   String b = ....
bean.setB(b);
......

  不妨写一个Binder自动绑定所有属性:

    MyBean bean = ...;    HashMap map = new HashMap();    Enumeration names = request.getParameterNames();    while (names.hasMoreElements())    {      String name = (String) names.nextElement();      map.put(name, request.getParameterValues(name));    }    BeanUtils.populate(bean, map);

  其中BeanUtils的populate方法或者getProperty,setProperty方法其实都会调用convert进行转换。
    但Converter只支持一些基本的类型,甚至连java.util.Date类型也不支持。而且它比较笨的一个地方是当遇到不认识的类型时,居然会抛出异常来。 对于Date类型,我参考它的sqldate类型实现了一个Converter,而且添加了一个设置日期格式的函数。
要把这个Converter注册,需要如下语句:

    ConvertUtilsBean convertUtils = new ConvertUtilsBean();
   DateConverter dateConverter = new DateConverter();
   convertUtils.register(dateConverter,Date.class);



//因为要注册converter,所以不能再使用BeanUtils的静态方法了,必须创建BeanUtilsBean实例
BeanUtilsBean beanUtils = new BeanUtilsBean(convertUtils,new PropertyUtilsBean());
beanUtils.setProperty(bean, name, value);

4 其他功能
4.1 ConstructorUtils,动态创建对象

     public static Object invokeConstructor(Class klass, Object arg)

4.2 MethodUtils,动态调用方法
    MethodUtils.invokeMethod(bean, methodName, parameter);




4.3 PropertyUtils,当属性为Collection,Map时的动态读取:
Collection: 提供index

   BeanUtils.getIndexedProperty(orderBean,"items",1);

或者
  BeanUtils.getIndexedProperty(orderBean,"items[1]");

Map: 提供Key Value
  BeanUtils.getMappedProperty(orderBean, "items","111");//key-value goods_no=111

或者
  BeanUtils.getMappedProperty(orderBean, "items(111)")




4.4 PropertyUtils,直接获取属性的Class类型


     public static Class getPropertyType(Object bean, String name)

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-324933-1-1.html 上篇帖子: Crazy Programmer Homework One: Apache Xalan Studying 下篇帖子: Apache指南: .htaccess文件使用手册
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表