美文网首页
Spring BeanUtils.copyProperties源

Spring BeanUtils.copyProperties源

作者: hei禹 | 来源:发表于2018-08-30 23:37 被阅读0次

    最近用到了Spring的BeanUtils.copyProperties进行对象的拷贝,但拷贝的属性有null,如下:


    image.png

    对应的测试代码:

    public class HouseDO {
        private String location;
        private DeskDO desk;
        private List<ChairDO> chairs;
    }
    public class HouseVO {
        private String location;
        private DeskVO desk;
        private List<ChairVO> chairs;
    }
    
    

    DeskDO、DeskVO的属性是一模一样的,那为什么desk属性没有拷贝成功?而chairs属性拷贝成功了呢?有什么区别?从源码分析,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);
                        }
                    }
                }
            }
        }
    }
    
    org.springframework.util.ClassUtils
    
    /**
     * 检查右侧类型是否可以赋值给左侧类型(假设是通过反射进行设置)。 将原始包装类视为可赋值给相应的基元类型。
     * @param lhsType 目标类型
     * @param rhsType 源类型
     * @return 是否可以从元源类型赋值给目标类型
     * @see TypeUtils#isAssignable
     */
    public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType) {
        Assert.notNull(lhsType, "Left-hand side type must not be null");
        Assert.notNull(rhsType, "Right-hand side type must not be null");
        if (lhsType.isAssignableFrom(rhsType)) {
            return true;
        }
        if (lhsType.isPrimitive()) {
            Class<?> resolvedPrimitive = primitiveWrapperTypeMap.get(rhsType);  // for example: Integer.class -> int.class
            if (lhsType == resolvedPrimitive) {
                return true;
            }
        }
        else {
            Class<?> resolvedWrapper = primitiveTypeToWrapperMap.get(rhsType);  //  for example: int.class -> Integer.class
            if (resolvedWrapper != null && lhsType.isAssignableFrom(resolvedWrapper)) {
                return true;
            }
        }
        return false;
    }
    
    java.lang.Class
    
    /**
     * 确定此Class对象表示的类或接口,是否与指定的cls参数表示的类或接口相同,或者是它们的超类或超接口。
     * 如果是这样,它返回true; 否则返回false。 如果此Class对象表示基本类型,则如果指定的cls参数恰好是此Class对象,则此方法返回true;否则返回true。 否则返回false。
     * 具体来说,此方法测试是否可以通过标识转换(identity conversion)或扩展引用转换(widening reference conversion)将指定的Class参数表示的类型转换为此Class对象表示的类型。 
     * 有关详细信息,请参阅Java语言规范,第5.1.1和5.1.4节。
     */
    public native boolean isAssignableFrom(Class<?> cls);
    

    参考资料:

    https://blog.csdn.net/SJZYLC/article/details/81284386

    相关文章

      网友评论

          本文标题:Spring BeanUtils.copyProperties源

          本文链接:https://www.haomeiwen.com/subject/qpsjwftx.html