2

我实际上是在尝试使用 Groovy 创建一个 CLI。我在 Java 中设置了一个完整的 JavaFX GUI,我希望能够输入 groovy 脚本以在 groovy 脚本中运行不同的功能。

例如,假设我有这个脚本:

void meow() {
    println "walrus"
}

我希望能够输入“meow();” 并按回车键并使用脚本作为参考对其进行评估。

我试过使用

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!';");

但我就是无法运行自己的方法......如何解决?

4

2 回答 2

2

以下对我有用。

evaluate(new File("/Users/jellin/meow.groovy"))

我确实更改了 meow.groovy 文件以执行文件中的方法。

void meow() {
    println "walrus"
}

meow()

一个问题是我看不到将参数传递给调用脚本的方法。

我之前使用过以下,您可以将参数作为绑定的一部分传递。

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

于 2014-09-15T19:31:09.913 回答
0

谢谢你们的时间;经过一番搜索(总是在发布问题后我在研究中找到答案>,<),我发现您可以为 GroovyShell 设置一个基类......我是这样做的:

ClassLoader parent = getClass().getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);
loader.addClasspath("src/ScriptLoc/");
binding = new Binding();
CompilerConfiguration compConfig = new CompilerConfiguration();
compConfig.setScriptBaseClass("ScriptName");

shell = new GroovyShell(loader, binding, compConfig);

我认为有一种方法可以做到这一点,它就是……现在,每当我需要从文本框中评估脚本时,我就可以评估它,它会在基本脚本的上下文中评估它。

于 2014-09-15T19:35:39.383 回答