spring的BeanUtils属性copy

1、使用

BeanUtils.copyProperties将一个对象的属性copy到另外一个对象中。

2、copy的原理是获取需要copy属性的属性描述器(PropertyDescriptor),获取目标属性的PropertyDescriptor,并获取writeMethod,获取源属性的readMethod,将readMethod得到的结果(Object)写入到writeMethod中,所以如果属性是对象的,写入的是源对象引用的对象。

源码如下

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) {
            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];
            Method writeMethod = targetPd.getWriteMethod();
            if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null) {
                    Method readMethod = sourcePd.getReadMethod();
                    if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                        try {
                            if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                readMethod.setAccessible(true);
                            }

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

    }

我们用一个实际例子

两个对象Request1,Request2

package local.beancopy;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/**
 * @author: suntao
 */
@Data
public class Request1 {

    private String request;
    private List<Detail1> detail;

    @Data
    public static class Detail1 {
        private String name;
        private Integer age;
        private Integer sex;
        private BigDecimal income;
    }
}
@Data
public class Request2 {

    private String request;
    private List<Detail2> detail;

    @Data
    public static class Detail2 {
        private String name;
        private Integer age;
        private Integer sex;
        private BigDecimal income;
        private String secondName;
    }
}

Test代码:

package local.beancopy;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import cn.quantgroup.cashloanflow.util.JsonUtil;
import org.junit.Test;
import org.springframework.beans.BeanUtils;

/**
 * function:
 * date: 2019/12/2
 *
 * @author: suntao
 */
public class BeanUtilCopyTest {

    @Test
    public void testCopy() {
        Request2 request2 = new Request2();
        request2.setRequest("request2");

        List<Request2.Detail2> detail2List = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            Request2.Detail2 detail2 = new Request2.Detail2();
            detail2.setName("小明");
            detail2.setAge(i + 10);
            detail2.setSex(0);
            detail2.setIncome(new BigDecimal("2220"));
            detail2.setSecondName("fuck you,错了是 thank you");
            detail2List.add(detail2);
        }

        request2.setDetail(detail2List);

        Request1 request1 = new Request1();

        BeanUtils.copyProperties(request2, request1);

        request2.getDetail().get(0).setSecondName("爱你哦");

        System.out.println(JsonUtil.toJson(request1));

    }
}

打印结果:

{"request":"request2","detail":[{"name":"小明","age":10,"sex":0,"income":2220,"secondName":"爱你哦"},{"name":"小明","age":11,"sex":0,"income":2220,"secondName":"fuck you,错了是 thank you"}]}

案例的意思是要把Request2的对象copy到Request1的对象中。

但是注意看将Request2的对象copy到Request1的对象后,Request1.detail对象并没有secondName属性,这个属性只有Request2.detail才有,所以copy是在获取

request2的detail对象后,通过java反射吧得到Object直接赋值给request1,其绕过了java编译器,不会报错。

3、copy执行之后,改变源对象的引用值,copy后的对象也会改变

如上例子

request2.getDetail().get(0).setSecondName("爱你哦");

在copy之后执行。request1.detail的0号元素的secondName已经被改变.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值