如何从java类调用python方法?

Has*_*sti 8 python java methods jython

我在Java项目中使用Jython.

我有一个Java类:myJavaClass.java和一个Python类:myPythonClass.py

public class myJavaClass{
    public String myMethod() {
        PythonInterpreter interpreter = new PythonInterpreter();
        //Code to write
    }
 }
Run Code Online (Sandbox Code Playgroud)

Python文件如下:

class myPythonClass:
    def abc(self):
        print "calling abc"
        tmpb = {}
        tmpb = {'status' : 'SUCCESS'}
        return tmpb
Run Code Online (Sandbox Code Playgroud)

现在问题是我想abc()myMethod我的Java文件的方法调用我的Python文件的方法并打印结果.

Nik*_* B. 13

如果我正确阅读文档,您可以使用该eval功能:

interpreter.execfile("/path/to/python_file.py");
PyDictionary result = interpreter.eval("myPythonClass().abc()");
Run Code Online (Sandbox Code Playgroud)

或者如果你想得到一个字符串:

PyObject str = interpreter.eval("repr(myPythonClass().abc())");
System.out.println(str.toString());
Run Code Online (Sandbox Code Playgroud)

如果你想从Java变量中提供一些输入,你可以set事先使用,而不是在Python代码中使用那个变量名:

interpreter.set("myvariable", Integer(21));
PyObject answer = interpreter.eval("'the answer is: %s' % (2*myvariable)");
System.out.println(answer.toString());
Run Code Online (Sandbox Code Playgroud)