I searched around on SOF but don't find a so basic question related to BeanUtil use.
I have a POJO class let's say for example UserPojo
whose the class code is :
public class UserPojo{
private String name;
private int gender;
private int size;
//Setters
public void setName(String name) {this.name =name;}
public void setGender(int gender){this.gender=gender;}
public void setSize(int size) {this.size =size;}
//getters
public String getName() {return this.name;}
public int getGender(){return this.gender;}
public int getSize() {return this.size;}
}
My question is, how to use BeanUtil to automatically compare two instance of this bean ?
I tried this :
final BeanComparator<UserPojo> comparator = new BeanComparator<UserPojo>();
final int comparison = comparator.compare(expectedPojo, receivedPojo);
But it end on the following error:
java.lang.ClassCastException : UserPojo cannot be cast to java.lang.Comparable
I understand that my Pojo should implement the standard Comparable
interface, but this way the comparison do not rely on introspection and the import of BeanUtil seems very useless...
So, how to correctly use it ?
You've gotta look at the various constructors on there:
BeanComparator(String property)
BeanComparator(String property, Comparator comparator)
Here's the former's javadoc (2nd para is your answer):
As you'd expect, the constructor you're invoking does just this:
For comparing multiple properties, you could make use of the 2nd variant
I personally felt that the
Apache Commons CompareToBuilder
andGoogle Guava’s ComparisonChain
as better choices.