BeanUtils.copyProperties将Integer null转换为0

问题描述:

我注意到BeanUtils.copyProperties(dest,src)有一个奇怪的副作用。全部为空Integers(可能是Long,Date等)在这两个对象中都会转换为0:source(sic!)和destination。版本:公地的BeanUtils-1.7.0BeanUtils.copyProperties将Integer null转换为0

的javadoc:从原点豆到目的地豆的 所有情况下的属性名称是相同的

复制属性值。

例如:

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 

可以非常错误该源对象真正被修改。什么是最好的解决方案,使空值的“真正”的对象的副本。

+0

其中BeanUtils的版本?我有一些过时的问题 – Dewfy

+0

commons-beanutils-1.7.0,添加到帖子 – smas

好,我找到this post

然而有我 碰到而使用这些类这两个类之间有很大的区别:BeanUtils的做自动 类型转换和PropertyUtils没有。

例如:使用BeanUtils,您可以设置一个双值属性 提供一个字符串。 BeanUtils将检查该属性的类型并将该字符串转换为双精度型。使用PropertyUtils,您总是有 提供与属性相同类型的值对象,因此在此 示例中为double。

自动转换是没有必要在这种情况下,所以更好的选择是PropertyUtils

检查http://commons.apache.org/beanutils/api/org/apache/commons/beanutils/ConvertUtilsBean.html它表示整数转换的默认值为0.这是因为此处的目标类型是基本int或引用int,并且基本int不能设置为null。

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

UPDATE:用法

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

IntegerConverter converter = new IntegerConverter(null); 
BeanUtilsBean beanUtilsBean = new BeanUtilsBean(); 
beanUtilsBean.getConvertUtils().register(converter, Integer.class); 

看看为IntegerConverter的源代码 - 你在构造函数中设置的默认值。

+0

听起来像解释。所以我需要做的是替换/修改此转换器返回null - 默认值 – smas