我有一个 Groovy 脚本。在 Java 中,我通过 Binding 提供:
binding.put( 'a','Hello')
我通过 GroovyShell 运行脚本,结果是:
print "${a}"
将打印
Hello
我需要打印“${a}”
,其中a
可以是调用另一个方法的结果的任何文本。
只需打印一个名称在运行时确定的变量。这怎么可能?
再举一个例子来说明:
binding.put( 'm','n')
binding.put( 'n','p')
打印???输出应为 'p'
,其中 'm'
在脚本中已知,但 'n'
最佳答案
像这样的东西会起作用:
// 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);
希望对您有所帮助。
关于java - Groovy GString 变量双重替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24885385/