用BeanUtils复制Timestamp属性时如果为null 会导致No value specified异常。
参考 http://www.blogjava.net/javagrass/archive/2011/10/10/352856.html的方法解决了该问题,但是链接中的方法有一个地方有错误,下面为正确的代码。
/**
* @via http://www.blogjava.net/javagrass/archive/2011/10/10/352856.html
*/
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.converters.SqlDateConverter;
import org.apache.commons.beanutils.converters.SqlTimestampConverter;
import java.lang.reflect.*;
public final class BeanUtilEx extends BeanUtils {
private BeanUtilEx() {
}
static {
//注册sql.date的转换器,即允许BeanUtils.copyProperties时的源目标的sql类型的值允许为空
ConvertUtils.register(new SqlDateConverter(null), java.util.Date.class);
ConvertUtils.register(new SqlTimestampConverter(null), java.sql.Timestamp.class);
}
public static void copyProperties(Object target, Object source) throws
InvocationTargetException, IllegalAccessException {
org.apache.commons.beanutils.BeanUtils.copyProperties(target, source);
}
}
原因是原文章中没有在注册SqlTimestampConverter时传入默认返回的值:
ConvertUtils.register(new SqlTimestampConverter(null), java.sql.Timestamp.class);
源码中,SqlTimestampConverter有两个构造方法。在有值传入构造方法中,当属性为null时,返回传入的值。即构造时传入的时,是转换过程中抛出异常后返回的默认值。
package org.apache.commons.beanutils.converters;
import java.sql.Timestamp;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;
public final class SqlTimestampConverter implements Converter {
public SqlTimestampConverter() {
this.defaultValue = null;
this.useDefault = false;
}
public SqlTimestampConverter(Object defaultValue) {
this.defaultValue = defaultValue;
this.useDefault = true;
}
private Object defaultValue = null;
private boolean useDefault = true;
public Object convert(Class type, Object value) {
if (value == null) {
if (useDefault) {
return (defaultValue);
} else {
throw new ConversionException("No value specified");
}
}
if (value instanceof Timestamp) {
return (value);
}
try {
return (Timestamp.valueOf(value.toString()));
} catch (Exception e) {
if (useDefault) {
return (defaultValue);
} else {
throw new ConversionException(e);
}
}
}
}