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

environment.mddocs/

Environment and Setup

PyJNIus provides comprehensive Java environment detection and configuration for different platforms. The environment system automatically discovers Java installations, handles platform-specific JVM loading, and manages classpath configuration. It also includes JVM configuration utilities for setting options and classpath before JVM startup.

Capabilities

Java Environment Detection

Main function for getting platform-specific Java environment configuration.

def get_java_setup(platform: str = None) -> JavaLocation:
    """
    Get platform-specific Java environment configuration.
    
    Args:
        platform: Target platform ('win32', 'android', or None for auto-detection)
        
    Returns:
        JavaLocation object with Java environment information
        
    Note:
        Automatically detects and configures Java environment based on
        JAVA_HOME, JDK_HOME, JRE_HOME environment variables and system paths.
    """

JavaLocation Object

The JavaLocation object returned by get_java_setup() provides access to Java environment details:

class JavaLocation:
    """Java environment configuration object."""
    
    def get_javahome() -> str:
        """Get Java home directory path."""
    
    def get_javac() -> str:
        """Get javac compiler executable path."""
    
    def get_libraries() -> list:
        """Get list of required JNI libraries."""
    
    def get_library_dirs() -> list:
        """Get list of library search directories."""
    
    def get_include_dirs() -> list:
        """Get list of JNI header include directories."""
    
    def is_jdk() -> bool:
        """Check if installation is JDK (includes compiler) vs JRE only."""

Environment Variables

PyJNIus respects the following environment variables for Java detection:

  • JAVA_HOME: Primary Java installation directory
  • JDK_HOME: JDK-specific installation directory
  • JRE_HOME: JRE-specific installation directory
  • CLASSPATH: Additional Java classpath entries

Environment Variable Priority:

  1. JAVA_HOME (highest priority)
  2. JDK_HOME
  3. JRE_HOME
  4. System default Java installation

Platform-Specific Behavior

Desktop Platforms (Windows, Linux, macOS):

  • Automatic JVM library loading from standard locations
  • Support for both JDK and JRE installations
  • Dynamic library path resolution

Android Platform:

  • Integration with python-for-android build system
  • Automatic thread detachment for all threads
  • Android-specific JNI library handling

Windows-Specific:

  • DLL directory management for JVM loading
  • Support for multiple JVM variants (client, server, default)
  • Automatic library path resolution

Usage Examples:

Basic Environment Setup

from jnius.env import get_java_setup

# Get Java environment for current platform
java_env = get_java_setup()

print(f"Java Home: {java_env.get_javahome()}")
print(f"Is JDK: {java_env.is_jdk()}")
print(f"Libraries: {java_env.get_libraries()}")
print(f"Include Dirs: {java_env.get_include_dirs()}")

# Check if we can compile Java code
if java_env.is_jdk():
    javac_path = java_env.get_javac()
    print(f"Java compiler: {javac_path}")
else:
    print("JRE only - no compiler available")

Platform-Specific Setup

from jnius.env import get_java_setup
import sys

# Get setup for specific platform
if sys.platform == 'win32':
    java_env = get_java_setup('win32')
elif 'ANDROID_ARGUMENT' in os.environ:
    java_env = get_java_setup('android')
else:
    java_env = get_java_setup()  # Auto-detect

# Platform-specific library handling
libs = java_env.get_libraries()
lib_dirs = java_env.get_library_dirs()

print(f"Platform: {sys.platform}")
print(f"Required libraries: {libs}")
print(f"Library directories: {lib_dirs}")

Environment Validation

from jnius.env import get_java_setup
import os

def validate_java_environment():
    """Validate Java environment setup."""
    try:
        java_env = get_java_setup()
        
        # Check Java home exists
        java_home = java_env.get_javahome()
        if not os.path.exists(java_home):
            return False, f"Java home not found: {java_home}"
        
        # Check for JDK if needed
        if not java_env.is_jdk():
            return False, "JDK required but only JRE found"
        
        # Check libraries
        libs = java_env.get_libraries()
        lib_dirs = java_env.get_library_dirs()
        
        for lib_dir in lib_dirs:
            if not os.path.exists(lib_dir):
                return False, f"Library directory not found: {lib_dir}"
        
        return True, "Java environment valid"
        
    except Exception as e:
        return False, f"Java environment error: {e}"

# Usage
is_valid, message = validate_java_environment()
print(f"Environment valid: {is_valid}")
print(f"Message: {message}")

Classpath Management

import os
from jnius.env import get_java_setup

def setup_classpath(additional_jars=None):
    """Setup Java classpath with additional JAR files."""
    java_env = get_java_setup()
    
    # Get existing classpath
    existing_classpath = os.environ.get('CLASSPATH', '')
    
    # Build new classpath
    classpath_entries = []
    
    if existing_classpath:
        classpath_entries.append(existing_classpath)
    
    if additional_jars:
        for jar_path in additional_jars:
            if os.path.exists(jar_path):
                classpath_entries.append(jar_path)
            else:
                print(f"Warning: JAR not found: {jar_path}")
    
    # Set classpath
    if classpath_entries:
        new_classpath = os.pathsep.join(classpath_entries)
        os.environ['CLASSPATH'] = new_classpath
        print(f"Classpath set to: {new_classpath}")
    
    return java_env

