BeanUtils拷贝List数据

news/2024/7/8 2:17:47 标签: list

工具类:

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;
    }
}

方法测试:

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;
    }
}

结果:
在这里插入图片描述


http://www.niftyadmin.cn/n/5536063.html

相关文章

顶级10大AI测试工具

每周跟踪AI热点新闻动向和震撼发展 想要探索生成式人工智能的前沿进展吗&#xff1f;订阅我们的简报&#xff0c;深入解析最新的技术突破、实际应用案例和未来的趋势。与全球数同行一同&#xff0c;从行业内部的深度分析和实用指南中受益。不要错过这个机会&#xff0c;成为AI领…

WebRtc实现1V1音视频通话

WebRtc实现1V1音视频通话 简介应用场景共享桌面的基本原理传统共享桌面WebRTC 共享桌面 相关API基本使用调用本地摄像头播放约束设置 媒体协商过程协议协议的交换与传输 WebRTC 通信过程ICE Candidate&#xff08;ICE 候选者&#xff09; 1V1视频通话 简介 WebRTC&#xff0c;名…

浏览器向客户端提供文件下载(Java实现)

场景&#xff1a; 某一系统需上传黑白名单时&#xff0c;需向用户提供导入模板&#xff0c;这时候需要为客户端提供文件模板下载&#xff0c;用户按照该模板格式填写内容。 package com.wyw.learn.upOrdownload.service;import lombok.RequiredArgsConstructor; import org.spr…

Windows 下用MSYS2 环境为RP2040 编译MicroPython 固件

就是想试试看MSYS2 能兼容到什么地步。自己做了个RP2040 板子&#xff0c;用了4MB 的Flash&#xff0c;默认的Micropython 固件是2MB 的&#xff0c;所以只能自己编译固件。 编译环境 MSYS2 的安装方法、基本配置什么的我就不管了&#xff0c;到处都有文章介绍这个。只提一点…

品牌营销:白加黑经典案例分析,社交电商代运营公司,新零售全案策划

#白加黑营销 #品牌策划 #独特销售主张 #市场占领 品牌的核心目标是盈利&#xff0c;而品牌策划就是为了推动这一目标的实现&#xff0c;使整个过程更加顺利和成功。每一位企业家创建品牌的最终目的都是为了获取更多的利润。然而&#xff0c;理想与现实往往存在差距。在实际操作…

深度学习-数学基础(四)

深度学习数学基础 数学基础线性代数-标量和向量线性代数-向量运算向量加和向量内积向量夹角余弦值 线性代数-矩阵矩阵加法矩阵乘法矩阵点乘矩阵计算的其他内容 人工智能-矩阵的操作矩阵转置&#xff08;transpose&#xff09;矩阵与向量的转化 线性代数-张量&#xff08;tensor…

Pip的缓存机制解析:提升Python包管理效率的秘密武器

Pip的缓存机制解析&#xff1a;提升Python包管理效率的秘密武器 Pip是Python的包管理工具&#xff0c;用于安装和管理Python库。从pip 20.3版本开始&#xff0c;引入了一项重要的特性——缓存机制。这一机制显著提升了包安装的速度和效率&#xff0c;尤其是在网络条件不佳或需…

技术赋能政务服务:VR导视与AI客服在政务大厅的创新应用

在数字化转型的浪潮中&#xff0c;政务大厅作为服务民众的前沿阵地&#xff0c;其服务效率和质量直接影响着政府形象和民众满意度。然而&#xff0c;许多政务大厅仍面临着缺乏智能化导航系统的挑战&#xff0c;这不仅增加了群众的办事难度&#xff0c;也降低了服务效率。维小帮…