Sören Bleikertz
03 Sep 2010

Calling Python functions from Java using Jython

If we want to call a function written in Python from Java, which takes
as input a Java object and returns another object, we can realize it
using the following snippet build on Jython.

ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");
engine.eval(new FileReader("foobar.py"));
Bindings bind = engine.getBindings(ScriptContext.ENGINE_SCOPE);

PyFunction func = (PyFunction) bind.get("func");
Foo foo = new Foo();
PyObject ret = func.__call__(Py.java2py(foo));
Bar bar = Py.tojava(ret, Bar.class);