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);
                    }
                }
            }
        }
    }

第一次循環 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章