Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java BeanUtils.copyProperties将整型null转换为0_Java_Spring_Reflection_Javabeans - Fatal编程技术网

Java BeanUtils.copyProperties将整型null转换为0

Java BeanUtils.copyProperties将整型null转换为0,java,spring,reflection,javabeans,Java,Spring,Reflection,Javabeans,我注意到BeanUtils.copyProperties(dest,src)有一个奇怪的副作用。所有空整数(可能也有长,日期等)在两个对象中都转换为0:源(原文如此!)和目标。版本:commons-beanutils-1.7.0 javadoc: 将属性值从源bean复制到目标bean,以便 属性名称相同的所有情况 例如: class User { Integer age = null; // getters & setters } ... User userDest = n

我注意到BeanUtils.copyProperties(dest,src)有一个奇怪的副作用。所有空
整数
(可能也有
日期
等)在两个对象中都转换为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
源对象实际上被修改了,这可能是非常错误的。使用空值创建对象的“真实”副本的最佳解决方案是什么

选中它表示整数转换的默认值为0。这是因为这里的目标类型是基元int或引用int,基元int不能设置为null

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

更新:用法是

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

IntegerConverter converter = new IntegerConverter(null); 
BeanUtilsBean beanUtilsBean = new BeanUtilsBean();
beanUtilsBean.getConvertUtils().register(converter, Integer.class);
看看IntegerConverter的源代码-您在构造函数中设置了默认值。

好的,我找到了

然而,这两门课之间有一个很大的区别 在使用这些类时遇到:BeanUtils执行自动 类型转换和PropertyUtils不支持

例如:对于BeanUtils,可以通过 提供字符串。BeanUtils将检查属性的类型和 将字符串转换为双精度字符串。拥有你一直拥有的财产 提供与属性类型相同的值对象,因此 例子是双重的


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

哪个版本的beanUtils?我在postSo中添加的obsoletecommons-beanutils-1.7.0中遇到了一些问题。如果我覆盖类中某个特定函数的配置,那么不同类中使用的bean UTIL实例会发生什么情况。重写是特定于该函数还是该类的所有函数?请听我解释。所以我需要做的是替换/修改这个转换器以返回null-默认值