CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyjnius

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

Pending
Overview
Eval results
Files

autoclass.mddocs/

Automatic Class Loading

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.

Capabilities

Main Autoclass Function

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()

Class Registration

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.
    """

Java Standard Library Reflection Wrappers

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: ...

Protocol Mapping

Built-in protocol mappings that make Java collections behave like Python collections.

protocol_map: dict

The protocol_map dictionary automatically adds Python magic methods to Java classes:

  • java.util.Collection: __len__, __contains__, __delitem__
  • java.util.List: __getitem__ (with IndexError for iteration)
  • java.util.Map: __setitem__, __getitem__, __delitem__, __len__, __contains__, __iter__
  • java.util.Iterator: __iter__, __next__ (StopIteration support)
  • java.lang.Iterable: __iter__
  • java.lang.AutoCloseable: __enter__, __exit__ (context manager support)
  • java.lang.Comparable: __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
    pass

Class Hierarchy Analysis

Internal 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

docs

autoclass.md

environment.md

index.md

manual-classes.md

signatures.md

utilities.md

tile.json