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

时间:2008-10-19 14:37:38

标签: groovy scripting

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

3 个答案:

答案 0 :(得分:20)

好吧,如果您使用的是一个简单的脚本(不使用“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”关键字定义的变量进行枚举的简单方法,但我会兴趣地看这个问题,看看是否有其他人知道如何。

答案 1 :(得分:4)

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

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

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

产量

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

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

答案 2 :(得分:0)

Groovy 对象包含方法 - dump() https://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Object.html

String  dump()
Generates a detailed dump string of an object showing its class, hashCode and fields.

示例:

class MyClass {
    def foo = "abc"
    def bar = "def"
}


println(new MyClass().dump())

标准输出:<MyClass@1fa268de foo=abc bar=def>