Mybatis中的PropertyCopier属性复制器

PropertyCopier属性复制器位于MyBatis中reflection包下子包property属性子包,其作用就是将一个对象的属性复制到另一个对象中。

源码如下:
public final class PropertyCopier {

  private PropertyCopier() {
    // Prevent Instantiation of Static Class
  }

  public static void copyBeanProperties(Class<?> type, Object sourceBean, Object destinationBean) {
    Class<?> parent = type;
    while (parent != null) {
      // 获取所有字段属性
      final Field[] fields = parent.getDeclaredFields();
      for(Field field : fields) {
        try {
          // 设置访问权限
          field.setAccessible(true);
          field.set(destinationBean, field.get(sourceBean));
        } catch (Exception e) {
          // Nothing useful to do, will only fail on final fields, which will be ignored.
        }
      }
      // 获取继承的字段属性
      parent = parent.getSuperclass();
    }
  }

}
getDeclaredFields方法无法获取继承父类的字段属性。

禁止改动的类定义为final类型,私有化构造方法提供静态方法。

测试案例:

@SpringBootTest
public class TestPropertyCopier {

    @Test
    public void test1(){
        User user1 = new User();
        user1.setName("张三丰");
        user1.setAge(100);
        User user2 = new User();
        System.out.println("复制前user2:"+user2.toString());
        PropertyCopier.copyBeanProperties(User.class,user1,user2);
        System.out.println("复制后user2:"+user2.toString());
    }
}

测试结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值