本文介绍了Groovy:$ {}中变量的嵌套求值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种方法可以对Groovy中的"$ -Strings"进行嵌套评估,例如

I there a way to do nested evaluation of "$-Strings" in Groovy like, e.g.

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我相信这是有可能的.

My attempts to solve this either don't give proper results (e.g. just obj.street} or won't compile at all.I simply haven't understood the whole concept so far it seems. However, seeing this: http://groovy.codehaus.org/Strings+and+GString I believe it should be possible.

推荐答案

该页面如何使您认为有可能?没有任何嵌套的示例.

What about that page makes you think it'd be possible? There aren't any nested examples.

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

AFAIK it's not possible by default; expressions within ${} aren't re-evaluated. Which would be dangerous anyway since it'd be really easy to make it infinitely-deep and blow the stack.

在这种情况下,还是没有必要的.

In this case, it's not necessary anyway.

  • obj设为实际地图,而不是闭包,并且
  • 在字段名称上使用法线贴图[]访问权限
  • Make obj be an actual map, not a closure, and
  • Use normal map [] access on the field name
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设为闭包而不是地图,尽管我不明白为什么.

Edit It's possible I misunderstood and you're deliberately making obj a closure instead of a map, although I don't understand why.

这篇关于Groovy:$ {}中变量的嵌套求值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 08:28
查看更多