Friday, January 8, 2010

BeanComparator and null values

I was working on a project where we need to use the Commons Beanutils library in order to make comparisons on some Java beans. Our goal was to compare multiple properties on bean which can contains null value. In order to achieve this, we try to use the BeanComparator togheter with the ComparatorChain class:
Person o1 = new Person();
Person o2 = new Person();
o1.setId(1);
o1.setName("Name");
o2.setId(1);
o2.setName("Name");
ComparatorChain comparatorChain = new ComparatorChain();
comparatorChain.addComparator(new BeanComparator("id"));
comparatorChain.addComparator(new BeanComparator("name"));
int result = comparatorChain.compare(o1, o2);

The problem here is with the null values. If the Id or the Name of a person is nulle you will get the following exception:
java.lang.ClassCastException: java.lang.NullPointerException
at org.apache.commons.beanutils.BeanComparator.compare(BeanComparator.java:155)
at org.apache.commons.collections.comparators.ComparatorChain.compare(ComparatorChain.java:277)
How to solve this issue? The solution is to use the NullComparator class and wrap the BeanComparator for example with the following code:
Person o1 = new Person();
Person o2 = new Person();
o1.setId(1);
o1.setName("Name");
o2.setId(1);
o2.setName("Name");
ComparatorChain comparatorChain = new ComparatorChain();
comparatorChain.addComparator(new BeanComparator("id"), new NullComparator());
comparatorChain.addComparator(new BeanComparator("name"), new NullComparator());
int result = comparatorChain.compare(o1, o2);
In this way the null values are managed properly and you do not have the NullPointerException anymore!