The example below shows a couple ways of setting variables in the binding, getting the variable values from the binding and how to capture standard output from the script. The one tricky part is the question "When is something in the Binding and when not?" The answer is: when it's not defined, it is in the binding! In the example below, variable c is placed in the binding, but since it is def'd in the script, the value for that variable comes from the local variable rather than the binding.
// setup binding
def binding = new Binding()
binding.a = 1
binding.setVariable('b', 2)
binding.c = 3
println binding.variables
// setup to capture standard out
def content = new StringWriter()
binding.out = new PrintWriter(content)
// evaluate the script
def ret = new GroovyShell(binding).evaluate('''
def c = 9
println 'a='+a
println 'b='+b
println 'c='+c
retVal = a+b+c
a=3
b=2
c=1
''')
// validate the values
assert binding.a == 3
assert binding.getVariable('b') == 2
assert binding.c == 3 // binding does NOT apply to def'd variable
assert binding.retVal == 12 // local def of c applied NOT the binding!
println 'retVal='+binding.retVal
println binding.variables
println content.toString()
Output
[a:1, b:2, c:3] retVal=12 [a:3, b:2, c:3, out:java.io.PrintWriter@1e0799a, retVal:12] a=1 b=2 c=9
Hope this helps!
No comments:
Post a Comment