摘要

本文浅析BeanUtils中copyProperties的原理。简述大致实现流程

源码浅析

org.springframework.beans.BeanUtils

/**
 * 将给定源bean的属性值赋值到目标bean中。
 * 注意:只要属性匹配,源类和目标类就不必相互匹配(match),甚至不必相互派生(derived from each other)。 源bean暴露但目标bean没有暴露的属性,会被自动忽略。
 * 这只是一种方便的方法。 对于更复杂的转换需求,请考虑使用完整的BeanWrapper。
* @param source 源bean
* @param target the target bean目标bean
* @throws BeansException,如果拷贝失败
* @see BeanWrapper
*/
public static void copyProperties(Object source, Object target) throws BeansException {
    copyProperties(source, target, null, (String[]) null);
}

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) {
        // 获取其setter方法
        Method writeMethod = targetPd.getWriteMethod();
        if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
            // 获取source对象与target对象targetPd属性同名的PropertyDescriptor对象sourcePd
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null) {
                // 获取source对应属性的getter方法
                Method readMethod = sourcePd.getReadMethod();
                if (readMethod != null &&
                        // 判断是否可赋值,如上述例子:desk是DeskVO、DeskDO,返回false;而chairs都是List<?>,返回true
                        ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                    try {
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        // 通过反射获取source对象属性的值
                        Object value = readMethod.invoke(source);
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        // 通过反射给target对象属性赋值
                        writeMethod.invoke(target, value);
                    }
                    catch (Throwable ex) {
                        throw new FatalBeanException(
                                "Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                    }
                }
            }
        }
    }
}

小结

执行过程比较简单,使用jdk提供的内省的方式属性描述类PropertyDescriptor。但是底层对象取值、赋值还是用的反射。

copyProperties是浅拷贝还是深拷贝

毫无疑问是浅拷贝