前言

前面已经学习了Apache Commons Beanutils包里的PropertyUtils和动态bean,接下来将学习剩下的几个工具类,个人觉得还是非常实用的,特别是CollectionUtils;

BeanUtils

简单介绍下两个方法的使用,populate和copyProperties,

populate可以帮助我们把Map里的键值对值拷贝到bean的属性值中;

copyProperties,顾名思义,帮我们拷贝一个bean的属性到另外一个bean中,注意是浅拷贝

如下示例:

/*
* File Name: BeanUtilsTest.java
* Description:
* Author: http://www.cnblogs.com/chenpi/
* Create Date: 2017年5月30日
*/
package apache.commons.beanutils.example.utils; import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map; import org.apache.commons.beanutils.BeanUtils; import apache.commons.beanutils.example.pojo.User; /**
*
* @author http://www.cnblogs.com/chenpi/
* @version 2017年5月30日
*/ public class BeanUtilsTest
{ public static void main(String[] args) throws IllegalAccessException, InvocationTargetException
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "001");
//map.put("address", "hz");
map.put("id", "100");
map.put("state", false);
map.put("others", "others"); User u = new User();
BeanUtils.populate(u, map); System.out.println(u); User u1 = new User();
BeanUtils.copyProperties(u1, u);
System.out.println(u1);
}
}

ConvertUtils

实际上,BeanUtils是依赖ConvertUtils来完成实际山的类型转换,但是有时候我们可能需要自定义转换器来完成特殊需求的类型转换;

自定义类型转换器步骤:

1、定义一个实现类实现Converter接口

2、调用ConvertUtils.register方法,注册该转换器

如下是一个实例,我们会在字符串转换的时候,加上一个前缀:

/*
* File Name: CustomConverters.java
* Description:
* Author: http://www.cnblogs.com/chenpi/
* Create Date: 2017年5月30日
*/
package apache.commons.beanutils.example.utils; import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map; import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter; import apache.commons.beanutils.example.pojo.User; /**
*
* @author http://www.cnblogs.com/chenpi/
* @version 2017年5月30日
*/ public class CustomConverters
{ public static void main(String[] args) throws IllegalAccessException, InvocationTargetException
{
ConvertUtils.register(new StringConverter(), String.class); Map<String, String> map = new HashMap<String, String>();
map.put("name", "001");
map.put("address", "hz");
map.put("id", "100");
map.put("state", "false"); User u = new User();
BeanUtils.populate(u, map); System.out.println(u);
}
} class StringConverter implements Converter {
/**
*
*
* @see org.apache.commons.beanutils.Converter#convert(java.lang.Class, java.lang.Object)
* @param type
* @param value
* @return
*/
@SuppressWarnings("unchecked")
@Override
public <T> T convert(Class<T> type, Object value)
{ if(String.class.isInstance(value)){
return (T) ("###" + value);
}else{
return (T) value;
} }
}

这里有一点需要注意,像BeanUtils, ConvertUtils 和 PropertyUtils工具类都是共享同一个转换器的,这样子虽然用起来很方便,但有时候显得不够灵活,实际上BeanUtilsConvertUtils 和 PropertyUtils都有一个对应的可实例化的类,即BeanUtilsBean、ConvertUtilsBean、PropertyUtilsBean;

它们的功能与BeanUtilsConvertUtils 和 PropertyUtils类似,区别是它们可以实例化,而且每个实例都可以拥有自己的类型转换器;

CollectionUtils

顾名思义,集合工具类,只不过它操作的都是集合里的bean,

利用这个工具类,我们可以批量修改、查询、过滤集合中的bean,甚至还可以拷贝集合中所有bean的某个属性到另外一个集合中,有点Java 8新特性 Streams 的感觉

如下示例:

/*
* File Name: CollectionUtilsTest.java
* Description:
* Author: http://www.cnblogs.com/chenpi/
* Create Date: 2017年5月30日
*/
package apache.commons.beanutils.example.utils; import java.util.ArrayList;
import java.util.Collection;
import java.util.List; import org.apache.commons.beanutils.BeanPropertyValueChangeClosure;
import org.apache.commons.beanutils.BeanPropertyValueEqualsPredicate;
import org.apache.commons.beanutils.BeanToPropertyValueTransformer;
import org.apache.commons.collections.CollectionUtils; import apache.commons.beanutils.example.pojo.User; /**
*
* @author http://www.cnblogs.com/chenpi/
* @version 2017年5月30日
*/ public class CollectionUtilsTest
{ public static void main(String[] args)
{
List<User> userList = new ArrayList<User>();
User u1 = new User();
u1.setId(1l);
u1.setName("chenpi1");
u1.setState(true);
User u2 = new User();
u2.setId(2l);
u2.setName("chenpi2");
User u3 = new User();
u2.setId(3l);
u2.setName("chenpi3");
u2.setState(true);
userList.add(u1);
userList.add(u2);
userList.add(u3); //批量修改集合
BeanPropertyValueChangeClosure closure = new BeanPropertyValueChangeClosure("name",
"updateName"); CollectionUtils.forAllDo(userList, closure); for (User tmp : userList)
{
System.out.println(tmp.getName());
} BeanPropertyValueEqualsPredicate predicate =
new BeanPropertyValueEqualsPredicate( "state", Boolean.TRUE ); //过滤集合
CollectionUtils.filter( userList, predicate );
for (User tmp : userList)
{
System.out.println(tmp);
} //创建transformer
BeanToPropertyValueTransformer transformer = new BeanToPropertyValueTransformer( "id" ); //将集合中所有你user的id传输到另外一个集合上
Collection<?> idList = CollectionUtils.collect( userList, transformer );
for (Object id : idList)
{
System.out.println(id);
}
}
}

