我編寫項目,在那裏使用Groovy和Java。 我有這樣的Groovy腳本在我的項目:使用GroovyShell從Java代碼運行腳本
int sum(def a, def b) {
return (int)a + (int)b;
}
在我的主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代碼。 我該怎麼做纔對? UPD: 完整堆棧跟蹤從主類:
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())
和代碼的主類調用正確,但答案不正確
如果你把完整的堆棧跟蹤放在一起,它會容易得多......它將使我們能夠找出哪一部分在行中爲'null'... – Codebender
@Codebender我從Main類放置堆棧跟蹤,我的項目 – Giymose
@Giymose,所以現在調查第140行。 – Opal