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

1.属性的动态getter,setter

在这框架满天飞的年代,不能事事都保证执行getter,setter函数了,有时候属性是要需要根据名字动态取得的,就像这样:  
BeanUtils.getProperty(myBean,"code");
而BeanUtils更强的功能是直接访问内嵌对象的属性,只要使用点号分隔。
BeanUtils.getProperty(orderBean, "address.city");
相比之下其他类库的BeanUtils通常都很简单,不能访问内嵌的对象,所以经常要用Commons BeanUtils替换它们。
BeanUtils还支持List和Map类型的属性。如下面的语法即可取得顾客列表中第一个顾客的名字
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 = ....

不妨写一个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 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.2 PropertyUtils,获取属性的Class类型
     public static Class getPropertyType(Object bean, String name)
4.3 ConstructorUtils,动态创建对象
      public static Object invokeConstructor(Class klass, Object arg)
4.4 MethodUtils,动态调用方法
    MethodUtils.invokeMethod(bean, methodName, parameter);

4.5 动态Bean 见用DynaBean减除不必要的VO和FormBean

转载于:https://www.cnblogs.com/sandaoliu/p/3720533.html

Beanutils基本用法相关推荐

  1. (转载)BeanUtils.copyProperties() 用法

    BeanUtils.copyProperties() 用法 标签: hibernateuserjdbc数据库strutsjava 2009-10-17 23:04 35498人阅读 评论(6) 收藏  ...

  2. BeanUtils.copyProperties() 用法

    转载自 https://blog.csdn.net/jdjdndhj/article/details/62056137 第一步: BeanUtils.copyProperties()与Property ...

  3. BeanUtils.populate()用法

    BeanUtils.populate()源码分析 BeanUtils.populate( user , request.getParameteMap() ) 看完这两篇应该可以对这个方法有一个更深的认 ...

  4. 对象复制的7种方法,还是Spring的最好用!

    日常编程中,我们会经常会碰到对象属性复制的场景,就比如下面这样一个常见的三层 MVC 架构. 当我们在上面的架构下编程时,我们通常需要经历对象转化,将业务请求流程经历三层机构后需要把 DTO 转为DO ...

  5. springboot+vue练手级项目,真实的在线博客系统

    文章目录 spring boot 练手实战项目说明 基础知识 面试准备 1. 工程搭建 1.1 新建maven工程 1.1.2遇到的bug 1.2 配置 1.3 启动类 2. 首页-文章列表 2.1 ...

  6. Java笔记--自己工作涉及

    集合工具-CollUtil CollUtil.newArrayList方法表示新建ArrayList并填充元素 HashMap<String, String> map = CollUtil ...

  7. Java常用知识补充

    Java常用知识补充 目录 Java常用知识补充 1.sort与comparator 1)Java的sort 2)Java 的Comparator 2.java lamda 3.java集合 Arra ...

  8. BeanUtils.copyProperties与PropertyUtils.copyProperties用法及区别

    转自:http://www.cnblogs.com/fayf/articles/1272982.html 一.简介:BeanUtils提供对Java反射和自省API的包装.其主要目的是利用反射机制对J ...

  9. BeanUtils之populate的用法

    BeanUtils之populate的用法 BeanUtils.populate( Object bean, Map properties ), 这个方法会遍历map<key, value> ...

  10. BeanUtils.copyProperties的用法

    前言 org.springframework.beans.BeanUtils,它提供了对java反射和自省API的包装.它里面还有很多工具类,这里我们介绍一下copyProperties. 我们如果有 ...

最新文章

  1. 可以发张图片做链接用吗
  2. linux vg 镜像,Linux下载_Linux系统各种版本ISO镜像下载(redhat,centos,oracle,ubuntu,openSUSE)...
  3. 各种Oracle常见操作2
  4. pythondevp2p_以太坊GO、JAVA、PYTHON、RUBY、JS客户端介绍
  5. Android之关于电话录音原理,目前的方法还是只能录MIC
  6. mysql导入source注意点
  7. 高负载高并发网站架构分析
  8. php的get和post,PHP中GET和POST区别
  9. 交互设计的职能:交互设计师具体做什么
  10. win7计算机搜索文件搜不到,Win7搜不到文件如何解决?Win7搜不到文件的解决方法...
  11. R语言柯西概率分布(cauchy distribution)函数(dcauchy, pcauchy, qcauchy rcauchy)实战
  12. Ubuntu查看USB串口号【简单、好记、好看】
  13. 国内APP消息推送机制以及微信消息延迟问题剖析
  14. 2的10次方-1的python表达式_python计算数学表达式
  15. 微信打不开文件怎么办
  16. 进程文件ntvdm.exe
  17. 【十八掌●基本功篇】第一掌:Java之IO
  18. Latex在论文中输出微米和cm-1
  19. 电邮地址_电子邮件如何运作?
  20. 5.5 listen() --- 如果有“人”,请叫我?

热门文章

  1. java rsa2加密算法_java RSA加密解密
  2. ImportError: No module named ‘keras_contrib‘
  3. logistic回归__基于Python和Numpy函数库
  4. python实现判断给定列表是否存在重复元素,且索引差小于k
  5. GitHub超详细图文攻略 - Git客户端下载安装 GitHub提交修改源码工作流程 Git分支 标签 过滤 Git版本工作流
  6. linux安装mysql 5.7_linux安装mysql5.7.24
  7. mysql加begin报错,MySQL存储过程例子,不能在if else里面用begin end否则会报错Error Code:1064解决...
  8. BootStrap的应用——实现黑马旅游网页面
  9. php+getdomfromstring,php使用simple_html_dom解析HTML示例
  10. autosar架构_(1)Testing-Autosar架构及模块描述