danb
danb

Reputation: 10379

How do I enumerate all the defined variables in a groovy script

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?

Upvotes: 21

Views: 10984

Answers (3)

Amerousful
Amerousful

Reputation: 2545

Groovy Object contains method - 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.

Example:

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


println(new MyClass().dump())

stdout: <MyClass@1fa268de foo=abc bar=def>

Upvotes: 0

Urs Reupke
Urs Reupke

Reputation: 6921

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

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.

Upvotes: 4

Ted Naleid
Ted Naleid

Reputation: 26821

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.

Upvotes: 25

Related Questions