在Groovy中获取其名称的变量值

时间:2011-06-15 10:06:18

标签: groovy gstring

我定义了以下变量:

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

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

使这种替换最简单的方法是什么? 我如何从s2构建一个GString并对其进行评估? (VALs和s2是从数据库加载的,这个代码片段仅用于演示我的问题。)

2 个答案:

答案 0 :(得分:6)

如果您可以将变量放入地图,可以使用SimpleTemplateEngine

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()

修改

您可以使用绑定而不是地图,因此以下适用于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()

答案 1 :(得分:1)

以及如何:

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

def s2 = "hello ${VAL1}, please have a ${VAL2}".toString()

注意:注意双引号