2014-09-26 104 views
0

有人能让我离开LambdaJ坑吗?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()))); 

而是抛出异常[编辑:由于进行代理final类的已知限制]

注意,解决此获得的一种方式是有两个字段比较里面的方法TestObject,但让我们假设我不能这样做是因为您选择的原因。

我错过了什么?

回答

0

在使用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); 
     } 
    }; 
} 

PropertyUtilsorg.apache.commons.beanutils

类使用这种匹配方式:

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