I write project, where I work with Groovy and Java. I have this Groovy script in my project:
int sum(def a, def b) {
return (int)a + (int)b;
}
And in my Main Java class I write this:
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();
}
}
But I have NullPointerException in this line: answer = (int) shell.run(new File("src/Summary.groovy"), arguments);
So, what I want? I want run Main class and call groovy script, which contain function of sum a + b and return this value to Java code.
How can I do it correct?
UPD:
Full stackTrace from Main class:
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:
Incorrect output:
a:1 b:2 answer: 33
I use this script:
def sum (int a, int b) {
print("a:" + a + " b:" + b + "\n")
return a + b
}
return sum (args[0].toInteger(), args[1].toInteger())
And code from Main class correct call it, but answer incorrect
nullin the line...