为什么需要?
我们在项目中总是遇到实体类(entity)和视图类(vo)需要相互转换,可能是单个bean、可能是bean集合
暴力解决
思路:单个bean可以用set方法修改属性字段,集合就循环set
BeanUtils.copyProperties复制单个bean的属性字段
优点:当需要set多个字段时可以使用BeanUtils.copyProperties方法,提高代码可读性
import org.springframework.beans.BeanUtils;
BeanUtils.copyProperties(复制前的bean,复制后的bean)
可以将两个bean相同的字段属性复制给后者,即使是null。
JSON.parseArray复制bean集合
List<复制后的bean> beans = JSON.parseArray(JSON.toJSONString(复制前bean集合), 复制后的bean.class);
这样可以得到复制后的bean集合,比for循环BeanUtils.copyProperties方法更快,更优雅。map也是类似的。