Pyjnius: Accessing Java classes from Python

We’re pleased to announce the Pyjnius project. It’s a Python library to access Java classes from Python, on the desktop or on Android.

We found others libraries such as JPype or Py4j, but we weren’t happy with the design and the usability. Using Jython wasn’t an option either, because we wanted to use the library within our python for android project.

Let me show you how simple it is to use Pyjnius:

>>> from jnius import autoclass
>>> Stack = autoclass('java.util.Stack')
>>> stack = Stack()
>>> stack.push('hello')
>>> stack.push('world')
>>> stack.pop()
>>> stack.pop()

What we demonstrate here is the autoclass function that create kind-of proxy that reflect all the methods and fields available from the Java class java.util.Stack.

Ok, maybe you want an Android-related example? Just have a look:

from jnius import autoclass
from time import sleep

MediaRecorder = autoclass('')
AudioSource = autoclass('$AudioSource')
OutputFormat = autoclass('$OutputFormat')
AudioEncoder = autoclass('$AudioEncoder')

# Record the Microphone with a 3GP recorder
mRecorder = MediaRecorder()

# Record 5 seconds

More examples are available in the documentation. We have a mapping between Java/Python type, native arrays, support for methods with multiple signatures, and a lot more. We are using Cython + JNI internally. The performance cost is minimal.

The library is already available for Python for android.

The library have been done by Gabriel Pettier and myself, under the Kivy organization.