smas smas -4 years ago 166
Java Question

BeanUtils.copyProperties convert Integer null to 0

I noticed that BeanUtils.copyProperties(dest, src) has a strange side effect. All null

etc. too) convert to 0 in both objects: source (sic!) and destination. Version: commons-beanutils-1.7.0


Copy property values from the origin bean to the destination bean for
all cases where the property names are the same.

For example:

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

It can be very buggy that source object is actually modified. What is the best solution to make "real" copy of object with null value.

Answer Source

Ok I've found this post

There is however a big difference between these two classes which I came across while using these classes: BeanUtils does an automatic type conversion and PropertyUtils does not.

For example: with BeanUtils you can set a double valued property by providing a String. BeanUtils will check the type of the property and convert the String into a double. With PropertyUtils you always have to provide a value object of the same type as the property, so in this example a double.

Automatic conversion is not necessary in this case, so better choice is PropertyUtils class

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download