我正在尝试从 groovy 脚本中提取闭包。我将闭包定义为
def printMe = {str ->println str}
在我的 groovy 文件中,然后尝试通过从绑定(bind)中获取它来使用它,如下所示:
GroovyScriptEngine gse = new GroovyScriptEngine(new String[] { "scripts" });
Binding binding = new Binding();
gse.run("test.groovy", binding);
Closure cls = (Closure) binding.getVariable("printMe");
cls.call("foo");
但是当我运行它时出现以下错误。
groovy.lang.MissingPropertyException: No such property:
printMe for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:55)
at GroovyTry.main(GroovyTry.java:19)
有没有办法从 groovy 脚本中获取闭包(或普通方法)?
最佳答案
如果从闭包声明中省略 def
会怎样?
printMe = { str -> println str }
通过使用 def,我认为 printMe
变量成为脚本的本地变量,而不是进入绑定(bind)
阅读更多关于 Scoping and the Semantics of "def" 的信息
关于java - 如何将闭包从 groovy 导入到 java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3370455/