java - 如何正确使用Apache Common BeanUtil的BeanComparator来受益于内省(introspection)?

标签 java javabeans apache-commons introspection apache-commons-beanutils

我在 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 CompareToBuilderGoogle Guava 的 ComparisonChain 是更好的选择。

关于java - 如何正确使用Apache Common BeanUtil的BeanComparator来受益于内省(introspection)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27131762/

相关文章:

java - 在 JBoss 4.2.x 上升级到 Quartz 1.6

行为附加到注释的 Java 设计问题

Java 多线程 - 有没有办法同步/锁定映射中的特定值以进行读取和写入?

java - 如何在 Play 框架的索引页面上加载示例 html 页面?

java - 将 JavaBeans 编码为多种格式

java - 反序列化 session 数据时出现 InvalidClassException 错误

java - Apache Commons CSV - 不区分大小写的标题?

java - 使用 Java Swing 计算并显示文本框中的字符数

执行了Java垃圾回收,但未收到GC通知

java - 如何将元素添加到具有模型类型的列表中