加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

string – Groovy:${}内变量的嵌套计算

发布时间:2020-12-14 16:28:17 所属栏目:大数据 来源:网络整理
导读:我有办法在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 fig
我有办法在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成为一个实际的地图,而不是一个闭包,和
>对字段名称使用法线贴图[]访问

def obj = [ "name": "Whatever","street": "ABC-Street","zip": "22222" ]
def fieldNames = ["name","zip"]

fieldNames.each { println "Gimme the value ${obj[it]}" }

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

编辑我可能误解了你并且故意让obj成为闭包而不是地图,尽管我不明白为什么.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读