Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 584
danb Avatar asked Oct 19 '08 14:10

danb


People also ask

How do you define a variable in Groovy?

Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.

How do I print values in a Groovy script?

You can use the print function to print a string to the screen. You can include \n to embed a newline character. There is no need for semi-colon ; at the end of the statement. Alternatively you can use the println function that will automatically append a newline to the end of the output.

How do you set a global variable in Groovy?

import groovy. transform. Field var1 = 'var1' @Field String var2 = 'var2' def var3 = 'var3' void printVars() { println var1 println var2 println var3 // This won't work, because not in script scope. }

What are the data types in Groovy?

Groovy supports the same primitive types as defined by the Java Language Specification: integral types: byte (8 bit), short (16 bit), int (32 bit) and long (64 bit) floating-point types: float (32 bit) and double (64 bit) the boolean type (one of true or false )


2 Answers

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.

like image 182
Ted Naleid Avatar answered Sep 20 '22 10:09

Ted Naleid


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.

like image 25
Urs Reupke Avatar answered Sep 21 '22 10:09

Urs Reupke