如何枚举groovy脚本中的所有已定义变量

时间:2021-03-28 18:55:44

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?

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

2 个解决方案

#1


20  

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:

好吧,如果您使用的是一个简单的脚本(不使用“def”关键字),您定义的变量将存储在绑定中,您可以像这样得到它们:

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.

我不知道通过“def”关键字定义的变量进行枚举的简单方法,但我会兴趣地看着这个问题,看看其他人是否知道如何。

#2


4  

Actually, Ted's answer will also work for 'def'ed variables.

实际上,泰德的回答也适用于'def'ed变量。

def foo = "abc"
def bar = "def"

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

yields

baz = ghi
__ = [null, null, null]
foo = abc
_ = null
bar = def

I'm not sure what the _-variables signify, but I'm sure you can work around them.

我不确定_变量意味着什么,但我相信你可以解决它们。

#1


20  

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:

好吧,如果您使用的是一个简单的脚本(不使用“def”关键字),您定义的变量将存储在绑定中,您可以像这样得到它们:

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.

我不知道通过“def”关键字定义的变量进行枚举的简单方法,但我会兴趣地看着这个问题,看看其他人是否知道如何。

#2


4  

Actually, Ted's answer will also work for 'def'ed variables.

实际上,泰德的回答也适用于'def'ed变量。

def foo = "abc"
def bar = "def"

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

yields

baz = ghi
__ = [null, null, null]
foo = abc
_ = null
bar = def

I'm not sure what the _-variables signify, but I'm sure you can work around them.

我不确定_变量意味着什么,但我相信你可以解决它们。