1

I have a variable that contains the name of another variable which I want to retrieve the value, e.g.:

def variable = "finalVariableValue"
def variableName = "variable"

How can I get variable.value as I only know variableName?

I've seen the a Binding could be used but I have a lot of variable that I need to put on this Binding object in order to make it works. Is the only way?

NB: this behaviour is really similar to the ant property extension mechanism.

Thanks, Michele.

Mikyjpeg
  • 1,179
  • 1
  • 13
  • 39

2 Answers2

4

By prefixing it with def you are not registering it in an object you can inspect, like a map; one could argue it is registered in the AST, but that is a rocky road.

My 0.03 are working with a map, with a binding, or with dynamic properties. Drop the def part and choose one of the solutions:

Map

Simply declare the variable as a key in a map:

def map = [:]
map.variable = "finalVariableValue"
def variableName = "variable"

assert map[variableName] == "finalVariableValue"

Binding (with script)

Use the script built-in binding. Note this only works with scripts:

variable = "finalVariableValue"
variableName = "variable"

assert binding[variableName] == "finalVariableValue"

Dynamic properties

Use some dynamic properties mechanism, like an Expando (also, you could use getProperty with setProperty and others):

class Container extends Expando {
    def declare() {
        variable = "finalVariableValue"
        variableName = "variable"
    }
}

c = new Container()
c.declare()

assert c[c.variableName] == "finalVariableValue"
Will
  • 14,348
  • 1
  • 42
  • 44
  • Thanks, I was thinking there was a more "groovy" way, but map should works. – Mikyjpeg Dec 15 '15 at 16:09
  • AFAIK groovy lacks any access to a collection of the vars. I guess you wanted something like python's [`locals()`](http://stackoverflow.com/a/1041906/563890) – Will Dec 16 '15 at 11:50
0

You can use the script's scope, simply dropping the Type definition:

variable = 'value'
name = 'variable'

assert 'variable' == this.name
assert 'value' == this[this.name]

or using @Field annotation:

import groovy.transform.Field

@Field def variable = 'value'
@Field def name = 'variable'

assert 'variable' == this.name
assert 'value' == this[this.name]
jalopaba
  • 8,039
  • 2
  • 44
  • 57