Spring中BeanUtils.copyProperties源码分析

使用Spring的BeanUtils进行对象拷贝很容易。

首先引入响应的jar包:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>5.0.7.RELEASE</version>
</dependency>

使用时代码就一行:

org.springframework.beans.BeanUtils.copyProperties(orig, dest);

对应形参:Object source, Object target

参数表示要把orig里面的属性值拷贝到dest对象中。

注意,对象拷贝的是属性值的引用,如果是基础数据类型还好,如果是一个对象类型,拷贝完成后,orig里面的对象类型属性值发生变化,dest里面相应的属性值会发生变化。会有一定的风险。

 

查看spring源码,方法实现代码如下:

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;
   }
//获取target对象的PropertyDescriptor属性数组targetPds
   PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
   List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
//遍历target对象属性
   for (PropertyDescriptor targetPd : targetPds) {
//获取其set方法
      Method writeMethod = targetPd.getWriteMethod();
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值