Reputation: 3036
What is the correct and simplest way to access a closure defined within another script in Groovy. This might not be the best design, but I have a closure defined in
SomeScript.groovy
bindingC = {
...
}
def localC = {
...
}
OtherScript.groovy
SomeScript s = new SomeScript()
s.bindingC(...);
s.localC(...);
Note: SomeScript.groovy is program logic and OtherScript.groovy is unit testing logic. They are both in the same package and I'm able to access methods in SomeScript already.
Upvotes: 0
Views: 740
Reputation: 14519
There are two ways (i'm aware) you can use to achieve what you want; you can either instantiate the SomeScript
and run its contents or you can evaluate SomeScript
using groovy shell. The script needs to be executed so the variable will be created in the binding:
SomeScript.groovy:
bindingC = {
110.0
}
OtherScript.groovy solution 1:
s = new GroovyShell().evaluate new File("SomeScript.groovy")
assert s.bindingC() == 110.0
OtherScript.groovy solution 2:
s2 = new SomeScript() // SomeScript is also an instance of groovy.lang.Script
s2.run()
assert s2.bindingC() == 110.0
Upvotes: 3