A Python module to access Java classes as Python classes using JNI.
—
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.
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.
"""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."""PyJNIus respects the following environment variables for Java detection:
Environment Variable Priority:
Desktop Platforms (Windows, Linux, macOS):
Android Platform:
Windows-Specific:
Usage Examples:
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")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}")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}")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)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')PyJNIus supports multiple CPU architectures with automatic detection:
MACHINE2CPU: dict # Maps platform.machine() values to CPU stringsSupported Architectures:
i686 → i386)x86_64 → amd64)armv7l → arm)aarch64 → aarch64)sun4u, sun4v → sparcv9)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}")Common Environment Problems:
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