BeanUtils.copyProperties源码解析

private static void copyProperties(Object source, Object target, Class<?> editable, 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) { //null
        if (!editable.isInstance(target)) {
            throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]");
        }

        actualEditable = editable;
    }

    //获取目标对象所有字段属性
    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); 
    //需要过滤的字段
    List<String> ignoreList = ignoreProperties != null ? Arrays.asList(ignoreProperties) : null; 
    PropertyDescriptor[] var7 = targetPds;
    int var8 = targetPds.length;

    for(int var9 = 0; var9 < var8; ++var9) {
        //获取目标字段
        PropertyDescriptor targetPd = var7[var9]; 
        //获取set方法
        Method writeMethod = targetPd.getWriteMethod(); 
        //set方法不为空,过滤字段为空或过滤字段不包括当前遍历字段
        if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
            //获取源字段
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); 
            if (sourcePd != null) {
                //获取get方法
                Method readMethod = sourcePd.getReadMethod(); 
                //ClassUtils.isAssignable判断是否可转(目标类型是否为源类型父类,或相同)
                if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                    try {
                        //判断是否为public
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { 
                             //打破封装
                             readMethod.setAccessible(true); 
                        }
                        //value赋值
                        Object value = readMethod.invoke(source); 
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        //值拷贝
                        writeMethod.invoke(target, value); 
                    } catch (Throwable var15) {
                        throw new FatalBeanException("Could not copy property '" + targetPd.getName() + "' from source to target", var15);
                    }
                }
            }
        }
    }

第一次循环 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值