使用Spring的BeanUtils进行对象拷贝很容易。
首先引入响应的jar包:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
使用时代码就一行:
org.springframework.beans.BeanUtils.copyProperties(orig, dest);
对应形参:Object source, Object target
参数表示要把orig里面的属性值拷贝到dest对象中。
注意,对象拷贝的是属性值的引用,如果是基础数据类型还好,如果是一个对象类型,拷贝完成后,orig里面的对象类型属性值发生变化,dest里面相应的属性值会发生变化。会有一定的风险。
查看spring源码,方法实现代码如下:
private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
@Nullable String... ignoreProperties) throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
Class<?> actualEditable = target.getClass();
if (editable != null) {
if (!editable.isInstance(target)) {
throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
"] not assignable to Editable class [" + editable.getName() + "]");
}
actualEditable = editable;
}
//获取target对象的PropertyDescriptor属性数组targetPds
PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
//遍历target对象属性
for (PropertyDescriptor targetPd : targetPds) {
//获取其set方法
Method writeMethod = targetPd.getWriteMethod();