0

我有一个 Groovy 脚本。在 Java 中通过绑定我提供:

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

我通过 GroovyShell 运行脚本,然后:

print "${a}"

将打印

Hello

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

再举一个例子来说明:

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

打印 ????并且输出应该是'p''m'在脚本中已知但不是'n'

4

1 回答 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);

我希望这会有所帮助。

于 2014-07-22T18:34:49.577 回答