参考资料

http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.3/apidocs/org/apache/commons/beanutils/package-summary.html

源码

https://github.com/peterchenhdu/apache-commons-beanutils-example

Apache Commons Beanutils 三 (BeanUtils、ConvertUtils、CollectionUtils...)的更多相关文章

  1. Spring中的BeanUtils与apache commons中的BeanUtils用法[1]

    1. 前言 在开发过程中,经常遇到把要给一个bean的属性赋给另外一个bean.最笨的方法是每个属性都单独写一个,聪明的方法是应用反射写一个工具方法.考虑到这个需求基本每个程序员都会遇到,那么一定已经 ...

  2. Apache Commons Digester 三(规则注解)

    前言 Digester规则的定义除了可以在代码中直接new规则添加到 Digester对象外,还可以用xml配置规则,如下所示: <digester-rules> <pattern ...

  3. Apache Commons 简述

    Apache Commons 是一个关注于可复用的 Java 组件的 Apache 项目.Apache Commons 由三部分构成: Commons Proper - 一个可复用的 Java 组件库 ...

  4. 对于Java Bean的类型转换问题()使用 org.apache.commons.beanutils.ConvertUtils)

    在进行与数据库的交互过程中,由数据库查询到的数据放在 map 中,由 map 到 JavaBean 的过程中可以使用 BeanUtils.populate(map,bean)来进行转换 这里要处理的问 ...

  5. org.springframework.beans.BeanUtils与org.apache.commons.beanutils.BeanUtils的copyProperties用法区别

    知识点 org.springframework.beans.BeanUtils与org.apache.commons.beanutils.BeanUtils都提供了copyProperties方法,作 ...

  6. Java工具类之Apache的Commons Lang和BeanUtils

    Apache Commons包估计是Java中使用最广发的工具包了,很多框架都依赖于这组工具包中的一部分,它提供了我们常用的一些编程需要,但是JDK没能提供的机能,最大化的减少重复代码的编写. htt ...

  7. Apache Commons BeanUtils

    http://commons.apache.org/proper/commons-beanutils/javadocs/v1.9.2/apidocs/org/apache/commons/beanut ...

  8. myeclipse的项目导入到eclipse下,com.sun.org.apache.commons.beanutils.BeanUtils不能导入

    com.sun.org.apache.commons.beanutils.BeanUtils这个包不能引入了怎么办自己下了个org.apache.commons的jar包了之后,改成import or ...

  9. 关闭log4j 输出 DEBUG org.apache.commons.beanutils.*

    2016-03-23 10:52:26,860 DEBUG org.apache.commons.beanutils.MethodUtils - Matching name=getEPort on c ...

随机推荐

  1. 微信小程序之 -----事件

    事件分类      1. 冒泡事件:     当一个组件上的事件被触发后,该事件会向父节点传递.      2. 非冒泡事件:   当一个组件上的事件被触发后,该事件不会向父节点传递.   常见的冒泡 ...

  2. Django contenttypes 应用

    Django contenttypes 应用 什么是Django ContentTypes? Django ContentTypes是由Django框架提供的一个核心功能,它对当前项目中所有基于Dja ...

  3. React-router4 第八篇 ReactCSSTransitionGroup 动画转换

    https://reacttraining.com/react-router/web/example/animated-transitions 动画转换这么高级,其实是又引入了一个组件,没什么特别, ...

  4. 【转】Cron表达式详解

    Cron表达式是一个字符串,字符串以5或6个空格隔开,分为6或7个域,每一个域代表一个含义,Cron有如下两种语法格式: (1) Seconds Minutes Hours DayofMonth Mo ...

  5. 判断jquery对象是否具有某指定属性或者方法的几种方法

    1.typeof 运算符:返回一个用来表示表达式的数据类型的字符串.("number", "string", "boolean", &quo ...

  6. html-day06

    html-day06 1.定位 定位: 1.普通流定位 普通流,又称为文档流 块级元素:从上到下一个一个的排列 行内元素:一行内从左到右的排列 2.浮动定位 1.什么是浮动定位 将元素排除在普通流之外 ...

  7. 2019.02.17 spoj Query on a tree VI(链分治)

    传送门 题意简述:给你一棵nnn个黑白点的树,支持改一个点的颜色,询问跟某个点颜色相同的连通块大小. 思路: 还是链分治 233 记fi,0/1f_{i,0/1}fi,0/1​表示iii的所有颜色为0 ...

  8. 2019swpuj2ee作业一:C/S,B/S的应用的区别

    1.硬件环境不同: C/S 一般建立在专用的网络上, 小范围里的网络环境, 局域网之间再通过专门服务器提供连接和数据交换服务.B/S 建立在广域网之上的, 不必是专门的网络硬件环境,例与电话上网,  ...

  9. python 在unix下json格式显示结果

    在使用命令号输出接口测试结果,发现无法按照期望的json格式进行显示.查阅资料发现python自带强大的工具. 直接上代码: import os,requests url = XXXXXX conte ...

  10. 解决eclipse部署maven时,src/main/resources里面配置文件加载不到webapp下classes路径下的问题

    解决eclipse部署maven时,src/main/resources里面配置文件加载不到webapp下classes路径下的问题. 有时候是src/main/resources下面的,有时候是sr ...