我在映射中存储了一些 GString,并尝试在运行时评估它们:
//this is in begginning of my class or controller or service and is a global variable
def placeholderStrings=["nameString":"My name is $name","professionString":"My profession is $profession"]
//this params map comes after arrival of request from client side and following code is inside the controller
params=["name":"name1","profession":"profession1"]
def paramsKeyMap=params.keySet()
paramsKeyMap.each{
bindings."$it"=params[it]
println it
}
println placeholderStrings.get("nameString") // this line gives error as groovy.lang.MissingPropertyException: No such property: name
上面的代码给出错误但下面的代码运行:
params=["name":"name1","profession":"profession1"]
def keyMap=params.keySet()
keyMap.each {
binding[it] =params[it]
println it // or even binding[it] = 'something'
}
//Now I am declaring it locally pls note this
def placeholderStrings=["nameString":"My name is $name","professionString":"My profession is $profession"]
println placeholderStrings.get("nameString") // this line gives error as groovy.lang.MissingPropertyException: No such property: name
正如我们所看到的区别,在第一个脚本中,占位符字符串是在绑定(bind)之前声明的,而在第二个脚本中,它是在绑定(bind)之后声明的。我想做类似于第一种情况的事情,因为在我的应用程序中,我需要根据客户端请求在运行时评估占位符字符串。
- 当请求到来时,我需要使用
placeholderStrings.get(keyFromParams)
获取适当的值。 - 用上面获得的字符串中的绑定(bind)替换占位符。
现在的问题是,每当我调用 placeholderStrings.get(keyFromParams)
时,它都会尝试替换字符串中的占位符并抛出异常。
为了解决这个问题,我尝试将 placeholderString 值存储为单引号字符串,例如:
def placeholderStrings=["nameString":'My name is $name',"professionString":'My profession is $profession']
但是现在我无法将上面映射中的值转换为 GString 以便可以替换占位符。那么有人可以建议可以做什么吗?
最佳答案
惰性 GString(例如 "My name is ${-> name}"
)可能会解决问题,但是将替换注入(inject)脚本绑定(bind)的整个方法感觉像是一种 hack(和潜在的安全性)洞)给我。使用模板引擎可能会更好。 Groovy 附带了 SimpleTemplateEngine
和 GStringTemplateEngine
,尽管有人告诉我它们很容易遇到内存泄漏问题(我不知道细节)。
关于groovy - 将 GString 存储在变量中并在运行时求值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17628935/