一、异常描述
通过org.apache.commons.beanutils.BeanUtils(commons-beanutils-1.8.3.jar.zip包下载)的copyProperties对日期对象copy的时候因为日期复制为NULL空,造成“org.apache.commons.beanutils.ConversionException: No value specified for 'java.sql.Date'”异常提示,详细日志如下所示
Exception in thread "main" org.apache.commons.beanutils.ConversionException: No value specified for 'java.sql.Date'@b@ at org.apache.commons.beanutils.converters.AbstractConverter.handleMissing(AbstractConverter.java:310)@b@ at org.apache.commons.beanutils.converters.AbstractConverter.convert(AbstractConverter.java:136)@b@ at org.apache.commons.beanutils.converters.ConverterFacade.convert(ConverterFacade.java:60)@b@ at org.apache.commons.beanutils.BeanUtilsBean.convert(BeanUtilsBean.java:1078)@b@ at org.apache.commons.beanutils.BeanUtilsBean.copyProperty(BeanUtilsBean.java:437)@b@ at org.apache.commons.beanutils.BeanUtilsBean.copyProperties(BeanUtilsBean.java:286)@b@ at org.apache.commons.beanutils.BeanUtils.copyProperties(BeanUtils.java:137)@b@ at com.xwood.object.copy.DateOBJConvert.main(DateOBJConvert.java:14)
测试代码如下
import org.apache.commons.beanutils.BeanUtils;@b@@b@public class DateOBJConvert {@b@@b@ public static void main(String[] args) throws Exception{@b@ @b@ OBJa obja=new OBJa();@b@ @b@ OBJb objb=new OBJb("b",null);@b@ @b@ BeanUtils.copyProperties(obja, objb);@b@ @b@ System.out.println(obja.toString());@b@ }@b@@b@}
二、解决方法
1.基于org.apache.commons.beanutils.Converter的接口重写转换逻辑,为空的时候默认转出为null,如下定义新DateConvert类,代码如下
import java.util.Date;@b@import org.apache.commons.beanutils.Converter;@b@@b@public class DateConvert implements Converter {@b@@b@ public Object convert(Class arg0, Object arg1) {@b@ Date date = (Date) arg1;@b@ return date == null ? null : date;@b@ }@b@@b@}
2.再定义BeanUtilsEx工具类基础org.apache.commons.beanutils.BeanUtils,将步骤1中DateConvert注入java.util.Date、java.sql.Date替换对象,代码如下
import java.lang.reflect.InvocationTargetException;@b@import org.apache.commons.beanutils.BeanUtils;@b@import org.apache.commons.beanutils.ConvertUtils;@b@@b@public class BeanUtilsEx extends BeanUtils {@b@@b@ static {@b@ ConvertUtils.register(new DateConvert(), java.util.Date.class);@b@ ConvertUtils.register(new DateConvert(), java.sql.Date.class);@b@ }@b@@b@ public static void copyProperties(Object dest, Object orig) {@b@ try {@b@ BeanUtils.copyProperties(dest, orig);@b@ } catch (IllegalAccessException ex) {@b@ ex.printStackTrace();@b@ } catch (InvocationTargetException ex) {@b@ ex.printStackTrace();@b@ }@b@ }@b@}
3.原来上面测试DateOBJConvert类需改为BeanUtilsEx.copyProperties如下
public class DateOBJConvert {@b@@b@ @b@ public static void main(String[] args) throws Exception{@b@ @b@ OBJa obja=new OBJa();@b@ @b@ OBJb objb=new OBJb("b",null);@b@ @b@ BeanUtilsEx.copyProperties(obja, objb);@b@ @b@ System.out.println(obja.toString());@b@ }@b@@b@}
控制台输入结果:id:b@createDate:null