使用BeanUtils时,遇到日期类型的空值时会抛错的解决办法

在使用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);









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值