如何将Java中的`Consumer`转换为Groovy中的`Closure`?

huangapple go评论71阅读模式
英文:

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&lt;Example&gt; consumer = (Example e) -&gt; {
  e.doSomething();
};
someGroovyApi(convertConsumerToClosure(consumer));

答案1

得分: 2

您可以使用MethodClosureConsumer(或任何其他函数接口)转换为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, &quot;accept&quot;);

答案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&lt;Example&gt;(outerObject) {
  public Example call(final Object o) {
    final Example e = (Example) o;

    e.doSomething();

    return e;
  }
}

huangapple
  • 本文由 发表于 2020年8月4日 05:14:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63237044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定