一探Spring中BeanUtils的copyProperties方法

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

	//獲取目標對象的各屬性信息
        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();
	//判斷該屬性是否在不被copy的屬性集合中
            if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
		//根據目標對象的屬性名稱,獲取源對象的該屬性信息
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null) {
			 //獲取源對象的該屬性的讀方法,即get方法
                    Method readMethod = sourcePd.getReadMethod();
			 //判斷目標對象的set方法所需的參數類型和源對象get方法的返回類型是否一致
                    if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                        try {
			    //如果源對象的get方法不包含public修飾符,將該方法修改爲可以通過反射外部訪問
                            if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                readMethod.setAccessible(true);
                            }
						
			    //通過反射獲取源對象該屬性的值
                            Object value = readMethod.invoke(source);
			    //如果目標對象的set方法不包含public修飾符,將該方法修改爲可以通過反射外部訪問
                            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);
                        }
                    }
                }
            }
        }

    }

通過copyProperties方法的源代碼可以看出,實現此功能有三個必須條件:
1.需要複製的屬性名要相同;
2.對於要複製的屬性,源對象必須有get方法,目標對象必須有set方法;
3.目標對象的set方法所需的參數類型和源對象get方法的返回類型保持一致。

下面貼上測試類和測試代碼:

被複制的類

public class CopyTest1 {

    private String outStr;
    private CopyTest1.Inner inner;
    private List<Integer> num;

    public static class Inner {
        public String inStr;
    }

    public String getOutStr() {
        return outStr;
    }

    public void setOutStr(String outStr) {
        this.outStr = outStr;
    }

    public Inner getInner() {
        return inner;
    }

    public void setInner(Inner inner) {
        this.inner = inner;
    }

    public List<Integer> getNum() {
        return num;
    }

    public void setNum(List<Integer> num) {
        this.num = num;
    }

    @Override
    public String toString() {
        return "CopyTest1{" +
                "outStr='" + outStr + '\'' +
                ", inner=" + inner +
                ", num=" + num +
                '}';
    }

目標類

public class CopyTest2 {

    private String outStr;
    private CopyTest2.Inner inner;
    private List<String> num;

    public static class Inner {
        public String inStr;
    }

    public String getOutStr() {
        return outStr;
    }

    public void setOutStr(String outStr) {
        this.outStr = outStr;
    }

    public Inner getInner() {
        return inner;
    }

    public void setInner(Inner inner) {
        this.inner = inner;
    }

    public List<String> getNum() {
        return num;
    }

    public void setNum(List<String> num) {
        this.num = num;
    }

    @Override
    public String toString() {
        return "CopyTest2{" +
                "outStr='" + outStr + '\'' +
                ", inner=" + inner +
                ", num=" + num +
                '}';
    }
}

測試方法

public static void main(String[] args) {
        CopyTest1 test1 = new CopyTest1();
        test1.setOutStr("hahahaha");
        List<Integer> num = new ArrayList();
        num.add(1);
        test1.setNum(num);
        CopyTest1.Inner inner = new CopyTest1.Inner();
        inner.inStr = "hohohoho";
        test1.setInner(inner);

        System.out.println(test1.toString());
        CopyTest2 test2 = new CopyTest2();
        BeanUtils.copyProperties(test1, test2);
        System.out.println(test2.toString());
    }

從debug的效果看出屬於兩個類中的內部類,即使類名和屬性名都相同相同,仍然不會複製,因爲目標對象的set方法所需的參數類型和源對象get方法的返回類型是不一致,違反了條件3。因此,內部類需要單獨使用copyProperties方法,複製一遍屬性。

源對象中的list泛型爲Integer,而目標對象中list的泛型爲String,但是泛型只是編譯期起約束作用,運行期可以看出set的參數類型和get的返回類型都是java.util.List,並無約束,因此也可以實現複製。

本文參考:www.jianshu.com/p/357b55852efc

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