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

标签 java groovy command-line-interface groovyshell

我本质上是想用 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/

相关文章:

java - 使用 iv/pass/salt/iterations 进行 AES 加密

groovy - 将方法添加到闭包

mysql - 如何使用命令行将 SQL 查询导出到 TXT

java - Spring mvc portlet : how to get data from jsp?

java - 如何在 Camel route 使用上下文路径?

java - 使用 Spock 进行测试 - 使用复杂的数据提供程序

包含反斜杠的 Java 命令行参数

linux - 有没有办法在 Linux 中继续损坏的 scp(安全复制)命令进程?

java - 如何从 kotlin 访问枚举的 "overridden"name() 方法?

java - 如何在android中实现一个按钮onclick的两个功能