原文网址:SpringBoot--复制对象的工具类_IT利刃出鞘的博客-CSDN博客
简介
说明
本文介绍复制对象的工具类。
项目中经常遇到将List转化为其他类型的List的情况,比如:将List<User>转化为List<UserDTO>。
优点
- 一行代码即可转换
- 底层使用Spring的BeanUtils,稳定
代码
package com.knife.router4j.server.common.util;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class BeanHelper {
/**
* 浅拷贝
*/
public static <T> T shallowClone(Object source, Class<T> target) {
if (source == null) {
return null;
}
T t;
try {
t = target.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
BeanUtils.copyProperties(source, t);
return t;
}
/**
* 浅拷贝
*/
public static <T> List<T> shallowClone(List<?> sources, Class<T> target) {
if (CollectionUtils.isEmpty(sources)) {
return new ArrayList<>();
}
List<T> targets = new LinkedList<>();
for (Object source : sources) {
T t = null;
try {
t = target.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
BeanUtils.copyProperties(source, t);
targets.add(t);
}
return targets;
}
/**
* 深拷贝
*/
public static <T> T deepClone(Object source, Class<T> target) {
if (source == null) {
return null;
}
String json = JsonUtil.toJson(source);
return JsonUtil.toObject(json, target);
}
/**
* 深拷贝
*/
public static <T> List<T> deepClone(List<?> sources, Class<T> target) {
if (CollectionUtils.isEmpty(sources)) {
return new ArrayList<>();
}
String json = JsonUtil.toJson(sources);
return JsonUtil.toObjectList(json, new TypeReference<List<T>>() {});
}
}注:
里边的深拷贝用到了JSON工具类,见: SpringBoot--封装JSON工具类(基于Jackson)_IT利刃出鞘的博客-CSDN博客
用法
List<User> users = new ArrayList();
List<UserDTO> userDTOs = BeanHelper.shallowClone(users, UserDTO.class);版权声明:本文为feiying0canglang原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。