use*_*982 5 string groovy gstring
我有办法在Groovy中对"$ -Strings"进行嵌套评估,例如
def obj = {["name":"Whatever", "street":"ABC-Street", "zip":"22222"]}
def fieldNames = ["name", "street", "zip"]
fieldNames.each{ fieldname ->
def result = " ${{->"obj.${fieldname}"}}" //can't figure out how this should look like
println("Gimme the value "+result);
}
Run Code Online (Sandbox Code Playgroud)
结果应该是:
Gimme the value Whatever
Gimme the value ABC-Street
Gimme the value 22222
Run Code Online (Sandbox Code Playgroud)
我试图解决这个问题要么没有给出正确的结果(例如只是obj.street),要么根本不会编译.到目前为止,我根本就没有理解整个概念.但是,看到这个:http:// groovy.codehaus.org/Strings+and+GString我相信它应该是可能的.
该页面的什么让您认为这是可能的?没有任何嵌套示例。
AFAIK 默认情况下这是不可能的;${}
不会重新评估其中的表达式。无论如何,这都是危险的,因为很容易使其无限深并破坏堆栈。
在这种情况下,无论如何都没有必要。
obj
成为一个实际的地图,而不是一个闭包,并且[]
对字段名称使用法线贴图访问def obj = [ "name": "Whatever", "street": "ABC-Street", "zip": "22222" ]
def fieldNames = ["name", "street", "zip"]
fieldNames.each { println "Gimme the value ${obj[it]}" }
Gimme the value -> Whatever
Gimme the value -> ABC-Street
Gimme the value -> 22222
Run Code Online (Sandbox Code Playgroud)
编辑我可能误解了,你故意关闭obj
而不是地图,尽管我不明白为什么。