1
def var1 = "test"
def test = "Hello"

Now I want to print "Hello" using var1 variable, like:

echo "${{var1}}"

But it is not working for me.

Opal
  • 81,889
  • 28
  • 189
  • 210

2 Answers2

1

The only idea (I'm aware of) to make it work is the following piece of code:

import groovy.transform.Field

@Field
def var1 = "test"
@Field
def test = "Hello"

def field = this.getClass().getDeclaredField(var1)
field.setAccessible(true)
println field.get(this)

What you tried will not work for sure. @the_storyteller's idea with Map also makes sense.

Opal
  • 81,889
  • 28
  • 189
  • 210
0

To the best of my knowledge, Groovy doesn't support referencing variables using a String variable name.

The best way I know to reference a value using a String is to store it in a map, and query the map. You can find an example in this answer: To use a string value as a variable name

the_storyteller
  • 2,335
  • 1
  • 26
  • 37