我编写项目,在其中使用 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/