简体   繁体   中英

Using groovy.lang.Closure in Java application

I would like to use the Groovy Closure class in a Java application, but am having more trouble than expected. Here's what I have:

int count = 0;
groovy.lang.Closure closure = { count = 1 };

However, when I try to compile this using JDK 7, I get the error: illegal initializer for Closure

Am I missing something really obvious? Thanks for your help.

As Oliver already said, Java does not support this syntax. (Disclaimer: all code untested) What you can do is this:

Closure closure = new Closure(null) {
  public Object doCall() {
    /* some code here */
  }
};

But this won't let you set count inside this method, because this is an Java anonymous inner class, thus count has to be final. You can bypass this with any kind of redirection, for example an array. Or you mimic what Groovy does and use this:

import groovy.lang.*;
Reference count = new Reference(0);
Closure closure = new Closure(this) {
  public Object doCall() {
    count.set(1);
  }
};

There's already an answer above, I am simply adding an working example.

Groovy Code that accepts closure,

public class GroovyService {

    Integer doSomething(Closure<Integer> fn) {
        fn()
    }
}

Calling groovy closure From java,

import groovy.lang.Closure;

public class JavaCanCallGroovy {

    public static void main(String[] args) {

        GroovyService service = new GroovyService();

        Integer data = service.doSomething(new Closure<Integer>(null) { //need to pass owner = null
            @Override
            public Integer call() {
                return 100;
            }
        });

        System.out.println(data);
    }
}

Call groovy closure from scala

import groovy.lang.Closure

object ScalaCanCallGroovy extends App {

  private val closure = new Closure[Integer]() {
    override def call() = 1
  }

  val groovyService = new GroovyService
  val data = groovyService.doSomething(closure)

  assert(data == 1)
}

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