复制对象属性

复制两个对象之间的属性

在使用jpa时,更新对象属性之前,需要先查出来entity对象,然后把前台传入到后端的form对象中不为空的属性,覆盖到entity对象中,在调用repository的save方法,完成更新。

这里在对属性覆盖式时,参考BeanUtils.copyProperties(),写了一段工具代码,里面可以自定义一些处理,后续可以优化

 /**
   *  把source 不为空的属性覆盖到 target
   * @param source
   * @param target
   */
  private void transferFields(Object source, Object target) {
    try {
      Class sourceClass = source.getClass();
      Class targetClass = target.getClass();
      BeanInfo metricBeanInfo = Introspector.getBeanInfo(sourceClass);
      BeanInfo targetBeanInfo = Introspector.getBeanInfo(targetClass);
      // 获取sorce对象得属性值 然后复制给target对象
      PropertyDescriptor[] propertyDescriptors = metricBeanInfo.getPropertyDescriptors();
      PropertyDescriptor[] targetBeanInfoPropertyDescriptors = targetBeanInfo.getPropertyDescriptors();
      Map<String, Method> methodMap = Arrays.stream(targetBeanInfoPropertyDescriptors)
        .filter(t -> ObjectUtil.isNotNull(t.getWriteMethod()))
        .collect(Collectors.toMap(t -> t.getReadMethod().getName(), t -> t.getWriteMethod()));
      for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        // 获取source对象的属性值
        Method readMethod = propertyDescriptor.getReadMethod();
        String fieldName = readMethod.getName();
        Object value = readMethod.invoke(source);
        Method writeMethod = methodMap.get(fieldName);
        if (ObjectUtil.isEmpty(value) || Objects.isNull(writeMethod)) {
          continue;
        }
        //复制给target对象
        Class<?> parameterType = writeMethod.getParameterTypes()[0];
        if (String.class.equals(parameterType)) {
          value = String.valueOf(value);
        } else if (Long.class.equals(parameterType)) {
          value = Long.valueOf((String) value);
        }
        writeMethod.setAccessible(true);
        writeMethod.invoke(target, value);
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage());
    }
  }

获取一个class的属性以及父类的属性:

for循环

ArrayList<Field[]> fieldList = CollectionUtil.newArrayList();
for (Class currClass = dtoClass; currClass != null && currClass != Object.class;currClass = currClass.getSuperclass()) {
  Field[] declaredFields = currClass.getDeclaredFields();
  fieldList.add(declaredFields);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值