java拷贝对象列表List copyProperties

开发中,规范不能用mapper查出来的结果直接传,而是需要定义专门用来传数据的DTO对象
这时候查出来的数据就需要用BeanUtil的copyProperties来转一下过去,List略麻烦,遂写个通用工具
先引个万能hutool省事

<!--hutool-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.0.6</version>
</dependency>
/**
 * @Author: Fcx
 * @Date: 2019/11/20 20:45
 * @Version 1.0
 */
public class CopyListUtil {
    private CopyListUtil() {
    }
    /**
     * 列表对象拷贝
     * @param sources 源列表
     * @param clazz 目标列表对象Class
     * @param <T> 目标列表对象类型
     * @param <M> 源列表对象类型
     * @return 目标列表
     */
    public static <T, M> List<T> copyListProperties(List<M> sources, Class<T> clazz) {
        if (Objects.isNull(sources) || Objects.isNull(clazz) || sources.isEmpty()) {
            throw new IllegalArgumentException();
        }
        List<T> targets = new ArrayList<>(sources.size());
        for (M source : sources) {
            T t = ReflectUtil.newInstance(clazz);
            BeanUtil.copyProperties(source,t);
            targets.add(t);
        }
        return targets;
    }
}

开发注意规范哦

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。