将GroovyShell用作“表达评估器/引擎",(或:如何重用GroovyShell) [英] Using GroovyShell as "expression evaluator/engine" (or: How to reuse GroovyShell)

查看:52
本文介绍了将GroovyShell用作“表达评估器/引擎",(或:如何重用GroovyShell)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 GroovyShell 用作程序中的表达式评估器/引擎".它接受两个输入:(a)一个或多个初始化脚本(b)用户定义的脚本.然后,两者都在运行时串联为一大段脚本(文本),并馈入外壳.

I'm using GroovyShell as an "expression evaluator/engine" inside my program. It accepts two inputs: (a) one or more init scripts (b) user-defined script. Both are then concatenated at runtime as big chunk of script (text) and feed to the shell.

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

def shell = new GroovyShell()
output = shell.evaluate(initScripts + userScript)

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

The above code will run in a loop, where the contents of userScript will vary.

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

So far, initScripts only contain variable definitions (e.g. def $yyyy = new Date().format('yyyy')) which might be referenced in userScript (e.g. print "$yyyy 001").

有没有更有效的方法呢?(例如,重用外壳,如何?)因为现在非常很慢.

Is there any more efficient approach for this? (E.g. reusing the shell, how?) Because right now it's very slow.

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

Groovy is a must. Please don't recommend other scripting engine.

我在考虑GroovyShell是否可以做到这一点(伪代码):

I'm thinking whether GroovyShell can do this (pseudo-code):

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

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

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

Is this possible? (Last time I googled it's not possible, but I'm hoping I'm wrong)

推荐答案

您可以缓存GroovyShell,而不必始终创建一个新对象:

You can cache the GroovyShell, you don't need to create a new one always:

final static GroovyShell shell = new GroovyShell()

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

Also if you run one Script many times you may cache them too. You can create a Script with GroovyShell.parse(String scriptText), use Script.run() to run the script.

本节可能也有帮助,除了脚本之外,您还可以创建groovy对象动态地

This section of the documentation might help too, instead of scripts you can also create groovy objects dynamically.

这篇关于将GroovyShell用作“表达评估器/引擎",(或:如何重用GroovyShell)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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