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

标签 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我相信这应该是可能的。

最佳答案

那个页面怎么样让你认为这是可能的?没有任何嵌套示例。

AFAIK 默认情况下是不可能的; ${} 中的表达式不会重新评估。无论如何这都是危险的,因为它真的很容易使其无限深并炸毁堆栈。

在这种情况下,无论如何都没有必要。

  • 制作 obj是一个实际的 map ,而不是一个闭包,和
  • 使用法线贴图 []访问字段名称

  • 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关闭而不是 map ,虽然我不明白为什么。

    关于string - Groovy:${} 内变量的嵌套评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10977361/

    相关文章:

    java - 动态 GString 创建不符合我的预期

    javascript - 在书签中转义原始的、未转义的字符串

    javascript - 替换 json/jsObject/string 中的多个值

    c - 在链表上使用 strtok()

    Groovy 节点与节点列表

    groovy - 如何避免说 "gstring"?

    c++ - 在 C++ 中解释转义的 unicode 字符

    java - 构建 gradle 插件

    html - Groovy MarkupBuilder - 不产生原始文本