在Groovy Shell执行期间发出局部变量值

时间:2018-09-28 04:41:23

标签: groovy groovyshell

请考虑使用以下Groovy脚本:

temp = a + b
temp * 10

现在,假设ab以各自的值绑定到上下文,并且该脚本是使用Groovy Shell脚本执行的。

有没有一种方法可以获取temp变量赋值,而无需将值打印/记录到控制台?例如,给定a=2b=3,我不仅想知道脚本返回了50,还想知道temp=5。有没有办法拦截每个分配以捕获值?

任何建议或替代方案均应得到赞赏。预先感谢!

1 个答案:

答案 0 :(得分:1)

您可以通过将Binding实例传递给GroovyShell对象来捕获脚本中的所有绑定和分配。考虑以下示例:

def binding = new Binding()
def shell = new GroovyShell(binding)

def script = '''
a = 2
b = 3
temp = a + b
temp * 10
'''

println shell.run(script, 'script.groovy', [])

println binding.variables

运行此脚本会将以下两行打印到控制台:

50
[args:[], a:2, b:3, temp:5]

如果要访问temp脚本变量的值,只需执行以下操作:

binding.variables.temp
相关问题