Tuesday, July 6, 2010

BeanUtils vs. PropertyUtils

Every now and then I come across a situation where I want to set a property by name in stead of calling the setter directly. The Apache Commons BeanUtils provides both a BeanUtils and a PropertyUtils class which implements this functionality, but I can never remember the difference between these two. When googled for this I found a comment from someone who said that PropertyUtils is the newer class so it's probably best to use that one.
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.

Concluding: If you want automatic type conversion, use BeanUtils. Otherwise both BeanUtils and PropertyUtils seem to do the same thing. Debugging through the BeanUtils code, you'll even notice that the BeanUtils class eventually uses the PropertyUtils to set the property. So, if you don't need type conversion, by using PropertyUtils you'll probably save a couple of cpu cycles.