简体   繁体   中英

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. 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));

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;
  }
}

You can use MethodClosure to convert a Consumer (or any other functional interface) to a Closure .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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