Embedding a Python Interpreter in Java – Jython

So here is the other half of the code – the Java test end
(Note Test Class in this case is a simple Java class with a property (string) Value)
(The real case would not use propertis due to the access differences between .net and Java – the script needs to be consistent over each environment in the real case):

import org.python.util.PythonInterpreter;
import org.python.core.PySystemState;
import org.python.core.PyObject;
import org.python.core.Py;

public class Prog {

  public static void main( String[] args)
  {
    try{
      PySystemState.initialize();
      PythonInterpreter interp = new PythonInterpreter();

//this is the python program as a string
//miss the package (from JythonTest) and it works up till
//casting it back to a JavaClass -> __tojava__ fails....
      interp.exec("from JythonTest import TestClass\n" +
                  "\n" +
                  "def MakeOne():\n" +
                  " return TestClass()\n" +
                  "\n" +
                  "def Update(item):\n" +
                  " item.setValue( \"Hello World\")"
      );

      PyObject makeOne = interp.get("MakeOne");
      PyObject update = interp.get("Update");

//this calls the python function MakeOne 
//declared in the python code
//where TestClass is a Java class

      PyObject jc = makeOne.__call__();
      update.__call__(jc);

      TestClass jjc = (TestClass)jc.__tojava__(TestClass.class);

      System.out.println(jjc.getValue());

    } catch(Exception ex){ ex.printStackTrace();}

  }

}
This entry was posted in Python and tagged , , , . Bookmark the permalink.

Leave a Reply