BeanUtils.copyProperties将Integer null转换为0

luk*_*ymo 15 java reflection spring javabeans

我注意到BeanUtils.copyProperties(dest,src)有一个奇怪的副作用.全空Integers(也许Long,Date等过)转换为0两个对象:源(原文如此)和目的地.版本:commons-beanutils-1.7.0

的Javadoc:

对于属性名称相同的所有情况,将属性值从原始bean复制到目标bean.

例如:

class User {
   Integer age = null;
   // getters & setters
}
...
User userDest = new User();
User userSrc = new User();
BeanUtils.copyProperties(userDest, userSrc);
System.out.println(userDest.getAge()); // 0
System.out.println(userSrc.getAge()); // 0
Run Code Online (Sandbox Code Playgroud)

实际修改源对象可能非常麻烦.使用null值制作对象的"真实"副本的最佳解决方案是什么.

Mic*_*les 16

检查http://commons.apache.org/beanutils/api/org/apache/commons/beanutils/ConvertUtilsBean.html它表示整数转换的默认值为0.这是因为这里的目标类型是原始int或引用int和原始int不能设置为null.

您可以覆盖Integer的转换器,并将其替换为默认值为null的转换器.

更新:用法是

import org.apache.commons.beanutils.converters.IntegerConverter;

IntegerConverter converter = new IntegerConverter(null); 
BeanUtilsBean beanUtilsBean = new BeanUtilsBean();
beanUtilsBean.getConvertUtils().register(converter, Integer.class);
Run Code Online (Sandbox Code Playgroud)

看一下IntegerConverter的源代码 - 在构造函数中设置默认值.


luk*_*ymo 16

好的,我发现了这篇文章

然而,在使用这些类时我遇到的这两个类之间存在很大差异:BeanUtils执行自动类型转换而PropertyUtils不执行.

例如:使用BeanUtils,您可以通过提供String来设置双值属性.BeanUtils将检查属性的类型并将String转换为double.使用PropertyUtils,您始终必须提供与属性相同类型的值对象,因此在此示例中为double.

在这种情况下不需要自动转换,因此更好的选择是PropertyUtils