java jython 调用,从Java调用jython脚本

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值