使用BeanUtils时,Date类型值为空的解决方法

使用BeaUtils.copyProperties时,如果源目标中包含Date类型(sql.date,util,date)字段,而且该字段值为空时,会出现异常,无法赋值,解决方法如下:

1、建立一个新的BeaUtilsEx类继承BeanUtils

2、在其中声名Date类型的转换类

3、实现这个转换类

BeanUtilsEx代码如下:

package com.fish.util;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.HashMap;
import java.util.Map;
import java.lang.reflect.*;

public final class BeanUtilEx
    extends BeanUtils {

  private static Map cache = new HashMap();
  private static Log logger = LogFactory.getFactory().getInstance(BeanUtilEx.class);

  private BeanUtilEx() {
  }

  static {
    //注册sql.date的转换器,即允许BeanUtils.copyProperties时的源目标的sql类型的值允许为空
    ConvertUtils.register(new SqlDateConverter(), java.util.Date.class);
    //ConvertUtils.register(new SqlTimestampConverter(), java.sql.Timestamp.class);
    //注册util.date的转换器,即允许BeanUtils.copyProperties时的源目标的util类型的值允许为空
    ConvertUtils.register(new UtilDateConverter(), java.util.Date.class);
  }

  public static void copyProperties(Object target, Object source) throws
      InvocationTargetException, IllegalAccessException {
    //update bu zhuzf at 2004-9-29
    //支持对日期copy

    org.apache.commons.beanutils.BeanUtils.copyProperties(target, source);

  }
}

 至于转换类SqlDateConverter和UtilDateConverter,实现起来很简单,这里省略

你可能感兴趣的:(Java)