英文:
How to convert Java `Consumer` to Groovy `Closure`?
问题
我有一些Java代码需要调用一个接受Closure作为参数的Groovy API。我该如何将Java的Consumer转换为Groovy的Closure?代码大致如下:
final Consumer<Example> consumer = (Example e) -> {
e.doSomething();
};
someGroovyApi(convertConsumerToClosure(consumer));
英文:
I have some Java code that needs to call a Groovy API that takes a Closure as a parameter. How do I go about converting a Java Consumer to a Groovy Closure? The code looks something like:
final Consumer<Example> consumer = (Example e) -> {
e.doSomething();
};
someGroovyApi(convertConsumerToClosure(consumer));
答案1
得分: 2
您可以使用MethodClosure将Consumer(或任何其他函数接口)转换为Closure。
Closure closure = new MethodClosure(consumer, "accept");
英文:
You can use MethodClosure to convert a Consumer (or any other functional interface) to a Closure.
Closure closure = new MethodClosure(consumer, "accept");
答案2
得分: 1
不必试图将Consumer转换为Closure,只需创建等效的Closure,类似于:
new Closure<Example>(outerObject) {
public Example call(final Object o) {
final Example e = (Example) o;
e.doSomething();
return e;
}
}
英文:
Rather than trying to convert the Consumer into a Closure, just create the equivalent Closure, something like:
new Closure<Example>(outerObject) {
public Example call(final Object o) {
final Example e = (Example) o;
e.doSomething();
return e;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论