使用GroovyShell作为"表达式计算器/引擎"(或:如何重用GroovyShell)

wir*_*uma 9 groovy groovyshell

GroovyShell在我的程序中使用"表达式评估器/引擎".它接受两个输入:(a)一个或多个init脚本(b)用户定义的脚本.然后两者在运行时连接成大块脚本(文本)并提供给shell.

String initScripts = getFromDB()
String userScript = getFromUser()

def shell = new GroovyShell()
output = shell.evaluate(initScripts + userScript)
Run Code Online (Sandbox Code Playgroud)

上面的代码将在循环中运行,其中的内容userScript将有所不同.

到目前为止,initScripts仅包含def $yyyy = new Date().format('yyyy')可能在userScript(例如print "$yyyy 001")中引用的变量定义(例如).

有没有更有效的方法呢?(例如重用shell,怎么样?)因为现在它非常慢.

编辑: Groovy是必须的.请不要推荐其他脚本引擎.

编辑:我在想GroovyShell是否可以这样做(伪代码):

def shell = new GroovyShell()
shell.evaluate(initScripts)

for each userScript in DB {
    shell.put(userScript )
    def result = shell.evaluateThat()
    println "Result is $result"
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?(上次我用谷歌搜索它是不可能的,但我希望我错了)

Ada*_*dam 7

您可以缓存GroovyShell,您不需要总是创建一个新的:

final static GroovyShell shell = new GroovyShell()
Run Code Online (Sandbox Code Playgroud)

此外,如果您多次运行一个脚本,也可以缓存它们.您可以Script使用GroovyShell.parse(String scriptText)创建一个,使用Script.run()来运行脚本.

文档的这一部分也可能有所帮助,您也可以动态创建groovy对象,而不是脚本.

  • GroovyShell 是无状态和线程安全的吗?有些人可以同时使用不同的脚本来使用该程序(这是肯定的,因为`userScript` 可能因用户而异,甚至每次调用都不同)。 (2认同)