写Java的同学应该都知道,在Java里面有各种O(PO,VO,TO,QO,BO,DTO),我们经常需要将各种O对象之间转换数据,用的比较多的就是Spring的BeanUtils工具的copyProperties函数和dozer的Mapper,这两种都可以完成属性的复制,但是无法完成列表的快速复制,因而笔者封装了一下,来支持列表的复制。
注意:如果对性能要求比较高的话,可以使用BeanCopier工具封装BeanCopier工具,支持单个对象以及列表拷贝,超高性能简单实用
需要明确说的是,BeanUtils是浅拷贝,如需使用深拷贝,请移步:对象属性深拷贝工具DozerBeanMapper封装
代码如下:
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* BeanUtil 对象属性复制
*
* @author itoak
* @date 2019-10-09
* @time 17:11
* @desc 支持单个对象属性复制、列表对象的属性复制
*/
public class BeanUtil {
/**
* 单个对象属性复制
*
* @param source 复制源
* @param clazz 目标对象class
* @param <T> 目标对象类型
* @param <M> 源对象类型
* @return 目标对象
*/
public static <T, M> T copyProperties(M source, Class<T> clazz) {
if (Objects.isNull(source) || Objects.isNull(clazz))
throw new IllegalArgumentException();
T t = null;
try {
t = clazz.newInstance();
BeanUtils.copyProperties(source, t);
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return t;
}
/**
* 列表对象属性复制
*
* @param sources 源对象列表
* @param clazz 目标对象class
* @param <T> 目标对象类型
* @param <M> 源对象类型
* @return 目标对象列表
*/
public static <T, M> List<T> copyObjects(List<M> sources, Class<T> clazz) {
if (Objects.isNull(sources) || Objects.isNull(clazz))
throw new IllegalArgumentException();
return Optional.of(sources)
.orElse(Lists.newArrayList())
.stream().map(m -> copyProperties(m, clazz))
.collect(Collectors.toList());
}
}
使用方法:
@Getter
@Setter
static class PersonBO {
private String name;
}
@Getter
@Setter
static class PersonVO {
private String name;
}
public static void main(String[] args) {
//单个对象
PersonBO personBO = new PersonBO();
personBO.setName("itoak");
PersonVO personVO = BeanUtil.copyProperties(personBO, PersonVO.class);
System.out.println(personVO.getName().equals("itoak1"));
System.out.println(personVO.getName().equals("itoak"));
//列表
List<PersonBO> bos = new ArrayList<>();
PersonBO personBO1 = new PersonBO();
PersonBO personBO2 = new PersonBO();
personBO1.setName("Tom");
personBO2.setName("Lucy");
bos.add(personBO1);
bos.add(personBO2);
List<PersonVO> vos = BeanUtil.copyObjects(bos, PersonVO.class);
System.out.println(vos.size());
System.out.println(vos.get(0).getName());
System.out.println(vos.get(1).getName());
}