简体   繁体   English

如何从groovy导入一个闭包到java?

[英]How to import a closure from groovy to java?

I'm trying to extract a closure from a groovy script. 我正试图从一个groovy脚本中提取一个闭包。 I define the closure as 我将闭包定义为

def printMe = {str ->println str}

in my groovy file, and then try to use it by grabbing it from the binding as follows: 在我的groovy文件中,然后尝试通过从绑定中抓取它来使用它,如下所示:

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");

But I get the following error when I run this. 但是当我运行它时,我收到以下错误。

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)

Is there a way to grab a closure (or a plain method) from a groovy script? 有没有办法从groovy脚本中获取闭包(或普通方法)?

What happens if you omit the def from your closure declaration? 如果从闭包声明中省略def ,会发生什么?

printMe = { str -> println str }

By using def, I think the printMe variable becomes local to the script, rather than going in the Binding 通过使用def,我认为printMe变量变为脚本的本地变量,而不是进入Binding

Read more about Scoping and the Semantics of "def" 阅读更多关于范围和“def”的语义

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

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