2010-07-30 66 views
7

我試圖從一個Groovy腳本關閉。我定義的蓋,如何從常規導入封閉到Java?

def printMe = {str ->println str} 
在我的常規文件

,然後嘗試從綁定抓住它,如下所示使用它:

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腳本中獲取閉包(或普通方法)?

回答

9

如果您忽略你的閉合聲明def會發生什麼?

printMe = { str -> println str } 

通過使用閃避,我認爲printMe變量變成本地的腳本,而不是要在綁定

瞭解更多關於Scoping and the Semantics of "def"

+0

嘿感謝,這是現貨上。 – brice 2010-07-30 10:35:38