我如何枚举groovy脚本中的所有已定义的变量 [英] How do I enumerate all the defined variables in a groovy script

查看:126
本文介绍了我如何枚举groovy脚本中的所有已定义的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个groovy脚本,在运行时上下文中的变量数量未知,我如何找到它们并打印出每个脚本的名称和值?

解决方案

好的,如果你使用的是简单的脚本(你不使用def关键字),你定义的变量将被存储在绑定中,你可以像这:

  foo =abc
bar =def

if true){
baz =ghi
this.binding.variables.each {k,v - > println$ k = $ v}
}

打印:

  foo = abc 
baz = ghi
args = {}
bar = def

我不知道枚举通过用def关键字定义的变量的简单方法,但我会感兴趣地观看这个问题,看看别人是否知道如何。

I have a groovy script with an unknown number of variables in context at runtime, how do I find them all and print the name and value of each?

解决方案

Well, if you're using a simple script (where you don't use the "def" keyword), the variables you define will be stored in the binding and you can get at them like this:

foo = "abc"
bar = "def"

if (true) {
    baz = "ghi"
    this.binding.variables.each {k,v -> println "$k = $v"}
}

Prints:

    foo = abc 
    baz = ghi 
    args = {} 
    bar = def

I'm not aware of an easy way to enumerate through the variables defined with the "def" keyword, but I'll be watching this question with interest to see if someone else knows how.

这篇关于我如何枚举groovy脚本中的所有已定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