温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

BeanUtils.copyProperties复制属性失败的原因以及解决方法

发布时间:2021-08-31 12:50:08 来源:亿速云 阅读:539 作者:chen 栏目:开发技术

本篇内容主要讲解“BeanUtils.copyProperties复制属性失败的原因以及解决方法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“BeanUtils.copyProperties复制属性失败的原因以及解决方法”吧!

目录
  • BeanUtils.copyProperties复制属性失败

    • 描述

    • 解决办法

  • BeanUtils.copyProperties应用的改进

    • 为解决这个问题我重写了部分spring BeanUtils的代码

BeanUtils.copyProperties复制属性失败

描述

在JavaE中使用 BeanUtils.copyProperties,把A对象的name、age等属性复制到B对象中,A与B对象的类型不同。出现的问题是复制属性失败,根本原因是 BeanUtils找不到set、get方法。

import org.springframework.beans.BeanUtils;
BeanUtils.copyProperties(one, monitorCount);

解决办法

1,为复制对象的属性增加set、get方法。比如给name、age属性增加set、get方法。

2,也可以使用插件生成setter、getter比如:

package com.css.oa.exam.monitor.bean;
import lombok.Data; //使用lombok插件
@Data //使用这个注解可以生成setter
public class AssignOne{ 
  public String name; 
  public String age; 
}

BeanUtils.copyProperties应用的改进

在MVC的开发模式中经常需要将model与pojo的数据绑定,apache和spring的工具包中都有BeanUtils,使用其中的copyProperties方法可以非常方便的进行这些工作,但在实际应用中发现,对于null的处理不太符合个人的需要,例如在进行修改操作中只需要对model中某一项进行修改,那么一般我们在页面上只提交model的ID及需要修改项的值,这个时候使用BeanUtils.copyProperties会将其他的null绑定到pojo中去。

为解决这个问题我重写了部分spring BeanUtils的代码

如下:

public abstract class BeanUtils extends org.springframework.beans.BeanUtils {
 
  public static void copyProperties(Object source, Object target) throws BeansException {
    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");
    Class<?> actualEditable = target.getClass();
    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
    for (PropertyDescriptor targetPd : targetPds) {
      if (targetPd.getWriteMethod() != null) {
        PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
        if (sourcePd != null && sourcePd.getReadMethod() != null) {
          try {
            Method readMethod = sourcePd.getReadMethod();
            if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
              readMethod.setAccessible(true);
            }
            Object value = readMethod.invoke(source);
            // 这里判断以下value是否为空 当然这里也能进行一些特殊要求的处理 例如绑定时格式转换等等
            if (value != null) {
              Method writeMethod = targetPd.getWriteMethod();
              if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                writeMethod.setAccessible(true);
              }
              writeMethod.invoke(target, value);
            }
          } catch (Throwable ex) {
            throw new FatalBeanException("Could not copy properties from source to target", ex);
          }
        }
      }
    }
  }
}

apahce的BeanUtils的处理方法类似

到此,相信大家对“BeanUtils.copyProperties复制属性失败的原因以及解决方法”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI