BeanUtils.copyProperties方法遇到null值问题

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

[java]  view plain copy
  1. public abstract class BeanUtils extends org.springframework.beans.BeanUtils {  
  2.   
  3.   public static void copyProperties(Object source, Object target) throws BeansException {  
  4.     Assert.notNull(source, "Source must not be null");  
  5.     Assert.notNull(target, "Target must not be null");  
  6.     Class<?> actualEditable = target.getClass();  
  7.     PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);  
  8.     for (PropertyDescriptor targetPd : targetPds) {  
  9.       if (targetPd.getWriteMethod() != null) {  
  10.         PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());  
  11.         if (sourcePd != null && sourcePd.getReadMethod() != null) {  
  12.           try {  
  13.             Method readMethod = sourcePd.getReadMethod();  
  14.             if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {  
  15.               readMethod.setAccessible(true);  
  16.             }  
  17.             Object value = readMethod.invoke(source);  
  18.             // 这里判断以下value是否为空 当然这里也能进行一些特殊要求的处理 例如绑定时格式转换等等  
  19.             if (value != null) {  
  20.               Method writeMethod = targetPd.getWriteMethod();  
  21.               if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {  
  22.                 writeMethod.setAccessible(true);  
  23.               }  
  24.               writeMethod.invoke(target, value);  
  25.             }  
  26.           } catch (Throwable ex) {  
  27.             throw new FatalBeanException("Could not copy properties from source to target", ex);  
  28.           }  
  29.         }  
  30.       }  
  31.     }  
  32.   }  
  33. }  
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值