一、场景
最近在项目中需要用到复制对象属性值的需求,第一时间就想到了BeanUtils这个方法。
二、BeanUtils 分类
Spring:org.springframework.beans.BeanUtils;
Apache:org.apache.commons.beanutils.BeanUtils;
三、使用Api
都是将目标对象属性值复制到新对象属性中,但是参数有所不同,需要注意
//Spring org.springframework.beans.BeanUtils;
// source:源对象,target:目标对象
BeanUtils.copyProperties(source,target);
// Apache org.apache.commons.beanutils.BeanUtils;
BeanUtils.copyProperties(target,source);
四、使用细节差异
业务场景:需要将一个Map 对象的属性赋值给一个新的对象。使用Apache BeanUtils可以做到,而Spring BeanUtils 不行。
五、遇到的坑
在使用 BeanUtils.copyProperties() 时target 类对象访问修饰符没有设置为public。(当时使用了内部类),因为BeanUtils.copyProperties() 底层使用了反射。如果没有设置为public,则反射不到该类。