我本质上是想用 Groovy 创建一个 CLI。我在 Java 中设置了整个 JavaFX GUI,我希望能够输入 groovy 脚本以在 groovy 脚本内运行不同的函数。
例如,假设我有这个脚本:
void meow() {
println "walrus"
}
我希望能够输入“meow();”然后按 Enter 并使用脚本作为引用对其进行评估。
我尝试过使用
shell.evaluate(inputStr, "src/Server/Scripting/CommandLineScript.groovy");
但无济于事;它只是出现错误:
groovy.lang.MissingMethodException: No signature of method: CommandLineScript.meow() is applicable for argument types: () values: []
我可以调用其他标准函数,例如:
shell.evaluate("println 'Hello World!';");
但我无法运行我自己的方法...如何解决?
最佳答案
以下内容对我有用。
evaluate(new File("/Users/jellin/meow.groovy"))
我确实更改了 meow.groovy 文件以执行文件中的方法。
void meow() {
println "walrus"
}
meow()
一个问题是我没有找到将参数传递给调用脚本的方法。
我之前使用过以下内容,您可以将参数作为绑定(bind)的一部分传递。
String script = "full path to the script"
GroovyScriptEngine gse = new GroovyScriptEngine()
Binding binding = new Binding();
Object result = gse.run(script, binding)
此外,您也许可以简单地将其他脚本作为类引用并对其执行 run 方法。
还有一个 AST 转换,可用于让脚本扩展基本脚本。
请参阅此处了解更多信息
http://mrhaki.blogspot.com/2014/05/groovy-goodness-basescript-with.html
关于java - 如何评估脚本中的 Groovy 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25838241/