java - Groovy GString 变量双重替换

标签 java templates groovy gstring

我有一个 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/

相关文章:

java - 无法在 Groovy gradle 项目中找到或加载主类

bash - Jenkinsfile 添加 if else 脚本?

java - 有帮助组织我的类(class)吗?

java - runtime.exec() 花费无限时间来执行代码

Java Spring Boot - JPA : StackOverflowError with a @ManyToMany relation

c++ - 类型推导模板函数返回类型

c++ - 无操作函数模板

java - System.java :-2:in `arraycopy' : java. lang.ArrayIndexOutOfBoundsException

vue.js - 如何配置 Gridsome 以使用 API 将数据插入静态站点模板生成数千个产品页面?

grails - 如何保存方法以备后用,将其 stub 一段时间?