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 @ 2021-03-27 12:42  ~沐风  阅读(503)  评论(0编辑  收藏  举报