BeanUtils实体类转换

序言

 

代码

org.springframework.beans.BeanUtils

复制代码
package com.bitauto.oa.utils;

import com.alibaba.fastjson.JSON;
import com.bitauto.oa.domain.User;
import com.bitauto.oa.domain.UserDto;
import org.apache.commons.collections.CollectionUtils;
import org.junit.Test;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class BeanUtilsTest {
    @Test
    public void test() {
        //数据源
        User source = new User();
        source.setName("mf");
        source.setAge(26);
        //复制
        UserDto target = new UserDto();
        BeanUtils.copyProperties(source, target);
        System.out.println(target);
    }
    @Test
    public void list() {
        List<User> sourceList = new ArrayList<>();
        //数据源
        User source1 = new User();
        source1.setName("mf");
        source1.setAge(26);
        sourceList.add(source1);

        User source2 = new User();
        source2.setName("mg");
        source2.setAge(28);
        sourceList.add(source2);
        //复制
        List<UserDto> targetList = copyList(sourceList);
        System.out.println(targetList);
    }
    public static <T> List copyList(List<T> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList();
        }
        return JSON.parseArray(JSON.toJSONString(list), list.get(0).getClass());
    }
    public static Map<String, Object> copyMap(Map map) {
        return JSON.parseObject(JSON.toJSONString(map));
    }
}
复制代码

 

资料

posted @   ~沐风  阅读(509)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2020-03-27 React 入门(1)简介
2018-03-27 .Net并行编程(4)多线程之线程安全

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示