简体   繁体   中英

Call Groovy Closure from Java Class - Will it Compile?

I have some legacy Java code inside which I'd like to call a groovy Closure.

Is this something that the Java / Groovy cross-compiler will be able to handle? I suspect it compiles Java first, but does it do another pass over the Groovy bytecode to resolve all the java references.

Or do I need to compile the class with closure first into a jar, so that I can access it from Java?

I see this for mixing Java and Groovy :
Mixed Java and Groovy Applications

This example looks at the issues surrounding a mixed Java/Groovy application. This issue only arises when there is mutual dependencies between your mixed language source files. So, if part of your system is pure Java for instance, you won't have this problem. You would just compile that part of your system first and reference the resulting class/jar file(s) from the part of your system that was written in Groovy.

Without having to do anything in particular, I just got a simple version of this to work by following the advice from SjB's article and creating an interface in Java, which the groovy class then implements.

In java:

interface decorator {
    public String decorate(String in) ;
}

And then implementing in Groovy:

class GroovyDecorator implements decorator {
    public String decorate(String in) {
        return "foo";
    }
}

Then using this in Java like:

...
public void javaFunc(someObject someStuff, decorator d) {
    // do some stuff
    d.decorate("input string");
}

And calling from groovy:

GroovyDecorator gd = new GroovyDecorator() ;
javaFunc(someStuff, gd) ;

This worked fine without having to do any special compilation, although I am working in an established groovy environment that may have some special configuration I'm not aware of.

Note that the auto recompilation of .groovy files did not work. If I changed GroovyDecorator, I had to restart grails, which makes implementing stuff like this much less useful.

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