使用反射时遇到 org.apache.commons.beanutils.ConversionException: No value specified

本文探讨了在使用BeanUtils进行对象属性复制时遇到的空值问题,提供了两种解决方案:一是通过设置默认值来处理空的Date类型;二是通过自定义方法在执行BeanUtils.copyProperties()前检查对象所有字段是否为空。

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

原因为:使用BeanUtils时,有些类型值为空,例如Date。

若为Date:

- 1.设置默认值

如 ConvertUtils.register(new DateConverter(null), java.util.Date.class);
或在get/set方法中设置

- 2.执行BeanUtils.copyProperties()方法前,判断对象属性值是否为空

  if (!(CheckObjAllFieldsIsNull.checkObjAllFieldsIsNull(object))) {...}
public class CheckObjAllFieldsIsNull {
    /**
     * 判断对象中属性值是否全为空
     *
     * @param object
     * @return
     */
    public static boolean checkObjAllFieldsIsNull(Object object) {
        if (null == object) {
            return true;
        }

        try {
            for (Field f : object.getClass().getDeclaredFields()) {
                f.setAccessible(true);

                System.out.print(f.getName() + ":");
                System.out.println(f.get(object));

                if (f.get(object) != null && StringUtils.isNotBlank(f.get(object).toString())) {
                    return false;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }
}

觉得还不错可以点个赞哦~ 谢谢(๑•ᴗ•๑)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值