简体   繁体   English

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

[英]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? 我如何从s2构建一个GString并对其进行评估? (VALs and s2 are loaded from database, this snippet is only for demonstrating my problem.) (VAL和s2是从数据库加载的,此代码段仅用于说明我的问题。)

You can use the SimpleTemplateEngine if you can get your variables into a Map? 如果可以将变量放入Map中,则可以使用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()

edit 编辑

You can use the binding instead of the map, so the following works in the groovyconsole: 您可以使用绑定而不是地图,因此在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 注意:请注意双引号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM