我在 SOF 上搜索了一下,但没有找到与 BeanUtil 使用相关的如此基本的问题。
我有一个 POJO 类,例如 UserPojo
,其类代码是:
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;}
}
我的问题是,如何使用 BeanUtil 自动比较此 bean 的两个实例?
我尝试过这个:
final BeanComparator<UserPojo> comparator = new BeanComparator<UserPojo>();
final int comparison = comparator.compare(expectedPojo, receivedPojo);
但它因以下错误而结束:
java.lang.ClassCastException : UserPojo cannot be cast to java.lang.Comparable
我知道我的Pojo应该实现标准的Comparable
接口(interface),但是这样比较不依赖于内省(introspection),并且BeanUtil的导入似乎非常无用......
那么,如何正确使用呢?
最佳答案
你必须看看那里的各种构造函数:
BeanComparator(String property)
- 为 Bean 构造一个基于属性的比较器。
BeanComparator(String property, Comparator comparator)
- 为 Bean 构造一个基于属性的比较器。
这是前者的 javadoc(第二段是你的答案):
Constructs a property-based comparator for beans. This compares two beans by the property specified in the property parameter. This constructor creates a BeanComparator that uses a ComparableComparator to compare the property values.
Passing "null" to this constructor will cause the BeanComparator to compare objects based on natural order, that is java.lang.Comparable.
正如您所期望的,您调用的构造函数会执行以下操作:
this(null);
要比较多个属性,您可以使用第二个变体
Collections.sort(collection,
new BeanComparator("property1",
new BeanComparator("property2",
new BeanComparator("property3"))));
我个人认为 Apache Commons CompareToBuilder
和 Google Guava 的 ComparisonChain
是更好的选择。
关于java - 如何正确使用Apache Common BeanUtil的BeanComparator来受益于内省(introspection)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27131762/