2013-04-23 45 views
0

访问Groovy中另一个脚本中定义的闭包的正确和最简单的方法是什么?这可能不是最好的设计,但我有在其他脚本中定义的呼叫闭包

SomeScript.groovy定义的封闭

bindingC = { 
    ... 
} 

def localC = { 
    ... 
} 

OtherScript.groovy

SomeScript s = new SomeScript() 
s.bindingC(...); 
s.localC(...); 

注:SomeScript.groovy是程序逻辑和OtherScript。 groovy是单元测试逻辑。它们都在同一个包中,我可以在SomeScript中访问方法。

回答

3

有两种方式(我知道),你可以用它来实现你想要的;您可以实例化SomeScript并运行其内容,或者您​​可以使用groovy shell评估SomeScript。脚本需要执行这样的变量将在被创建的结合:

SomeScript.groovy:

bindingC = { 
    110.0 
} 

OtherScript.groovy溶液1:

s = new GroovyShell().evaluate new File("SomeScript.groovy") 
assert s.bindingC() == 110.0 

OtherScript.groovy溶液2:

s2 = new SomeScript() // SomeScript is also an instance of groovy.lang.Script 
s2.run() 
assert s2.bindingC() == 110.0 
+0

本地关闭无法访问权限?因为它就像一个方法的局部变量。 – xst 2013-04-23 19:17:11

+0

这是正确的.. – Will 2013-04-25 13:11:49

+0

@xst,也有groovy转换'@ Field',它可以改变脚本变量的范围:http://groovy.codehaus.org/gapi/groovy/transform/Field.html – Will 2013-05-04 11:34:47