我在地图中存储了一些 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
正如我们所看到的区别,在第一个脚本中,placeholderStrings 在绑定之前声明,而在第二个脚本中,它是在绑定之后声明的。我想做类似于第一种情况的事情,因为在我的应用程序中,我需要在运行时根据客户端请求评估占位符字符串。
- 当请求到来时,我需要使用
placeholderStrings.get(keyFromParams)
. - 用上面获得的字符串中的绑定替换占位符。
现在的问题是,当我调用 时placeholderStrings.get(keyFromParams)
,它会尝试替换字符串中的占位符并引发异常。
为了解决这个问题,我尝试将 placeholderString 值存储为单引号字符串,例如:
def placeholderStrings=["nameString":'My name is $name',"professionString":'My profession is $profession']
但是现在我无法将上面映射中的值转换为 GString 以便可以替换占位符。所以有人可以建议可以做什么吗?