Groovy 变量双重替换

Groovy variable double substitution

我想执行双重替换

打印时:

def y    = "${x}"
def x    = "world"
def z    = "Hello ${y}"
println z

它打印:

Hello ${x}

当我希望它打印 Hello World 时,我尝试执行双重评估 ${${}},将其转换为 org.codehaus.groovy.runtime.GStringImpl,然后绝望 ${y.toStrin()}

编辑:

更清楚地说,我是这个意思,但在 Groovy:

(我为什么要这样做?: 因为我们有一些文本文件需要用 groovy 个变量进行评估;变量很多并且在不同的部分代码不同,因此我希望有一个适用于所有情况的解决方案,而不是每次都绑定每个变量,而不是添加很多行代码)

因此,对于您所拥有的内容,您正在转义 $,因此它只是被解释为一个字符串。

对于你想要做的事情,我会研究 Groovys 的模板引擎: http://docs.groovy-lang.org/docs/next/html/documentation/template-engines.html

阅读您的评论后,我想出了一些想法并想出了这个人为的答案,这也可能不是您要找的东西:

import groovy.lang.GroovyShell

class test{
    String x = "world"
    String y = "${x}"
    void function(){
        GroovyShell shell = new GroovyShell();
        Closure c = shell.evaluate("""{->"Hello $y"}""")
        c.delegate = this
        c.resolveStrategry = Closure.DELEGATE_FIRST
        String z = c.call()
        println z
    }
}

new test().function()

但这是我能想到的最接近的东西,可能会引导你找到一些东西......

如果我没理解错的话,您是从其他地方阅读 y。因此,您想在 y 之后将 y 评估为 GString,然后 x 已加载。 groovy.util.Eval 将对简单的情况执行此操作。在这种情况下,您只有一个绑定变量:x.

def y = '${x}'
def x = 'world'

def script = "Hello ${y}"
def z = Eval.me('x', x, '"' + script + '".toString()') // create a new GString expression from the string value of "script" and evaluate it to interpolate the value of "x"
println z