简体   繁体   English

从Java类调用Groovy Closure - 它会编译吗?

[英]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. 我有一些遗留的Java代码,我想称之为groovy Closure。

Is this something that the Java / Groovy cross-compiler will be able to handle? 这是Java / Groovy交叉编译器能够处理的东西吗? I suspect it compiles Java first, but does it do another pass over the Groovy bytecode to resolve all the java references. 我怀疑它首先编译Java,但它是否通过Groovy字节码再次传递以解析所有java引用。

Or do I need to compile the class with closure first into a jar, so that I can access it from Java? 或者我是否需要首先将带有闭包的类编译到jar中,以便我可以从Java访问它?

I see this for mixing Java and Groovy : 我看到这个混合Java和Groovy:
Mixed Java and Groovy Applications 混合Java和Groovy应用程序

This example looks at the issues surrounding a mixed Java/Groovy application. 此示例查看有关混合Java / Groovy应用程序的问题。 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. 因此,如果您的系统的一部分是纯Java,那么您将不会遇到此问题。 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. 您只需先编译系统的那一部分,然后从系统中用Groovy编写的部分引用生成的类/ jar文件。

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. 我不需要特别做任何事情,只需按照SjB文章的建议并在Java中创建一个接口,然后实现groovy类,我就可以得到一个简单的版本。

In java: 在java中:

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

And then implementing in Groovy: 然后在Groovy中实现:

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

Then using this in Java like: 然后在Java中使用它:

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

And calling from groovy: 从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. 这很好,无需进行任何特殊的编译,虽然我在一个已建立的groovy环境中工作,可能有一些我不知道的特殊配置。

Note that the auto recompilation of .groovy files did not work. 请注意,.groovy文件的自动重新编译不起作用。 If I changed GroovyDecorator, I had to restart grails, which makes implementing stuff like this much less useful. 如果我更改了GroovyDecorator,我不得不重新启动grails,这使得实现这样的东西变得不那么有用了。

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

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