将GroovyShell用作“表达评估器/引擎",(或:如何重用GroovyShell)

编程入门 行业动态 更新时间:2024-10-09 12:35:11
本文介绍了将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)

本文发布于:2023-11-28 18:51:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643565.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:引擎   GroovyShell   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!