首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何正确使用Apache Common BeanUtil的BeanComparator来提高自省的效益?

如何正确使用Apache Common BeanUtil的BeanComparator来提高自省的效益?
EN

Stack Overflow用户
提问于 2014-11-26 00:23:25
回答 2查看 2.7K关注 0票数 1

我在SOF上搜索了一下,但没有找到一个与BeanUtil使用相关的基本问题。

我有一个POJO类,比如说UserPojo,它的类代码是:

代码语言:javascript
复制
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的两个实例?

我试过这个:

代码语言:javascript
复制
final BeanComparator<UserPojo> comparator = new BeanComparator<UserPojo>();
final int comparison = comparator.compare(expectedPojo, receivedPojo);

但它以以下错误结束:

代码语言:javascript
复制
java.lang.ClassCastException : UserPojo cannot be cast to java.lang.Comparable

我知道我的Pojo应该实现标准的Comparable接口,但是这种方式的比较不依赖于内省,并且导入BeanUtil似乎非常无用……

那么,如何正确使用它呢?

EN

回答 2

Stack Overflow用户

发布于 2014-11-26 00:45:30

你得看看上面的各种构造器:

BeanComparator(String property)

  • 为beans构造了一个基于属性的比较器。

BeanComparator(String property, Comparator comparator)

  • 为beans构造了一个基于属性的比较器。

这是前者的javadoc (第二段是你的答案):

为bean构造了一个基于属性的比较器。这将通过property参数中指定的属性比较两个bean。此构造函数创建一个使用ComparableComparator比较属性值的BeanComparator。

将“java.lang.Comparable”传递给此构造函数将导致BeanComparator根据自然顺序(即null)比较对象。

正如您所期望的那样,您调用的构造函数只执行以下操作:

代码语言:javascript
复制
this(null);

为了比较多个属性,您可以使用第二个变体

代码语言:javascript
复制
Collections.sort(collection, 
  new BeanComparator("property1", 
    new BeanComparator("property2", 
      new BeanComparator("property3")))); 

我个人觉得Apache Commons CompareToBuilderGoogle Guava’s ComparisonChain是更好的选择。

票数 0
EN

Stack Overflow用户

发布于 2014-11-26 22:48:43

我最终放弃了,并编写了这个代码。它没有回答这个问题,但这是我解决这个问题的方法:

代码语言:javascript
复制
import org.apache.commons.beanutils.BeanUtils;

public static void assertBeansEqual(final Object expected, final Object given) {
    try {
        final Map<String, String> expectedDescription = BeanUtils.describe(expected);
        final Map<String, String> givenDescription = BeanUtils.describe(given);

        // if the two bean don't share the same attributes.
        if (!(expectedDescription.keySet().containsAll(givenDescription.keySet()))) {
            final Set<String> keySet = givenDescription.keySet();
            keySet.removeAll(expectedDescription.keySet());
            fail("The expected bean has not the same attributes than the given bean, the followings fields are not present in the expected bean :" + keySet);
        }
        if (!(givenDescription.keySet().containsAll(expectedDescription.keySet()))) {
            final Set<String> keySet = expectedDescription.keySet();
            keySet.removeAll(givenDescription.keySet());
            fail("The expected bean has not the same attributes than the given bean, the followings fields are not present in the given bean :" + keySet);
        }

        final List<String> differences = new LinkedList<String>();
        for (final String key : expectedDescription.keySet()) {
            if (isNull(expectedDescription.get(key))) {
                // if the bean1 value is null and not the other -> not equal. This test is
                // required to avoid NPE attributes values are null. (null object dot not have
                // equals method).
                if (!isNull(givenDescription.get(key))) {
                    differences.add(key);
                }
            }
            else {
                // if two attributes don't share an attributes value.
                if (!expectedDescription.get(key).equals(givenDescription.get(key))) {
                    differences.add(key);
                }
            }
        }
        if (!differences.isEmpty()) {
            String attributes = "";
            for (final String attr : differences) {
                attributes = attributes + "|" + attr;
            }
            fail("Assertion fail, the expected bean and the given bean attributes values differ for the followings attributes : " + attributes + "|");
        }
    }
    catch (final Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27131762

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档