Groovy:$ {}内变量的嵌套评估

时间:2012-06-11 09:21:27

标签: 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);
}

结果应该是:

Gimme the value Whatever
Gimme the value ABC-Street
Gimme the value 22222

我尝试解决这个问题要么没有给出正确的结果(例如只是obj.street),要么根本不会编译。 到目前为止,我似乎还没有理解整个概念。但是,看到这一点:http://groovy.codehaus.org/Strings+and+GString我认为应该是可能的。

1 个答案:

答案 0 :(得分:4)

那个页面会让你觉得它有可能吗?没有任何嵌套示例。

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

编辑有可能我误解了你并且故意使obj关闭而不是地图,尽管我不明白为什么。

相关问题