简体   繁体   English

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

[英]How to convert Java `Consumer` to Groovy `Closure`?

I have some Java code that needs to call a Groovy API that takes a Closure as a parameter.我有一些 Java 代码需要调用一个 Groovy API 以Closure作为参数。 How do I go about converting a Java Consumer to a Groovy Closure ? go 如何将 Java Consumer转换为 Groovy Closure The code looks something like:代码看起来像:

final Consumer<Example> consumer = (Example e) -> {
  e.doSomething();
};
someGroovyApi(convertConsumerToClosure(consumer));

Rather than trying to convert the Consumer into a Closure , just create the equivalent Closure , something like:与其尝试将Consumer转换为Closure ,不如创建等效的Closure ,例如:

new Closure<Example>(outerObject) {
  public Example call(final Object o) {
    final Example e = (Example) o;

    e.doSomething();

    return e;
  }
}

You can use MethodClosure to convert a Consumer (or any other functional interface) to a Closure .您可以使用MethodClosureConsumer (或任何其他功能接口)转换为Closure

Closure closure = new MethodClosure(consumer, "accept");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM