Get variable value for its name in Groovy

jabal picture jabal · Jun 15, 2011 · Viewed 7.1k times · Source

I have the following variables defined:

def VAL1 = 'foo'
def VAL2 = 'bar'

def s2 = 'hello ${VAL1}, please have a ${VAL2}'

What is the easiest way to make this substitution work? How could I build a GString from s2 and have it evaluated? (VALs and s2 are loaded from database, this snippet is only for demonstrating my problem.)

Answer

tim_yates picture tim_yates · Jun 15, 2011

You can use the SimpleTemplateEngine if you can get your variables into a Map?

import groovy.text.SimpleTemplateEngine

def binding = [ VAL1:'foo', VAL2:'bar' ]

def template = 'hello ${VAL1}, please have a ${VAL2}'

println new SimpleTemplateEngine().createTemplate( template ).make( binding ).toString()

edit

You can use the binding instead of the map, so the following works in the groovyconsole:

// No def.  We want the vars in the script's binding
VAL1 = 'foo'
VAL2 = 'bar'

def template = 'hello ${VAL1}, please have a ${VAL2}'

// Pass the variables defined in the binding to the Template
new SimpleTemplateEngine().createTemplate( template ).make( binding.variables ).toString()