简体   繁体   中英

Calling jython script from java

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?

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 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM