Ant*_*era 5 groovy predicate java-8
我有这个运行良好的 Java 8 代码:
//Java 8
@Test public void testPredicates(){
Predicate<Integer> p1 = (i) -> true;
Predicate<Integer> p2 = (i) -> true;
Predicate<Integer> p3 = p1.and(p2);
List<Integer> is = new ArrayList<>();
is.add(1);
is.add(2);
assertTrue(is.stream().allMatch(p1.and(p2)));
}
Run Code Online (Sandbox Code Playgroud)
我在 Groovy (2.2) 中最接近它的是:
//Groovy 2.2
@Test
void test(){
Predicate<Integer> p1 = { i -> true}
Predicate<Integer> p2 = {i -> true}
Predicate<Integer> p3 = p2.and(p1)
List<Integer> is = new ArrayList<>()
is.add(1)
is.add(2)
assert(is.stream().allMatch(p1.and(p2)))
}
Run Code Online (Sandbox Code Playgroud)
Groovy 代码在调用该and方法的行上失败并显示以下内容:
java.lang.ClassCastException: java.lang.Boolean
cannot be cast to java.util.function.Predicate
Run Code Online (Sandbox Code Playgroud)
如果我用 just 替换断言assert(is.stream().allMatch(p1)),则测试成功完成。问题是and在谓词上调用方法。
例如p2在调试器中检查,我可以看到它有类型OneParameterTest$_test_closure2。反编译字节码可以验证这一点。
我有一种感觉,尽管我不确定,这与隐式闭包强制有关(请参阅http://groovy.codehaus.org/Groovy+2.2+release+notes)。
有什么方法可以编写 Groovy 代码,以便将谓词创建为 的真实实例java.util.function.Predicate?
有没有办法编写 Groovy 代码,以便将谓词创建为 java.util.function.Predicate 的真实实例?
您正在做的是创建 Predicate 的真实实例。问题是您创建它们的方式实际上只对单一方法接口有用。Predicate 定义了几种方法。有几种方法可以解决这个问题。也许最简单的方法是利用 Groovy 的 Map 接口支持。下面的代码仅考虑“and”和“test”,但您可以提供您实际调用的任何内容并省略其他内容。
很难从您的代码片段中说出您真正想要完成的任务,但只是为了解决您编写的特定测试,您应该能够执行类似的操作。测试方法都被硬编码为在此处返回 true,就像在您的测试中一样,但您可能在那里有真正的逻辑。
Predicate<Integer> p1 = [test:{ t -> true},
and: { Predicate other -> [test: { t -> true}] as Predicate}] as Predicate
// in your example you are never calling p2.and(...), but
// it is included here for consistency with the one above...
Predicate<Integer> p2 = [test:{ t -> true},
and: { Predicate other -> [test: { t -> true}] as Predicate}] as Predicate
// it isn't clear why you are creating p3, but you can...
Predicate<Integer> p3 = p1.and(p2)
List<Integer> is = new ArrayList<>()
is.add(1)
is.add(2)
assert(is.stream().allMatch(p1.and(p2)))
Run Code Online (Sandbox Code Playgroud)