我知道jython允许我们从任何java的类文件中调用java方法,就像它们是为python编写的那样,但是反过来可能吗???
我已经有很多用python编写的算法,它们在python和jython中工作得很好但是它们缺少一个合适的GUI。我计划将GUI与java一起使用并保持python库的完整性。我无法用jython或python编写一个好的GUI,我不能用python编写一个好的算法。所以我找到的解决方案是合并java的GUI和python的库。这可能吗。我可以从java调用python的库吗?
答案 0 :(得分:17)
是的,可以做到。通常,这将通过创建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!'
答案 1 :(得分:1)
您可以使用Jython从Java代码轻松调用python函数。只要您的python代码本身在jython下运行,即不使用某些不受支持的c扩展名。
如果这对你有用,那肯定是你能得到的最简单的解决方案。否则,您可以使用新Java6解释器支持中的org.python.util.PythonInterpreter。
一个简单的例子来自我的头脑 - 但我应该工作:(没有为简洁而做错误检查)
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('pathToModiles if they're not there by default')\nimport yourModule");
// execute a function that takes a string and returns a string
PyObject someFunc = interpreter.get("funcName");
PyObject result = someFunc.__call__(new PyString("Test!"));
String realResult = (String) result.__tojava__(String.class);