我知道 jython 允许我们从任何 java 的类文件中调用 java 方法,就好像它们是为 python 编写的一样,但是反过来可能吗???
我已经有很多用 python 编写的算法,它们在 python 和 jython 上工作得很好,但它们缺少合适的 GUI。我计划将 GUI 与 java 一起使用,并保持 python 库完好无损。我不能用 jython 或 python 编写一个好的 GUI,我不能用 python 编写一个好的算法。所以我找到的解决方案是合并 java 的 GUI 和 python 的库。这可能吗。我可以从 java 调用 python 的库吗?
是的,可以做到。通常,这将通过创建一个 PythonInterpreter
对象然后使用该对象调用 python 类来完成。
考虑以下示例:
Java:
import org.python.core.PyInstance;
import org.python.util.PythonInterpreter;
public class InterpreterExample
{
PythonInterpreter interpreter = null;
public InterpreterExample()
{
PythonInterpreter.initialize(System.getProperties(),
System.getProperties(), new String[0]);
this.interpreter = new PythonInterpreter();
}
void execfile( final String fileName )
{
this.interpreter.execfile(fileName);
}
PyInstance createClass( final String className, final String opts )
{
return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");
}
public static void main( String gargs[] )
{
InterpreterExample ie = new InterpreterExample();
ie.execfile("hello.py");
PyInstance hello = ie.createClass("Hello", "None");
hello.invoke("run");
}
}
python :
class Hello:
__gui = None
def __init__(self, gui):
self.__gui = gui
def run(self):
print 'Hello world!'