BeanUtils

BeanUtils工具包是由Apache公司所开发,主要是方便程序员对Bean类能够进行简便的操作。

BeanUtils一共分4个包:

org.apache.commons.beanutils

org.apache.commons.beanutils.converters

org.apache.commons.beanutils.locale

org.apache.commons.beanutils.locale.converters

其中需要我们特别关注的是这个org.apache.commons.beanutils包,其他包都是起辅助作用的。其中上面两个没有针对本地化的任何处理,执行效率高。下面两个对本地化有要求。

BeanUtils类

主要提供了对于JavaBean进行各种操作,比如对象,属性复制等等。

BeanUtils设置属性值的时候,如果属性是基本数据类型,那么BeanUtils会自动帮我们进行数据类型的转换,并且BeanUtils设置属性的时候也是依赖于底层的getter和setter方法。如果设置的属性值是其他的引用数据类型,此时必须要注册一个类型转换器才能实现自动的转换(参考下面的ConvertUtils)

主要方法 描述
cloneBean(Object bean) 对象的克隆
copyProperties(Object dest, Object orig) 对象的拷贝
copyProperty(Object bean, String name, Object value) 拷贝指定的属性值到指定的bean
setProperty(Object bean, String name, Object value) 设置指定属性的值
populate(Object bean, Map<String,? extends Object> properties) 将map数据拷贝到javabean中(map的key要与javabean的属性名称一致)

注:copyProperty与setProperty,日常使用时推荐copyProperty。如果我们需要自定义实现populate()方法,那么我们可以override setProperty()方法.

// JavaBean
public class Animal {
    private String name;
    private int age;
    private String color;
    private String sex;

    public Animal() {
    }

    getXxx和setXxx省略……
}
/**
 * BeanUtils
 */
@Test
public void test1() throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("name", "tuantuan");
    map.put("age", 3);
    map.put("color", "black");
    map.put("sex", "female");

    // 将map数据拷贝到javabean中
    Animal a1 = new Animal();
    BeanUtils.populate(a1, map);
    System.out.println(a1); // Animal [name=tuantuan, age=3, color=black, sex=female]

    // 对象的拷贝
    Animal a2 = new Animal();
    BeanUtils.copyProperties(a2, a1);
    System.out.println(a2);// Animal [name=tuantuan, age=3, color=black, sex=female]

    // 拷贝指定的属性
    Animal a3 = new Animal();
    BeanUtils.copyProperty(a3, "name", "yuanyuan");
    System.out.println(a3); // Animal [name=yuanyuan, age=0, color=null, sex=null]

    // 设置指定的属性
    BeanUtils.setProperty(a3, "sex", "male");
    System.out.println(a3); // Animal [name=yuanyuan, age=0, color=null, sex=male]

    // 克隆对象
    Object object = BeanUtils.cloneBean(a3);
    System.out.println(object); // Animal [name=yuanyuan, age=0, color=null, sex=male]
}

ConvertUtils

这个工具类的职能是在字符串和指定类型的实例之间进行转换。 实际上,BeanUtils是依赖ConvertUtils来完成类型转换,但是有时候我们可能需要自定义转换器来完成特殊需求的类型转换;

主要方法 描述
convert(Object value, Class<?> targetType) 将给定的value转换成指定的Class类型
// 将整型转换成字符串
Object object = ConvertUtils.convert(123, String.class);
String typeName = object.getClass().getTypeName();
System.out.println(typeName);

// 将日期转换成字符串
Object object2 = ConvertUtils.convert(new Date(), String.class);
String typeName2 = object2.getClass().getTypeName();
System.out.println(typeName2);

// 将字符串转换成Double
Object object3 = ConvertUtils.convert("123", Double.class);
String typeName3 = object3.getClass().getTypeName();
System.out.println(typeName3);

自定义类型转换:

自定义转换器,实现Converter接口,重写convert方法

class MyConverter implements Converter {
    private static SimpleDateFormat format;

    public MyConverter(String pattern) {
        format = new SimpleDateFormat(pattern);
    }

    @Override
    public Object convert(Class type, Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof String) {
            String tmp = (String) value;
            if (tmp.trim().length() == 0) {
                return null;
            } else {
                try {
                    return format.parse(tmp);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        } else {
            throw new ConversionException("not String");
        }
        return value;
    }
}

使用

MyConverter converter = new MyConverter("yyyy-MM-dd HH:mm:ss");
// 注册该转换器
ConvertUtils.register(converter, Date.class);
Object object3 = ConvertUtils.convert("2019-03-13 14:04:00", Date.class);
System.out.println(object3.getClass().getTypeName());
System.out.println(object3);
// BeanUtils设置属性时,自动进行类型转换
MyConverter converter = new MyConverter("yyyy-MM-dd HH:mm:ss");
// 注册该转换器
ConvertUtils.register(converter, Date.class);
Animal a5 = new Animal();
BeanUtils.copyProperty(a5, "birth", "2019-03-13 14:04:00");
System.out.println(a5);// Animal [name=null, age=0, color=null, sex=null, birth=Wed March 13 14:04:00 CST 2019]

PropertyUtils

BeanUtils与PropertyUtils这两个类几乎有一摸一样的功能,唯一的区别是:BeanUtils在对Bean赋值是会进行类型转化。
举例来说也就是在copyProperty时只要属性名相同,就算类型不同,BeanUtils也可以进行copy;而PropertyBean则可能会报错!!当然2个Bean之间的同名属性的类型必须是可以转化的,否则用BeanUtils一样会报错。若实现了org.apache.commons.beanutils.Converter接口则可以自定义类型之间的转化。由于不做类型转化,用PropertyUtils在速度上会有很大提高!

CollectionUtils

利用这个工具类,我们对集合进行修改、查询、过滤等操作
CollectionUtils属于commons-collections包

String[] arrA = new String[]{"1", "2", "3"};
String[] arrB = new String[]{"1", "a", "b"};
List<String> listA = Arrays.asList(arrA);
List<String> listB = Arrays.asList(arrB);

// 判断集合是否为 空
System.out.println(CollectionUtils.isEmpty(listA));// false
System.out.println(CollectionUtils.isEmpty(listB));// false

// 判断集合是否为 不为空
System.out.println(CollectionUtils.isNotEmpty(listA));// true
System.out.println(CollectionUtils.isNotEmpty(listB));// true

// 两个集合的比较
System.out.println(CollectionUtils.isEqualCollection(listA, listB));// false

// 集合的操作
// 取并集
System.out.println(CollectionUtils.union(listA, listB));// [1, a, 2, b, 3]
// 取交集
System.out.println(CollectionUtils.intersection(listA, listB));// [1]
// 取交集的补集
System.out.println(CollectionUtils.disjunction(listA, listB));// [a, 2, b, 3]
// 取集合相减
System.out.println(CollectionUtils.subtract(listA, listB));// [2, 3]
System.out.println(CollectionUtils.subtract(listB, listA));// [a, b]

List<String> listC = new ArrayList<>();
listC.add("1");
listC.add("2");
listC.add("3");
String[] arrC = {"4", "5", "6"};
// 向集合中添加值
CollectionUtils.addAll(listC, arrC);
System.out.println(listC);// [1, 2, 3, 4, 5, 6]
posted @ 2019-03-13 15:41  小老弟  阅读(5257)  评论(1编辑  收藏  举报