首页 文章

Groovy GString变量双替换

提问于
浏览
0

我有一个Groovy脚本 . 在Java中通过Binding我提供:

binding.put( 'a','Hello')

我通过GroovyShell运行脚本,我做:

print "${a}"

将打印

Hello

我需要 print "${a}" ,其中 a 可以是调用另一个方法的任何文本 . 只需打印一个名称在运行时确定的变量 . 这怎么可能 ?

还有一个例子可以澄清:

binding.put( 'm','n')
binding.put( 'n','p')

打印????输出应为 'p' ,其中 'm' 在脚本中已知但不是 'n'

1 回答

  • 1

    像这样的东西会起作用:

    // Java code...
    
    Binding binding = new Binding();
    binding.setVariable("m", "n");
    binding.setVariable("n", "result");
    
    // here the script is hardcoded in this Java source
    // file but could be read from anywhere...
    String groovyScript = "evaluate \"println(${m})\"";
    
    GroovyShell shell = new GroovyShell(binding);
    
    // this will println "result"
    shell.evaluate(groovyScript);
    

    我希望有所帮助 .

相关问题