在 Groovy Shell 执行期间发出局部变量值
Emit local variable values during Groovy Shell execution
假设我们有以下 Groovy 脚本:
temp = a + b
temp * 10
现在,假设 a
和 b
绑定到具有各自值的上下文,并且脚本是使用 groovy shell 脚本执行的。
有没有一种方法可以获得 temp
变量赋值的值,而无需 printing/logging 控制台的值?例如,给定 a=2
和 b=3
,我不仅想知道脚本返回了 50
,还想知道 temp=5
。有没有办法拦截每个赋值来捕获值?
如有任何建议或替代方案,我们将不胜感激。提前致谢!
您可以通过将 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
假设我们有以下 Groovy 脚本:
temp = a + b
temp * 10
现在,假设 a
和 b
绑定到具有各自值的上下文,并且脚本是使用 groovy shell 脚本执行的。
有没有一种方法可以获得 temp
变量赋值的值,而无需 printing/logging 控制台的值?例如,给定 a=2
和 b=3
,我不仅想知道脚本返回了 50
,还想知道 temp=5
。有没有办法拦截每个赋值来捕获值?
如有任何建议或替代方案,我们将不胜感激。提前致谢!
您可以通过将 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