代码之家  ›  专栏  ›  技术社区  ›  GalloCedrone

groovy变量双替换

  •  0
  • GalloCedrone  · 技术社区  · 6 年前

    我想表演 双重替代 .

    印刷时:

    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变量计算的文本文件;变量很多,代码的不同部分也不同,所以我希望在所有情况下都有一个解决方案,不必每次都绑定一个变量,也不必添加多行代码)

    2 回复  |  直到 6 年前
        1
  •  1
  •   virtualdogbert    6 年前

    所以用你所拥有的东西,你在逃避美元,所以它被解释为一个字符串。

    对于您要做的,我将研究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()
    

    但这是我能想到的最接近的事情,可能会让你找到一些…

        2
  •  1
  •   emilles    6 年前

    如果我理解正确,你在读 y 从其他地方。所以你想评估一下 Y 在…之后 Y 然后 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