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:In this way the null values are managed properly and you do not have the NullPointerException anymore!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);