java - 使用 GroovyShell 从 Java 代码运行脚本

标签 java groovy

我编写项目,在其中使用 Groovy 和 Java。 我的项目中有这个 Groovy 脚本:

int sum(def a, def b) {
return (int)a + (int)b;
}

在我的 Main Java 类中我这样写:

public static void main(String[] args) {
    int answer = 0;
    String[] arguments = new String[]{"1", "2"};
    GroovyShell shell = new GroovyShell();
    try {
        answer = (int) shell.run(new File("src/Summary.groovy"), arguments);
        System.out.print(answer);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

但是我在这一行中有NullPointerException:answer = (int) shell.run(new File("src/Summary.groovy"),arguments); 那么,我想要什么?我想运行 Main 类并调用 groovy 脚本,其中包含 sum a + b 函数并将该值返回给 Java 代码。 我怎样才能做到正确呢? 更新: 主类的完整 stackTrace:

Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

更新2: 不正确的输出: a:1 b:2 答案:33 我使用这个脚本:

def sum (int a, int b) {
print("a:" + a + " b:" + b + "\n")
return a + b
}
return sum (args[0].toInteger(), args[1].toInteger())

主类中的代码正确调用它,但答案不正确

最佳答案

您必须在脚本中调用某些内容 - 而不仅仅是提供一个函数。所以你的脚本可能如下所示:

int sum(def a, def b) {
   return ((int)a) + ((int)b)
}
return sum (args[0], args[1])

仍然将字符串转换为 int 看起来真的很奇怪 - 也许您想将字符串解析为 int 或其他东西(例如 "1".toInteger()a.toInteger() 就像你的情况一样)。

关于java - 使用 GroovyShell 从 Java 代码运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31198993/

相关文章:

java - 适用于套接字流的C++/Java序列化库?

java - 启动 3d 派对应用程序后崩溃,该应用程序崩溃后

grails - Canoo 和 Groovy - 如何使用 storeRegEx

maven - 创建具有依赖项的独立 Groovy 脚本

java - 我可以避免使用 Grape 在 Groovy 中加载模块吗?

json - HTTPBuilder 设置请求内容类型

java while循环 try catch ,无法打印到新行

java - 我正在使用 struts 框架,当我按下浏览器后退按钮时注销后,它将返回最后打开的页面。如何将其发送到登录页面?

java - 检查有效 session : isRequestedSessionIdValid() vs getSession(false)

jenkins - 仅在主节点上 checkout 和运行 SCM 管道