# Usage
additional_jars = [
    '/path/to/library1.jar',
    '/path/to/library2.jar'
]
java_env = setup_classpath(additional_jars)

JVM Configuration (jnius_config)

Functions for configuring JVM options and classpath before JVM startup. These must be called before importing jnius.

def set_options(*opts: str) -> None:
    """
    Set list of JVM options, replacing any previously set options.
    
    Args:
        *opts: JVM option strings (e.g., '-Xmx4096m', '-Xrs')
        
    Raises:
        ValueError: If JVM is already running
        
    Note:
        Must be called before importing jnius or JVM startup.
    """

def add_options(*opts: str) -> None:
    """
    Append options to the list of JVM options.
    
    Args:
        *opts: JVM option strings to append
        
    Raises:
        ValueError: If JVM is already running
    """

def get_options() -> list:
    """
    Get current list of JVM options.
    
    Returns:
        List of JVM option strings
    """

def set_classpath(*path: str) -> None:
    """
    Set JVM classpath, replacing existing classpath and CLASSPATH environment variable.
    
    Args:
        *path: Classpath entries (directories, JAR files)
        
    Raises:
        ValueError: If JVM is already running
    """

def add_classpath(*path: str) -> None:
    """
    Append items to JVM classpath.
    
    Args:
        *path: Classpath entries to append
        
    Raises:
        ValueError: If JVM is already running
    """

def get_classpath() -> list:
    """
    Get current JVM classpath including default entries.
    
    Returns:
        List of classpath entries
        
    Note:
        Includes CLASSPATH environment variable and PyJNIus defaults.
    """

def expand_classpath() -> str:
    """
    Expand classpath with wildcard resolution for JAR files.
    
    Returns:
        Platform-specific classpath string with wildcards expanded
    """

Usage Examples:

import jnius_config

# Set JVM options before importing jnius
jnius_config.set_options('-Xmx4096m', '-Xrs')
jnius_config.add_options('-XX:+UseG1GC')

# Set classpath with additional JARs
jnius_config.set_classpath('.', '/path/to/library.jar', '/path/to/libs/*')

# Now safe to import jnius
import jnius
from jnius import autoclass

# Use Java classes with configured environment
String = autoclass('java.lang.String')

Architecture Support

PyJNIus supports multiple CPU architectures with automatic detection:

MACHINE2CPU: dict  # Maps platform.machine() values to CPU strings

Supported Architectures:

  • x86 (i686i386)
  • x86_64 (x86_64amd64)
  • ARM (armv7larm)
  • ARM64 (aarch64aarch64)
  • SPARC (sun4u, sun4vsparcv9)

Usage Example:

from jnius.env import MACHINE2CPU, get_java_setup
from platform import machine

# Get current architecture
current_machine = machine()
cpu_type = MACHINE2CPU.get(current_machine, current_machine)

print(f"Machine: {current_machine}")
print(f"CPU Type: {cpu_type}")

# Java environment will use appropriate libraries for architecture
java_env = get_java_setup()
lib_dirs = java_env.get_library_dirs()

# Library directories often include architecture-specific paths
for lib_dir in lib_dirs:
    if cpu_type in lib_dir:
        print(f"Architecture-specific lib dir: {lib_dir}")

Troubleshooting Environment Issues

Common Environment Problems:

  1. JAVA_HOME not set: Set JAVA_HOME environment variable
  2. JRE vs JDK: Ensure JDK is installed if compilation is needed
  3. Architecture mismatch: Use JVM matching Python architecture (32/64-bit)
  4. Missing libraries: Install complete JDK/JRE package
  5. Classpath issues: Verify JAR files exist and are accessible

Debug Environment Setup:

import os
import sys
from jnius.env import get_java_setup

def debug_java_environment():
    """Debug Java environment configuration."""
    print("=== Java Environment Debug ===")
    
    # Environment variables
    print("\nEnvironment Variables:")
    for var in ['JAVA_HOME', 'JDK_HOME', 'JRE_HOME', 'CLASSPATH']:
        value = os.environ.get(var, 'Not set')
        print(f"  {var}: {value}")
    
    # Platform info
    print(f"\nPlatform: {sys.platform}")
    print(f"Architecture: {machine()}")
    
    # Java setup
    try:
        java_env = get_java_setup()
        print(f"\nJava Setup:")
        print(f"  Java Home: {java_env.get_javahome()}")
        print(f"  Is JDK: {java_env.is_jdk()}")
        print(f"  Libraries: {java_env.get_libraries()}")
        print(f"  Library Dirs: {java_env.get_library_dirs()}")
        print(f"  Include Dirs: {java_env.get_include_dirs()}")
        
    except Exception as e:
        print(f"\nJava Setup Error: {e}")

# Usage
debug_java_environment()

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