在运行时评估groovy字符串表达式 [英] evaluating a groovy string expression at runtime

查看:315
本文介绍了在运行时评估groovy字符串表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下代码(无效):

If I have code such as (which doesn’t work):

def value = element.getAttribute("value")
Binding binding = new Binding();
binding.setVariable("valueExpression", value);
def interpolatedValue = new GroovyShell(binding).evaluate("return valueExpression")
println ("interpolated Value = $interpolatedValue")

,并且xml属性中的值为时间为$ {new Date()}"

and the value from the xml attribute is "The time is ${new Date()}"

如何让Groovy在运行时评估此表达式?

how do I get Groovy to evaluate this expression at runtime?

使用上面的代码,我得到的是时间是$ {(new Date()}"),而不是求值结果….

Using the above code I get "The time is ${(new Date()}" instead of an evaluation….

感谢您的任何想法…….

Thanks for any thoughts….

推荐答案

嗯.首先,我以Michael的身份尝试过使用内联xml.但是看来,时髦可以正确地将它们视为GString.

Hmm. Firstly I have tried, as Michael, using inline xml. But It's seems, that groovy can properly treat them as GString.

因此,我设法通过另一种方式使事情工作:模板

So, I have managed make things to work using another way: Templates

def xml = new XmlSlurper().parse("test.xml")
def engine = new groovy.text.SimpleTemplateEngine()
def value = xml.em."@value".each { // iterate over attributes
    println(engine.createTemplate(it.text()).make().toString())
}

test.xml

<root>
    <em value="5"></em>
    <em value='"5"'></em>
    <em value='${new Date()}'></em>
    <em value='${ 5 + 4 }'></em>
</root>

输出

5
"5"
Wed Feb 26 23:01:02 MSK 2014
9

对于纯Groovy shell解决方案,我认为我们可以将表达式包装在其他"中,但是我还没有任何解决方案.

For pure Groovy shell solution, I think we can wrap expression in additional ", but I haven't get any solution yet.

这篇关于在运行时评估groovy字符串表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