通过名称访问变量值作为字符串 (groovy)
Access variable value by its name as String (groovy)
我已经做了一些研究,但我还没有找到适用于我的案例的工作代码。我有两个名为 test
和 test2
的变量,我想将它们以 [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)
输出:
期望的输出:
"HELLO WORLD this is my test"
我想我需要类似 map.putAt(it, eval(it))
的东西
编辑
这是我获取输入的方式。代码进入 'test'
脚本
右边是脚本中的变量名,左边是值(稍后会是动态的)
如果能用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
你快到了。
解决方案不是将值放入单独的变量中,而是将它们放入脚本绑定中。
在开头添加这个(删除变量test
和test2
):
def test="HELLO"
def test2="WORLD"
binding.setProperty('test', test)
binding.setProperty('test2', test2)
并更改此:
{ k -> map[k[1]] ?: k[0] }
对此:
{ k -> evaluate(k[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
我已经做了一些研究,但我还没有找到适用于我的案例的工作代码。我有两个名为 test
和 test2
的变量,我想将它们以 [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)
输出:
期望的输出:
"HELLO WORLD this is my test"
我想我需要类似 map.putAt(it, eval(it))
编辑
这是我获取输入的方式。代码进入 'test'
脚本
右边是脚本中的变量名,左边是值(稍后会是动态的)
如果能用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
你快到了。
解决方案不是将值放入单独的变量中,而是将它们放入脚本绑定中。
在开头添加这个(删除变量test
和test2
):
def test="HELLO"
def test2="WORLD"
binding.setProperty('test', test)
binding.setProperty('test2', test2)
并更改此:
{ k -> map[k[1]] ?: k[0] }
对此:
{ k -> evaluate(k[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