在使用BeanUtils的populate方法或者getProperty、setProperty方法时都会调用convert进行转换,但Converter只支持一些基本的类型,对于日期类型却不支持。如果源目标中包含日期类型字段,而且该字段值为空时,就会出现异常,无法赋值,解决方法如下:
1、新建一个转换器类,该类实现Converter接口,在convert方法中实现日期类型值的转换逻辑
public class DateConverter implements Converter{
public Object convert(Class type, Object value){
if(value == null){
return null;
}else if(type == Timestamp.class){
return convertToDate(type, value, "yyyy-MM-dd HH:mm:ss");
}else if(type == Date.class){
return convertToDate(type, value, "yyyy-MM-dd");
}else if(type == String.class){
return convertToString(type, value);
}
throw new ConversionException("不能转换 " + value.getClass().getName() + " 为 " + type.getName());
}
protected Object convertToDate(Class type, Object value, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
if(value instanceof String){
try{
if(CommonUtils.isEmpty(value.toString())){
return null;
}
Date date = sdf.parse((String) value);
if(type.equals(Timestamp.class)){
return new Timestamp(date.getTime());
}
return date;
}catch(Exception pe){
return null;
}
}else if(value instanceof Date){
return value;
}
throw new ConversionException("不能转换 " + value.getClass().getName() + " 为 " + type.getName());
}
protected Object convertToString(Class type, Object value) {
if(value instanceof Date){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
if (value instanceof Timestamp) {
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
try{
return sdf.format(value);
}catch(Exception e){
throw new ConversionException("日期转换为字符串时出错!");
}
}else{
return value.toString();
}
}
}
2、注册BeanUtils转换器
ConvertUtils.register(new DateConverter(), java.util.Date.class);