8

jythonを使用すると、JavaのクラスファイルからJavaメソッドをPython用に記述されているかのように呼び出すことができますが、その逆は可能ですか???

私はすでに Python で書かれた非常に多くのアルゴリズムを持っています。それらは Python と jython でうまく動作しますが、適切な GUI がありません。GUI を Java に組み込み、Python ライブラリをそのまま維持する予定です。jython または python で適切な GUI を作成することができず、python で適切なアルゴリズムを作成することもできません。だから私が見つけた解決策は、JavaのGUIとPythonのライブラリをマージすることでした。これは可能ですか?Java から Python のライブラリを呼び出すことはできますか。

4

1 に答える 1

22

はい、できます。通常、これはPythonInterpreter オブジェクトを作成し、それを使用して python クラスを呼び出すことによって行われます。

次の例を考えてみましょう:

ジャワ:

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");  
   }  
} 

パイソン:

class Hello:  
    __gui = None  

    def __init__(self, gui):  
        self.__gui = gui  

    def run(self):  
        print 'Hello world!'
于 2013-05-09T11:53:04.490 に答える