BeanUtils扩展

在使用BeanUtils进行对象属性复制时,遇到Java.util.Date类型转换异常以及Java.lang.Integer为null时默认转为0的问题。为避免意外结果,文章探讨了对BeanUtils进行扩展的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import org.apache.commons.beanutils.BeanUtils;

当使用BeanUtils时,

  1. java.util.Date类型转换会出现异常;
  2. java.lang.Integer(当为null的时候)会默认 转为0值,出现一些意外的结果

解决方案,对BeanUtils进行拓展:

import org.apache.commons.beanutils.Converter;

import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BeanUtilsExt extends BeanUtils {
    static {
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        ConvertUtils.register(new IntegerConvert(), java.lang.Integer.class);
    }

    public static void copyProperties(Object dest, Object orig) {
        try {
            BeanUtils.copyProperties(dest, orig);
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        } catch (InvocationTargetException ex) {
            ex.printStackTrace();
        }
    }
}
class DateConvert implements Converter {
    public Object convert(Class arg0, Object arg1) {
        Date d = (Date) arg1;
        if (d == null) {
            return null;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.parse(sdf.format(d));
        } catch (Exception e) {
            return null;
        }
    }
}
class IntegerConvert implements Converter {
    public Object convert(Class arg0, Object arg1) {
        Integer d = (Integer) arg1;
        if (d == null) {
            return null;
        }

        return d;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值