java对象属性拷贝,不拷贝空值

/**
* 对象拷贝
* 数据对象空值不拷贝到目标对象

* @param dataObject
* @param toObject
* @throws NoSuchMethodException
* copy
*/
  public static void copyBeanNotNull2Bean(Object databean,Object tobean)throws Exception
  {
 PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(databean);
      for (int i = 0; i < origDescriptors.length; i++) {
          String name = origDescriptors[i].getName();
//          String type = origDescriptors[i].getPropertyType().toString();
          if ("class".equals(name)) {
              continue; // No point in trying to set an object's class
          }
          if (PropertyUtils.isReadable(databean, name) &&PropertyUtils.isWriteable(tobean, name)) {
              try {
                  Object value = PropertyUtils.getSimpleProperty(databean, name);
                  if(value!=null){
                 getInstance().setSimpleProperty(tobean, name, value);
                  }
              }
              catch (java.lang.IllegalArgumentException ie) {
                  ; // Should not happen
              }
              catch (Exception e) {
                  ; // Should not happen
              }


          }
      }
  }
BeanUtils.copyProperties方法是Apache Commons BeanUtils库中的一个工具方法,用于将一个Java对象属性值复制到另一个Java对象中。默认情况下,该方法会将源对象的所有属性值复制到目标对象中,包括空值属性。 如果你想要排除空值属性,可以使用自定义的属性拷贝器(PropertyUtilsBean)来实现。以下是一种可能的实现方式: 1. 创建一个自定义的属性拷贝器类,继承自PropertyUtilsBean类,并重写copyProperties方法。 ```java import org.apache.commons.beanutils.PropertyUtilsBean; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.beanutils.DynaBean; public class CustomPropertyUtils extends PropertyUtilsBean { @Override public void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(orig); for (PropertyDescriptor origDescriptor : origDescriptors) { String name = origDescriptor.getName(); if (PropertyUtils.isReadable(orig, name) && PropertyUtils.isWriteable(dest, name)) { Object value = PropertyUtils.getSimpleProperty(orig, name); if (value != null) { PropertyUtils.setSimpleProperty(dest, name, value); } } } } } ``` 2. 在你的代码中使用自定义的属性拷贝器类进行属性拷贝。 ```java CustomPropertyUtils customPropertyUtils = new CustomPropertyUtils(); customPropertyUtils.copyProperties(destObject, sourceObject); ``` 这样,只有源对象中非空的属性值才会被复制到目标对象中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值