BeanUtils拷贝List数据

工具类:

java 复制代码
package com.ssdl.baize.pub;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import org.springframework.beans.BeanUtils;


public class BeanConvertUtils extends BeanUtils {
    public static <S, T> T convertTo(S source, Supplier<T> targetSupplier) {
        return convertTo(source, targetSupplier, null);
    }
    /**
     * 转换对象
     * @param source         源对象
     * @param targetSupplier 目标对象供应方
     * @param callBack       回调方法
     * @param <S>            源对象类型
     * @param <T>            目标对象类型
     * @return 目标对象
     */
    public static <S, T> T convertTo(S source, Supplier<T> targetSupplier, ConvertCallBack<S, T> callBack) {
        if (null == source || null == targetSupplier) {
            return null;
        }
        T target = targetSupplier.get();
        copyProperties(source, target);
        if (callBack != null) {
            callBack.callBack(source, target);
        }
        return target;
    }

    public static <S, T> List<T> convertListTo(List<S> sources, Supplier<T> targetSupplier) {
        return convertListTo(sources, targetSupplier, null);
    }

    /**
     * 转换对象
     * @param sources        源对象list
     * @param targetSupplier 目标对象供应方
     * @param callBack       回调方法
     * @param <S>            源对象类型
     * @param <T>            目标对象类型
     * @return 目标对象list
     */
    public static <S, T> List<T> convertListTo(List<S> sources, Supplier<T> targetSupplier, ConvertCallBack<S, T> callBack) {
        if (null == sources || null == targetSupplier) {
            return null;
        }
        List<T> list = new ArrayList<>(sources.size());
        for (S source : sources) {
            T target = targetSupplier.get();
            copyProperties(source, target);
            if (callBack != null) {
                callBack.callBack(source, target);
            }
            list.add(target);
        }
        return list;
    }
    /**
     * 回调接口
     *
     * @param <S> 源对象类型
     * @param <T> 目标对象类型
     */
    @FunctionalInterface
    public interface ConvertCallBack<S, T> {
        void callBack(S t, T s);
    }

    /**
     * 将源列表中的数据复制到目标列表中,并返回目标列表。
     *
     * @param sourceList 源列表
     * @param targetClass 目标列表中元素的类
     * @return 目标列表
     */
    public static <S, T> List<T> copyList(List<S> sourceList, Class<T> targetClass) {
        List<T> targetList = new ArrayList<>();
        for (S source : sourceList) {
            T target;
            try {
                target = targetClass.getDeclaredConstructor().newInstance();
                BeanUtils.copyProperties(target, source);
                targetList.add(target);
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException
                    | NoSuchMethodException e) {
                // 处理异常
                e.printStackTrace();
            }
        }
        return targetList;
    }
}

方法测试:

java 复制代码
package com.ssdl.baize.pub;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

public class Test01 {


    public static void main(String[] args) {

    }

    @Test
    public  void test01(){
        // 创建源对象列表
        List<SourceEntity> sourceList = new ArrayList<>();
        sourceList.add(new SourceEntity(1L, "张三"));
        sourceList.add(new SourceEntity(2L, "李四"));
        sourceList.add(new SourceEntity(3L, "王五"));
        // 定义目标对象的供应方(Supplier)
        Supplier<TargetDTO> targetSupplier = TargetDTO::new;
        // 转换对象列表
        List<TargetDTO> targetList = BeanConvertUtils.convertListTo(sourceList, targetSupplier, (source, target) -> {
            // 可以在回调函数中进行额外的处理   比如特定字段的赋值等
            target.setId(source.getId());
        });
        // 输出转换后的目标对象列表
        for (TargetDTO dto : targetList) {
            System.out.println("ID: " + dto.getId() + ", Name: " + dto.getName());
        }
    }


    @Test
    public  void test02(){
        // 单个对象
        SourceEntity zhangSan = new SourceEntity(1L, "张三");
        TargetDTO targetDTO = BeanConvertUtils.convertTo(zhangSan, TargetDTO::new);
        System.out.println("单个对象:"+targetDTO);
        // 单个对象某字段特殊处理
        TargetDTO targetDTO1 = BeanConvertUtils.convertTo(zhangSan, TargetDTO::new, (a, b) -> {
            Long id = a.getId();
            if (1L==id){
                b.setId(2L);
            }
        });
        System.out.println("单个对象某字段特殊处理:"+targetDTO1);

    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class SourceEntity {
        private Long id;

        private String name;
    }


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class TargetDTO {
        private Long id;

        private String name;
    }
}

结果:

相关推荐
ywl47081208715 小时前
常用的集合类有哪些?比如List如何排序?
list·java基础
绝世番茄17 小时前
鸿蒙原生ArkTS布局方式之List+swipeAction侧滑菜单深度解析
华为·list·harmonyos·鸿蒙
2501_943782333 天前
【共创季稿事节】鸿蒙原生 ArkTS 布局实现 Column + List + Navigation 协作导航 — 从列表渲染到页面切换的完整实践
学习·华为·list·harmonyos·鸿蒙
栈溢出了4 天前
Redis 消息队列笔记:List 与 Pub/Sub
redis·笔记·list
世人万千丶22 天前
成语接龙小应用 - HarmonyOS ArkUI 开发实战-TextInput与List列表-PC版本
华为·list·harmonyos·鸿蒙·鸿蒙系统
未若君雅裁22 天前
Python 数据容器详解,list、tuple、str、set、dict 到底怎么选
windows·python·list
苦学的罐头22 天前
C# 协变与逆变深度解析:为什么 IEnumerable<T> 能转换,而 List<T> 不行?
开发语言·c#·list
世人万千丶22 天前
家庭记账本小应用 - HarmonyOS ArkUI 开发实战-Tabs与List组件-PC版本
华为·list·harmonyos·鸿蒙
祭曦念23 天前
【共创季稿事节】鸿蒙原生 ArkTS 布局实践:List + onReachStart/End 分页加载完全指南
windows·list·harmonyos
Irissgwe1 个月前
C++ STL 详解:list 的介绍使用与模拟实现
开发语言·c++·stl·list