当存储在字符串中时,如何让groovy计算${sth}?
我得到一个包含当存储在字符串中时,如何让groovy计算${sth}?,groovy,Groovy,我得到一个包含${somethingElse}的文本,但它只是一个普通字符串 我有一门课: class Whatever { def somethingElse = 5 void action(String sth) { def test = [] test.testing = sth assert test.testing == 5 } } groovy可以吗 编辑: 我的场景是:加载xml文件,其中包含的节点的值
${somethingElse}
的文本,但它只是一个普通字符串
我有一门课:
class Whatever {
def somethingElse = 5
void action(String sth) {
def test = []
test.testing = sth
assert test.testing == 5
}
}
groovy可以吗
编辑:
我的场景是:加载xml文件,其中包含的节点的值指向我的应用程序中的一些其他值。假设我得到了shell.setVariable(“current”,myClass)
。现在,在我的xml中,我希望能够将${current.someField}
作为一个值。
问题是,xml中的值是一个字符串,我无法轻松计算它。
我无法预测用户将如何创建这些“值”,我只是让他们能够使用几个类
当加载xml文件时,我无法转换它,它必须是“按需”的,因为我在特定情况下使用它,我希望他们能够在那个时刻使用值,而不是在加载xml文件时
有什么建议吗?你可以做的一件事是:
class Whatever {
def somethingElse = 5
void action( String sth ) {
def result = new groovy.text.GStringTemplateEngine().with {
createTemplate( sth ).make( this.properties ).toString()
}
assert result == "Number 5"
}
}
// Pass it a String
new Whatever().action( 'Number ${somethingElse}' )
首先,我们所做的是在xml中使用这种格式:
normalText#codeToExecuteOrEvaluate#normalText
并将replace
闭包用于regexp和groovyShell.evaluate()
代码。
疯了。这花了很多时间和很多记忆
最后,我们将格式更改为原始格式,并为我们希望能够评估的每个字符串包装脚本:
Script script = shell.parse("\""+stringToParse+"\"")
在哪里
然后,我们可以根据需要多次调用script.run(),一切都进行得很好。
实际上它仍然是这样。这看起来像是一个很大的开销!我们考虑过使用shell并只设置绑定,但这看起来也有些过分。是的,我能想到的另一种方法是使用
GroovyShell
并传递绑定
。。。我想这样做的好处是你可以更好地控制允许的输入<代码>Eval.XXX不起作用,因为您不知道将要请求的变量…:-(
stringToParse = "Hello world @ ${System.currentTimeMillis()}!!"