Calling Java from Python Calling Java from Python python python

Calling Java from Python


You could also use Py4J. There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods:

from py4j.java_gateway import JavaGatewaygateway = JavaGateway()                        # connect to the JVMjava_object = gateway.jvm.mypackage.MyClass()  # invoke constructorother_object = java_object.doThat()other_object.doThis(1,'abc')gateway.jvm.java.lang.System.out.println('Hello World!') # call a static method

As opposed to Jython, one part of Py4J runs in the Python VM so it is always "up to date" with the latest version of Python and you can use libraries that do not run well on Jython (e.g., lxml). The other part runs in the Java VM you want to call.

The communication is done through sockets instead of JNI and Py4J has its own protocol (to optimize certain cases, to manage memory, etc.)

Disclaimer: I am the author of Py4J


Here is my summary of this problem: 5 Ways of Calling Java from Python

http://baojie.org/blog/2014/06/16/call-java-from-python/ (cached)

Short answer: Jpype works pretty well and is proven in many projects (such as python-boilerpipe), but Pyjnius is faster and simpler than JPype

I have tried Pyjnius/Jnius, JCC, javabridge, Jpype and Py4j.

Py4j is a bit hard to use, as you need to start a gateway, adding another layer of fragility.


Pyjnius docs and Github.

From the github page:

A Python module to access Java classes as Python classes using JNI.

PyJNIus is a "Work In Progress".

Quick overview

>>> from jnius import autoclass>>> autoclass('java.lang.System').out.println('Hello world') Hello world>>> Stack = autoclass('java.util.Stack')>>> stack = Stack()>>> stack.push('hello')>>> stack.push('world')>>> print stack.pop()world>>> print stack.pop()hello