I am currently working on a simple hello world program using jython and java.
The program is designed in way that a jython method accepts a name parameter and returns welcome message.
My problem is whenever I am accessing the jython method from java, it shows nullponter exception
My jython Script (JythonHello.py):
class JythonHello:
def __init__(self, name):
self.name = name
def sayHello(self):
return "Hello "+ self.name
and my java code:
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("src/jython/JythonHello.py");
PyObject callFunction = interpreter.get("sayHello");
PyObject result = callFunction.__call__(new PyString("Boban"));
String msg = (String) result.__tojava__(String.class);
System.out.println("output: " + msg);
}
Any suggestions?
-
Yes. Add the exception stack trace. And just for the record: you are sure that "src/...." is a valid path from where you call your java main?GhostCat– GhostCat2017年04月03日 07:45:29 +00:00Commented Apr 3, 2017 at 7:45
-
it shows only java.lang.NullPointerException. I am not sure about the path.Is there any other way of loading script file?Boban Thomas– Boban Thomas2017年04月03日 07:52:12 +00:00Commented Apr 3, 2017 at 7:52
-
But fore sure there are line numbers, method names?!GhostCat– GhostCat2017年04月03日 07:52:43 +00:00Commented Apr 3, 2017 at 7:52
-
java.lang.NullPointerException at javaSide.JavaClass.main(JavaClass.java:16)Boban Thomas– Boban Thomas2017年04月03日 07:53:56 +00:00Commented Apr 3, 2017 at 7:53
-
error in PyObject result = callFunction.__call__(new PyString("Boban"));Boban Thomas– Boban Thomas2017年04月03日 07:55:00 +00:00Commented Apr 3, 2017 at 7:55
1 Answer 1
Looking at your code; your python code defines a class and a member method:
class JythonHello:
def __init__(self, name): ...
def sayHello(self): ...
And it seems that you intend to call that method:
PyObject callFunction = interpreter.get("sayHello");
PyObject result = callFunction.__call__(new PyString("Boban"));
But please note: sayHello() doesn't take any arguments. That self parameter is an indication that you have to call it on an object; but without any other parameters!
So, in pure python you would say:
helloVar = JythonHello("Boban")
helloVar.sayHello()
But your java code tries to call it like
sayHello("Boban")
So, the real answer is: step back; and re-think what you really intend to do; and then write code that works that way.
I would start by not adding the "class" part on the python side; instead try to simply invoke a function that takes a string argument for example!
And finally: could it be that you are on the wrong path altogether? The main point of jython is to write simply python code to do "debug" work within a running JVM. You are writing complicated Java code to use a bit of python code on the other hand ...