我有一个表达式如:
def expr = 'anything="something"'
在我的情况下,上面的字符串来自Web服务,但它可以来自任何地方。我想评估这个,以便我最终得到变量"任何"它的值为"某些",这样:
assert anything=="something"
到目前为止,我试过了:
def anything
Eval.me(expr) // `anything` ends up null
我从SO上读到的东西:
def anything
Eval.me(expr.inspect()) // same thing: `anything` ends up null
也尝试过:
def anything
expr.execute() // complains: "Executable name has embedded quote, split the arguments"
可以这样做吗?
答案 0 :(得分:5)
您可以使用GroovyShell,看看:
def expr = 'anything = "something"'
def binding = new Binding()
def groovyShell = new GroovyShell(binding)
groovyShell.evaluate(expr)
assert binding.getVariable('anything') == "something"