使用 GroovyShell 从 Java 代码编写 运行 脚本

Use GroovyShell to run scripts from Java code

我编写项目,与 Groovy 和 Java 一起工作。 我的项目中有这个 Groovy 脚本:

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

在我的 Main Java class 我这样写:

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();
    }
}

但我在这一行中有 NullPointerExceptionanswer = (int) shell.run(new File("src/Summary.groovy"), arguments); 那么,我想要什么?我想要 运行 Main class 并调用 groovy 脚本,其中包含 sum a + b 和 return 这个值到 Java 代码的功能。 我该怎么做才能正确? 更新: 来自 Main class:

的完整 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)

UPD2: 输出不正确: a:1 b:2 answer: 33 我使用这个脚本:

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

Main class 中的代码正确调用它,但回答不正确

你必须在你的脚本中调用一些东西 - 而不仅仅是提供一个函数。所以你的脚本看起来像:

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

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