or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

autoclass.mdenvironment.mdindex.mdmanual-classes.mdsignatures.mdutilities.md
tile.json

tessl/pypi-pyjnius

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

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pyjnius@1.6.x

To install, run

npx @tessl/cli install tessl/pypi-pyjnius@1.6.0

index.mddocs/

PyJNIus

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

Package Information

  • Package Name: pyjnius
  • Language: Python
  • Installation: pip install pyjnius
  • Documentation: http://pyjnius.readthedocs.org

Core Imports

from jnius import autoclass

For manual class definitions:

from jnius import JavaClass, MetaJavaClass, JavaMethod, JavaStaticMethod, JavaField, JavaStaticField, PythonJavaClass, java_method

For utility functions:

from jnius import cast, find_javaclass, detach, JavaException, HASHCODE_MAX

For signature helpers:

from jnius import signature, JArray, jint, jlong, jfloat, jdouble, jboolean, jbyte, jchar, jshort, jvoid

For JVM configuration (before importing jnius):

import jnius_config

Basic Usage

from 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'))

Architecture

PyJNIus uses a multi-layered architecture for Java interoperability:

  • JNI Layer: Low-level C/Cython interface to the Java Virtual Machine
  • Object Wrappers: Python classes that wrap Java objects with automatic method binding
  • Metaclass System: MetaJavaClass automatically discovers and binds Java class members
  • Type Conversion: Bidirectional conversion between Python and Java data types
  • Protocol Mapping: Makes Java collections behave like Python collections

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.

Capabilities

Automatic Class Loading

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

Automatic Class Loading

Manual Class Definition

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

Manual Class Definition

Type System and Signatures

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

Type System and Signatures

Object Management and Utilities

Manage 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

Environment and Setup

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

Environment and Setup