springboot项目中经常会使用对象拷贝, 比如DTO转entity, entity转VO返回前端
单个对象常用的工具类有很多, 比如
#hutool cn.hutool.core.bean.BeanUtil #spring自带 org.springframework.beans.BeanUtils
开发过程中经常遇到的list对象拷贝时, 可能有些同学会循环去处理
ListuserList; List resultList = new ArrayList<>(); for (UserDTO user : userList) { UserEntity userEntity= new UserEntity(); BeanUtil.copyProperties(user, userEntity); resultList .add(userEntity); } return resultList;
整个过程可以封装成如下工具类CopyUtil
public staticListcopyList(List sources, Suppliertarget) { List list = new ArrayList<>(sources.size()); for (S source : sources) { T t = target.get(); BeanUtils.copyProperties(source, t); list.add(t); } return list; }
以上的场景就可以写成, 简化开发
// 入参ListuserList return CopyUtil.copyList(userList, UserEntity::new);



