Top Related Projects
JPype is cross language bridge to allow Python programs full access to Java class libraries.
Quick Overview
PyJNIus is a Python library that enables seamless integration between Python and Java, allowing developers to call Java methods from Python code. It provides a bridge to access Java classes and objects, making it particularly useful for Android development with Python frameworks like Kivy.
Pros
- Enables Python developers to leverage Java libraries and Android APIs
- Simplifies cross-language development between Python and Java
- Supports both Python 2 and Python 3
- Actively maintained and part of the Kivy ecosystem
Cons
- Requires Java Development Kit (JDK) to be installed
- Performance overhead due to the Python-Java bridge
- Limited documentation and examples compared to native Java development
- May introduce complexity in debugging due to the interaction between two languages
Code Examples
- Basic Java class instantiation and method call:
from jnius import autoclass
# Load Java classes
String = autoclass('java.lang.String')
System = autoclass('java.lang.System')
# Create a Java string and print it
java_string = String("Hello from Java!")
System.out.println(java_string)
- Accessing Android APIs:
from jnius import autoclass
# Load Android classes
PythonActivity = autoclass('org.kivy.android.PythonActivity')
Toast = autoclass('android.widget.Toast')
Context = autoclass('android.content.Context')
# Show a toast message
def show_toast(message):
activity = PythonActivity.mActivity
toast = Toast.makeText(activity, message, Toast.LENGTH_SHORT)
toast.show()
show_toast("Hello from PyJNIus!")
- Working with Java collections:
from jnius import autoclass
# Load Java classes
ArrayList = autoclass('java.util.ArrayList')
Collections = autoclass('java.util.Collections')
# Create and manipulate a Java ArrayList
java_list = ArrayList()
java_list.add("Apple")
java_list.add("Banana")
java_list.add("Cherry")
Collections.sort(java_list)
print(java_list.toString())
Getting Started
-
Install PyJNIus:
pip install pyjnius
-
Ensure Java Development Kit (JDK) is installed and JAVA_HOME environment variable is set.
-
Import and use PyJNIus in your Python code:
from jnius import autoclass # Now you can start using Java classes String = autoclass('java.lang.String') hello = String("Hello, PyJNIus!") print(hello.toUpperCase())
Note: When using PyJNIus for Android development with Kivy, additional setup may be required. Refer to the Kivy for Android documentation for more details.
Competitor Comparisons
JPype is cross language bridge to allow Python programs full access to Java class libraries.
Pros of JPype
- More mature and widely used project with a larger community
- Supports a broader range of Java features and libraries
- Better documentation and examples available
Cons of JPype
- Slower startup time due to JVM initialization
- More complex setup process, especially on Windows
- Larger memory footprint
Code Comparison
JPype:
import jpype
jpype.startJVM()
java_string = jpype.java.lang.String("Hello, World!")
print(java_string.toUpperCase())
jpype.shutdownJVM()
PyJNIus:
from jnius import autoclass
String = autoclass('java.lang.String')
java_string = String("Hello, World!")
print(java_string.toUpperCase())
Key Differences
- JPype requires explicit JVM startup and shutdown
- PyJNIus uses a simpler import and class instantiation approach
- JPype offers more flexibility in JVM configuration
- PyJNIus is more lightweight and easier to set up, especially for simple use cases
Both libraries aim to provide Python-Java interoperability, but JPype offers more comprehensive Java integration at the cost of increased complexity and resource usage. PyJNIus, on the other hand, provides a simpler and more lightweight solution that may be sufficient for many projects, particularly those already using Kivy.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
PyJNIus
PyJNIus is a Python library for accessing Java classes using the Java Native Interface (JNI).
PyJNIus is managed by the Kivy Team and can be used with python-for-android.
It can also be used independently of Kivy, on desktop and mobile platforms.
[!WARNING] The PyPI package name is now pyjnius instead of
jnius
.
Installation
pip install pyjnius
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
Usage with python-for-android
- Get python-for-android
- Compile a distribution with kivy (PyJNIus will be automatically added)
Then, you can do this kind of thing:
from time import sleep
from jnius import autoclass
Hardware = autoclass('org.renpy.android.Hardware')
print('DPI is', Hardware.getDPI())
Hardware.accelerometerEnable(True)
for x in range(20):
print(Hardware.accelerometerReading())
sleep(0.1)
It will output something like:
I/python ( 5983): Android kivy bootstrap done. __name__ is __main__
I/python ( 5983): Run user program, change dir and execute main.py
I/python ( 5983): DPI is 160
I/python ( 5983): [0.0, 0.0, 0.0]
I/python ( 5983): [-0.0095768067985773087, 9.3852710723876953, 2.2218191623687744]
I/python ( 5983): [-0.0095768067985773087, 9.3948478698730469, 2.2218191623687744]
I/python ( 5983): [-0.0095768067985773087, 9.3948478698730469, 2.2026655673980713]
I/python ( 5983): [-0.028730420395731926, 9.4044246673583984, 2.2122423648834229]
I/python ( 5983): [-0.019153613597154617, 9.3852710723876953, 2.2026655673980713]
I/python ( 5983): [-0.028730420395731926, 9.3852710723876953, 2.2122423648834229]
I/python ( 5983): [-0.0095768067985773087, 9.3852710723876953, 2.1835119724273682]
I/python ( 5983): [-0.0095768067985773087, 9.3756942749023438, 2.1835119724273682]
I/python ( 5983): [0.019153613597154617, 9.3948478698730469, 2.2122423648834229]
I/python ( 5983): [0.038307227194309235, 9.3852710723876953, 2.2218191623687744]
I/python ( 5983): [-0.028730420395731926, 9.3948478698730469, 2.2026655673980713]
I/python ( 5983): [-0.028730420395731926, 9.3852710723876953, 2.2122423648834229]
I/python ( 5983): [-0.038307227194309235, 9.3756942749023438, 2.2026655673980713]
I/python ( 5983): [0.3926490843296051, 9.3086557388305664, 1.3311761617660522]
I/python ( 5983): [-0.10534487664699554, 9.4331550598144531, 2.1068975925445557]
I/python ( 5983): [0.26815059781074524, 9.3469638824462891, 2.3463177680969238]
I/python ( 5983): [-0.1149216815829277, 9.3852710723876953, 2.31758713722229]
I/python ( 5983): [-0.038307227194309235, 9.41400146484375, 1.8674772977828979]
I/python ( 5983): [0.13407529890537262, 9.4235782623291016, 2.2026655673980713]
Advanced example
When you use autoclass
, it will discover all the methods and fields of the
class and resolve them. You may want to declare and use only what you
need. The previous example can be done manually as follows:
from time import sleep
from jnius import MetaJavaClass, JavaClass, JavaMethod, JavaStaticMethod
class Hardware(JavaClass):
__metaclass__ = MetaJavaClass
__javaclass__ = 'org/renpy/android/Hardware'
vibrate = JavaStaticMethod('(D)V')
accelerometerEnable = JavaStaticMethod('(Z)V')
accelerometerReading = JavaStaticMethod('()[F')
getDPI = JavaStaticMethod('()I')
# use that new class!
print('DPI is', Hardware.getDPI())
Hardware.accelerometerEnable()
for x in range(20):
print(Hardware.accelerometerReading())
sleep(0.1)
You can use the signatures
method of JavaMethod
and JavaMultipleMethod
, to inspect the discovered signatures of a method of an object
>>> String = autoclass('java.lang.String')
>>> dir(String)
['CASE_INSENSITIVE_ORDER', '__class__', '_JavaClass__cls_storage', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__javaclass__', '__javaconstructor__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__pyx_vtable__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'charAt', 'checkBounds', 'clone', 'codePointAt', 'codePointBefore', 'codePointCount', 'compareTo', 'compareToIgnoreCase', 'concat', 'contains', 'contentEquals', 'copyValueOf', 'empty', 'endsWith', 'equals', 'equalsIgnoreCase', 'finalize', 'format', 'getBytes', 'getChars', 'getClass', 'hashCode', 'indexOf', 'indexOfSupplementary', 'intern', 'isEmpty', 'join', 'lastIndexOf', 'lastIndexOfSupplementary', 'length', 'matches', 'nonSyncContentEquals', 'notify', 'notifyAll', 'offsetByCodePoints', 'regionMatches', 'registerNatives', 'replace', 'replaceAll', 'replaceFirst', 'split', 'startsWith', 'subSequence', 'substring', 'toCharArray', 'toLowerCase', 'toString', 'toUpperCase', 'trim', 'valueOf', 'wait']
>>> String.format.signatures()
[(['java/util/Locale', 'java/lang/String', 'java/lang/Object...'], 'java/lang/String'), (['java/lang/String', 'java/lang/Object...'], 'java/lang/String')]
Each pair contains the list of accepted arguments types, and the returned type.
Troubleshooting
Make sure a Java Development Kit (JDK) is installed on your operating system if you want to use PyJNIus on desktop. OpenJDK is known to work, and the Oracle Java JDK should work as well.
On Windows, make sure JAVA_HOME
points to your Java installation, so PyJNIus
can locate the jvm.dll
file allowing it to start Java. This shouldn't be
necessary on macOS and Linux, but in case PyJNIus fails to find it, setting
JAVA_HOME
should help.
License
PyJNIus is MIT licensed, actively developed by a great community and is supported by many projects managed by the Kivy Organization.
Documentation
Documentation for this repository.
Support
Are you having trouble using PyJNIus or any of its related projects in the Kivy ecosystem? Is there an error you donât understand? Are you trying to figure out how to use it? We have volunteers who can help!
The best channels to contact us for support are listed in the latest Contact Us document.
Contributing
PyJNIus is part of the Kivy ecosystem - a large group of products used by many thousands of developers for free, but it is built entirely by the contributions of volunteers. We welcome (and rely on) users who want to give back to the community by contributing to the project.
Contributions can come in many forms. See the latest Contribution Guidelines for how you can help us.
Code of Conduct
In the interest of fostering an open and welcoming community, we as contributors and maintainers need to ensure participation in our project and our sister projects is a harassment-free and positive experience for everyone. It is vital that all interaction is conducted in a manner conveying respect, open-mindedness and gratitude.
Please consult the latest Code of Conduct.
Contributors
This project exists thanks to all the people who contribute. [Become a contributor].
Backers
Thank you to all of our backers! ð [Become a backer]
Sponsors
Special thanks to all of our sponsors, past and present. Support this project by [becoming a sponsor].
Here are our top current sponsors. Please click through to see their websites, and support them as they support us.
Top Related Projects
JPype is cross language bridge to allow Python programs full access to Java class libraries.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot