一探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 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 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 getNum() {
        return num;
    }

    public void setNum(List 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 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 getNum() {
        return num;
    }

    public void setNum(List 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 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方法,复制一遍属性。

一探Spring中BeanUtils的copyProperties方法_第1张图片

一探Spring中BeanUtils的copyProperties方法_第2张图片

源对象中的list泛型为Integer,而目标对象中list的泛型为String,但是泛型只是编译期起约束作用,运行期可以看出set的参数类型和get的返回类型都是java.util.List,并无约束,因此也可以实现复制。

一探Spring中BeanUtils的copyProperties方法_第3张图片

一探Spring中BeanUtils的copyProperties方法_第4张图片

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

你可能感兴趣的:(源码剖析,框架经验)