以名称String(groovy)访问变量值

时间:2017-04-20 07:34:28

标签: groovy eval

我做了一些研究,但我没有为我的案例找到合适的代码。我有两个名为testtest2的变量,我想将它们放在[test:valueof(test), test2:valueof(test2)]

格式的地图中

我的代码如下:

def test="HELLO"
def test2="WORLD"
def queryText = "\$\$test\$\$ \$\$test2\$\$ this is my test"

def list = queryText.findAll(/\$\$(.*?)\$\$/)

def map = [:]
list.each{
    it = it.replace("\$\$", "")
    map.putAt(it, it)
}

queryText = queryText.replaceAll(/\$\$(.*?)\$\$/) { k -> map[k[1]] ?: k[0] }

System.out.println(map)
System.out.println(queryText)

输出:

output

期望的输出:

"HELLO WORLD this is my test"

我想我需要像map.putAt(it, eval(it))

这样的东西

修改

这是我得到输入的方式。代码进入'test'脚本

右边的是脚本中的变量名,左列是值(以后会是动态的)

enter image description here enter image description here

3 个答案:

答案 0 :(得分:3)

你快到了。
解决方案是将值放入单独的变量中,而不是将它们放入脚本绑定中。

在开头添加此内容(删除变量testtest2):

def test="HELLO"
def test2="WORLD"
binding.setProperty('test', test)     
binding.setProperty('test2', test2)  

并改变这一点:

{ k -> map[k[1]] ?: k[0] }

到此:

{ k ->  evaluate(k[1]) }

答案 1 :(得分:1)

如果你可以使用TemplateEngine,那应该很简单。

def text = '$test $test2 this is my test'
def binding = [test:'HELLO', test2:'WORLD']
def engine = new groovy.text.SimpleTemplateEngine() 
def template = engine.createTemplate(text).make(binding)
def result = 'HELLO WORLD this is my test'
assert result == template.toString()

您可以在线快速测试 Demo

答案 2 :(得分:1)

最后的工作代码,感谢所有人,尤其是那些帮助了我很多的dsharew!

#input String queryText,test,test2,test3

def list = queryText.findAll(/\$\$(.*?)\$\$/)

def map = [:]
list.each{
    it = it.replace("\$\$", "")
    map.putAt(it, it)
}

queryText = queryText.replaceAll(/\$\$(.*?)\$\$/) { k ->  evaluate(k[1]) }

return queryText