Sunday, March 28, 2010

Apache BeanUtils copyProperties turns Integer null to 0

I was working on an existing code base with using Apache BeanUtils.copyProperties. People in the team knows that the performance by using it is really bad. But since the uses of this BeanUtils is only affect testing and it's really easy to use, so no one is actually disagree to use it.

However, when I develop my test, I found a very strange behaviour from the BeanUtils.copyProperties method. If the source object has an attribute Integer and the value of it is null, after called the copyProperties method and the target object will turn it to an Integer object with value 0. (*Note that the source and target are the same class.) I searched over the net, many people knows that it's a problem and the reason is because BeanUtils register 0 as default to those primitive related object. http://commons.apache.org/beanutils/v1.8.2/apidocs/org/apache/commons/beanutils/ConvertUtilsBean.html

The story is not end yet. I found another interesting part is if you declare your source/target class to be default class instead of public class. It will actually not change the Integer object from null to 0, which will be the desired behaviour.

I don't understand why the scope of the class will make the difference. I guess if you are interested in that, you may need to look at the Apache BeanUtils source code and Java reflection to see how it behaves. For me, I wouldn't be bothered to dig deep as I have already changed to use another BeanUtils library from Spring Framework, which does the same job but it gives me the desired behaviour. Or if cglib improve their documentation in some day, I would prefer to use it as it has much better performance.

*Note that I was using Apache BeanUtils 1.8.0.
** Usage: Apache BeanUtils.copyProperties(<target object>, <source object>) whereas Spring BeanUtils.copyProperties(<source object>, <target object>)

No comments:

Post a Comment