Get variable value for its name in Groovy
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.)
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()
and what about :
def VAL1 = 'foo'
def VAL2 = 'bar'
def s2 = "hello ${VAL1}, please have a ${VAL2}".toString()
?
Note : notice the double quotes
精彩评论