A Python module to access Java classes as Python classes using JNI.
npx @tessl/cli install tessl/pypi-pyjnius@1.6.0PyJNIus is a Python module that provides seamless access to Java classes as Python classes using the Java Native Interface (JNI). It enables Python applications to call Java methods, access Java fields, and create Java objects directly, supporting both automatic class discovery and manual class declaration patterns.
pip install pyjniusfrom jnius import autoclassFor manual class definitions:
from jnius import JavaClass, MetaJavaClass, JavaMethod, JavaStaticMethod, JavaField, JavaStaticField, PythonJavaClass, java_methodFor utility functions:
from jnius import cast, find_javaclass, detach, JavaException, HASHCODE_MAXFor signature helpers:
from jnius import signature, JArray, jint, jlong, jfloat, jdouble, jboolean, jbyte, jchar, jshort, jvoidFor JVM configuration (before importing jnius):
import jnius_configfrom jnius import autoclass
# Automatic class loading - easiest approach
String = autoclass('java.lang.String')
string_obj = String('Hello World')
print(string_obj.length()) # 11
# Java collections work with Python protocols
Stack = autoclass('java.util.Stack')
stack = Stack()
stack.push('hello')
stack.push('world')
print(len(stack)) # 2
print(stack.pop()) # world
# Access static methods and fields
System = autoclass('java.lang.System')
System.out.println('Hello from Java!')
print('Java version:', System.getProperty('java.version'))PyJNIus uses a multi-layered architecture for Java interoperability:
This design enables seamless integration between Python and Java applications, supporting complex scenarios like Android app development via python-for-android, enterprise Java integration, and cross-platform development.
Automatically discover and bind Java classes with full method and field access using runtime reflection. This is the recommended approach for most use cases.
def autoclass(clsname: str, include_protected: bool = True, include_private: bool = True) -> type:
"""
Create Python wrapper class for Java class with automatic member discovery.
Args:
clsname: Fully qualified Java class name (e.g., 'java.lang.String')
include_protected: Include protected methods and fields
include_private: Include private methods and fields
Returns:
Python class that wraps the Java class
"""
def ensureclass(clsname: str) -> None:
"""Ensure Java class is loaded and registered."""Define Python wrapper classes manually for precise control over exposed methods and fields. Includes support for creating Python classes that implement Java interfaces (proxies). Useful for performance optimization and custom behavior.
class JavaClass:
"""Base class for manual Java class wrappers."""
class MetaJavaClass(type):
"""Metaclass for Java class wrappers with member binding."""
def JavaMethod(signature: str, varargs: bool = False) -> callable:
"""Wrap Java instance method."""
def JavaStaticMethod(signature: str, varargs: bool = False) -> callable:
"""Wrap Java static method."""
def JavaField(signature: str) -> property:
"""Wrap Java instance field."""
def JavaStaticField(signature: str) -> property:
"""Wrap Java static field."""
def JavaMultipleMethod(signatures: list) -> callable:
"""Wrap overloaded Java methods."""
class PythonJavaClass:
"""Base class for creating Python classes that implement Java interfaces."""
def java_method(signature: str, name: str = None) -> callable:
"""Decorator for binding Java methods to Python methods."""Generate JNI method signatures and handle type conversions between Python and Java.
def signature(returns: type, takes: list) -> str:
"""Generate JNI method signature string."""
def JArray(of_type: type) -> type:
"""Create array type specifier."""
# Primitive type specifiers
jboolean: type
jbyte: type
jchar: type
jdouble: type
jfloat: type
jint: type
jlong: type
jshort: type
jvoid: typeManage Java object lifecycle, type casting, and JVM interaction.
def cast(target_class: type, obj: object) -> object:
"""Cast Java object to target Java class type."""
def find_javaclass(class_name: str) -> object:
"""Find and load Java class by name."""
def detach() -> None:
"""Detach current thread from JVM."""
class JavaException(Exception):
"""Exception wrapper for Java exceptions."""
HASHCODE_MAX: int # Maximum Java hash code value (2^31 - 1)Object Management and Utilities
Configure Java environment, handle platform-specific JVM setup, and set JVM options before startup.
def get_java_setup(platform: str = None) -> object:
"""Get platform-specific Java environment configuration."""
# JVM Configuration (jnius_config module)
def set_options(*opts: str) -> None:
"""Set JVM options before startup."""
def add_options(*opts: str) -> None:
"""Append options to JVM options list."""
def get_options() -> list:
"""Get current list of JVM options."""
def set_classpath(*path: str) -> None:
"""Set JVM classpath before startup."""
def add_classpath(*path: str) -> None:
"""Append items to JVM classpath."""
def get_classpath() -> list:
"""Get current JVM classpath."""
def expand_classpath() -> str:
"""Expand classpath with wildcard resolution."""