如何评估脚本中的Groovy字符串?

时间:2014-09-14 21:34:32

标签: java groovy command-line-interface groovyshell

我实际上是在尝试使用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!';");

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);

我认为有一种方法可以做到这一点,就在那里......现在每当我需要从文本框中评估一个脚本时,我就可以对它进行评估并在基本脚本的上下文中对其进行评估