【问题标题】:Groovy GString variable double substitutionGroovy GString 变量双重替换
【发布时间】:2014-07-22 10:52:06
【问题描述】:

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

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

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

print "${a}"

将打印

Hello

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

再举一个例子来说明:

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

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

【问题讨论】:

  • 我没有得到print ???? 部分。
  • 您有一个变量,其名称是在运行时确定的,并且在绑定中。但是绑定中可能有很多东西。你怎么知道要打印哪个变量?或者我搞错了……
  • ???意味着我想念构造。我以为我需要像“${${m}}”这样的东西,但这是不允许的。我知道'm',m正在绑定到n,n到p
  • 我不确定这是怎么回事,但例如在groovysh 中,您可以通过this 访问上下文。所以这适用于groovyshm='n'; n='p'; "${this."$m"}"

标签: java templates groovy gstring


【解决方案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);

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多