[英]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. 我想在Java应用程序中使用Groovy Closure类,但是遇到的麻烦比预期的要多。 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
但是,当我尝试使用JDK 7编译它时,我收到错误: illegal initializer for Closure
Am I missing something really obvious? 我错过了一些非常明显的东西吗 Thanks for your help. 谢谢你的帮助。
As Oliver already said, Java does not support this syntax. 正如Oliver所说,Java不支持这种语法。 (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. 但这不会让你在这个方法中设置count,因为这是一个Java匿名内部类,因此count必须是final。 You can bypass this with any kind of redirection, for example an array. 您可以使用任何类型的重定向(例如数组)绕过此方法。 Or you mimic what Groovy does and use this: 或者你模仿Groovy做的事情并使用它:
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, 接受封闭的Groovy代码,
public class GroovyService {
Integer doSomething(Closure<Integer> fn) {
fn()
}
}
Calling groovy closure From java, 调用groovy闭包来自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 从scala调用groovy闭包
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.