Calling jython script from java

眉间皱痕 提交于 2021-02-08 06:35:45

问题


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?


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



来源:https://stackoverflow.com/questions/43179109/calling-jython-script-from-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!