evaluating a groovy string expression at runtime

自古美人都是妖i 提交于 2019-12-23 22:50:58

问题


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")

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

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

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

Thanks for any thoughts….


回答1:


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>

output

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

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




回答2:


You can also use the following code:

def value = element.getAttribute("value")
Binding binding = new Binding()
binding.setVariable("valueExpression", "\"$value\"")
binding.setVariable("a", 10)
binding.setVariable("b", 20)
def interpolatedValue = new GroovyShell(binding).evaluate(
    "return evaluate(valueExpression)")
println ("interpolated Value = $interpolatedValue")

I'm testing the code above using the following element:

The time is ${new Date()} and $a + $b is ${a+b}

The result is:

interpolated value = The time is Wed Feb 26 10:00:00 2014 and 10 + 20 is 30


来源:https://stackoverflow.com/questions/22032263/evaluating-a-groovy-string-expression-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!