【问题标题】:LambdaJ: matching on fields of the same objectLambdaJ:匹配同一对象的字段
【发布时间】:2014-09-26 09:31:49
【问题描述】:

谁能帮我摆脱掉入的 LambdaJ 坑?

假设我有一个此类对象的列表:

private class TestObject {
    private String A;
    private String B;
    //gettters and setters
}

假设我想从A.equals(B) 的列表中选择对象

我试过了:

 List<TestObject> theSameList = select(testList, having(on(TestObject.class).getA(), equalTo(on(TestObject.class).getB())));

但这会返回一个空列表

还有这个:

List<TestObject> theSameList = select(testList, having(on(TestObject.class).getA().equals(on(TestObject.class).getB())));

但这会引发异常 [EDIT:由于代理最终类的已知限制]

注意,解决此问题的一种方法是使用一种方法来比较 TestObject 中的两个字段,但我们假设由于您选择的原因我不能这样做。

我错过了什么?

【问题讨论】:

    标签: java hamcrest lambdaj


    【解决方案1】:

    在使用 LambdaJ 来匹配同一对象的字段后,唯一对我有用的解决方案是编写自定义匹配器。这是一个可以完成这项工作的快速而肮脏的实现:

    private Matcher<Object> hasPropertiesEqual(final String propA, final String propB) {
        return new TypeSafeMatcher<Object>() {
    
    
            public void describeTo(final Description description) {
                description.appendText("The propeties are not equal");
            }
    
            @Override
            protected boolean matchesSafely(final Object object) {
    
                Object propAValue, propBValue;
                try {
                    propAValue = PropertyUtils.getProperty(object, propA);
                    propBValue = PropertyUtils.getProperty(object, propB);
                } catch(Exception e) {
    
                    return false;
                }
    
                return propAValue.equals(propBValue);
            }
        };
    }
    

    PropertyUtils 是来自org.apache.commons.beanutils 的类

    这个匹配器的使用方法:

    List<TestObject> theSameList = select(testList, having(on(TestObject.class), hasPropertiesEqual("a", "b")));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-26
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 1970-01-01
      相关资源
      最近更新 更多