A Python module to access Java classes as Python classes using JNI.
—
Automatic class loading provides the simplest way to access Java classes from Python. PyJNIus uses Java reflection to automatically discover all public methods, fields, and constructors, creating Python wrapper classes with full access to Java functionality.
Creates Python wrapper classes automatically by analyzing Java classes at runtime using reflection.
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 in wrapper
include_private: Include private methods and fields in wrapper
Returns:
Python class that wraps the Java class with bound methods and fields
Raises:
Exception: If Java class cannot be found or loaded
"""Usage Examples:
from jnius import autoclass
# Load standard Java classes
String = autoclass('java.lang.String')
ArrayList = autoclass('java.util.ArrayList')
HashMap = autoclass('java.util.HashMap')
# Create instances and call methods
text = String('Hello World')
print(text.length()) # 11
print(text.toUpperCase()) # HELLO WORLD
# Work with collections
list_obj = ArrayList()
list_obj.add('item1')
list_obj.add('item2')
print(list_obj.size()) # 2
print(list_obj.get(0)) # item1
# Access static methods
System = autoclass('java.lang.System')
System.out.println('Hello from Java!')
current_time = System.currentTimeMillis()Ensures Java classes are loaded and registered in the PyJNIus class cache.
def ensureclass(clsname: str) -> None:
"""
Ensure Java class is loaded and registered in class cache.
Args:
clsname: Fully qualified Java class name
Note:
This function is called automatically by autoclass but can be used
to pre-load classes for performance optimization.
"""Pre-built wrapper classes for Java reflection API, used internally by autoclass for class analysis.
class Class:
"""Wrapper for java.lang.Class with reflection methods."""
def forName(class_name: str) -> 'Class': ...
def getName() -> str: ...
def getMethods() -> list: ...
def getFields() -> list: ...
def getConstructors() -> list: ...
def getSuperclass() -> 'Class': ...
def getInterfaces() -> list: ...
def isInterface() -> bool: ...
def isArray() -> bool: ...
def isPrimitive() -> bool: ...
class Method:
"""Wrapper for java.lang.reflect.Method."""
def getName() -> str: ...
def getParameterTypes() -> list: ...
def getReturnType() -> 'Class': ...
def getModifiers() -> int: ...
def isVarArgs() -> bool: ...
class Field:
"""Wrapper for java.lang.reflect.Field."""
def getName() -> str: ...
def getType() -> 'Class': ...
def getModifiers() -> int: ...
class Constructor:
"""Wrapper for java.lang.reflect.Constructor."""
def getParameterTypes() -> list: ...
def getModifiers() -> int: ...
def isVarArgs() -> bool: ...
class Modifier:
"""Wrapper for java.lang.reflect.Modifier with static methods."""
@staticmethod
def isPublic(mod: int) -> bool: ...
@staticmethod
def isPrivate(mod: int) -> bool: ...
@staticmethod
def isProtected(mod: int) -> bool: ...
@staticmethod
def isStatic(mod: int) -> bool: ...
@staticmethod
def isFinal(mod: int) -> bool: ...
@staticmethod
def isAbstract(mod: int) -> bool: ...Built-in protocol mappings that make Java collections behave like Python collections.
protocol_map: dictThe protocol_map dictionary automatically adds Python magic methods to Java classes:
__len__, __contains__, __delitem____getitem__ (with IndexError for iteration)__setitem__, __getitem__, __delitem__, __len__, __contains__, __iter____iter__, __next__ (StopIteration support)__iter____enter__, __exit__ (context manager support)__eq__, __ne__, __lt__, __gt__, __le__, __ge__Usage Examples:
from jnius import autoclass
# Java collections work with Python syntax
ArrayList = autoclass('java.util.ArrayList')
list_obj = ArrayList()
list_obj.add('hello')
list_obj.add('world')
# Python protocols work automatically
print(len(list_obj)) # 2
print('hello' in list_obj) # True
# Iteration works naturally
for item in list_obj:
print(item)
# Maps work like Python dictionaries
HashMap = autoclass('java.util.HashMap')
map_obj = HashMap()
map_obj['key1'] = 'value1'
map_obj['key2'] = 'value2'
print(len(map_obj)) # 2
print(map_obj['key1']) # value1
# Context manager support for closeable resources
FileInputStream = autoclass('java.io.FileInputStream')
with FileInputStream('file.txt') as stream:
# stream.close() called automatically
passInternal functions used by autoclass to analyze Java class inheritance and interface implementation.
def identify_hierarchy(cls: 'Class', level: int, concrete: bool = True) -> list:
"""
Analyze Java class hierarchy including superclasses and interfaces.
Args:
cls: Java Class object to analyze
level: Current hierarchy depth level
concrete: Whether to include concrete classes only
Returns:
List of (class, level) tuples representing hierarchy
"""This function enables autoclass to properly handle method resolution order and interface implementation when creating Python wrapper classes.
Install with Tessl CLI
npx tessl i tessl/pypi-pyjnius