JPype1

1.6.0 · active · verified Sun Mar 29

JPype is a Python module that provides full access to Java libraries from within Python. It seamlessly bridges Python and Java at the native level using the Java Native Interface (JNI), allowing Python to leverage Java-only libraries, develop and test Java code, and perform scientific computing. The current version is 1.6.0, and it is actively maintained with regular releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the JVM, import a basic Java class (`java.lang.String`), create an instance, call a method, and then shut down the JVM. It highlights the importance of setting the `JAVA_HOME` environment variable for JPype to locate the Java Virtual Machine.

import jpype
import jpype.imports
from jpype.types import *
import os

# Ensure JAVA_HOME is set or provide jvmpath directly
# Example: jvmpath = jpype.getDefaultJVMPath() (only works if JAVA_HOME is configured)
# Or, set it manually (e.g., for Windows: C:\Program Files\Java\jdk-11\bin\server\jvm.dll)
# For Linux/macOS: /usr/lib/jvm/java-11-openjdk/lib/server/libjvm.so or similar
# For robust execution, ensure JAVA_HOME is set in your environment variables.
java_home = os.environ.get('JAVA_HOME', '')
if not java_home:
    print("Warning: JAVA_HOME environment variable is not set. JPype might not find the JVM.")
    print("Please set JAVA_HOME to your JDK/JRE installation path.")
    # Attempt to start without explicit path if JAVA_HOME is missing, might fail
    jvm_args = []
else:
    print(f"Using JAVA_HOME: {java_home}")
    # On some systems, getDefaultJVMPath might still require the full path to libjvm.so/jvm.dll
    # For simplicity in quickstart, relying on JAVA_HOME or system default
    jvm_args = [] # JPype often infers path if JAVA_HOME is set

# Start the JVM with a minimal classpath
try:
    # Using a dummy classpath for demonstration; replace with actual JARs if needed.
    # For this simple example, no specific JARs are required beyond standard Java libraries.
    jpype.startJVM(jpype.getDefaultJVMPath(), *jvm_args, classpath=[os.environ.get('CLASSPATH', '')])
    
    # Import a Java class
    from java.lang import System, String

    # Use Java objects and methods
    java_string = String("Hello from Java!")
    System.out.println(java_string)

    # Accessing Java static fields or methods
    print(f"Java Version: {System.getProperty('java.version')}")

except Exception as e:
    print(f"Failed to start JVM or execute Java code: {e}")
finally:
    # Shutdown the JVM
    if jpype.isJVMStarted():
        jpype.shutdownJVM()
        print("JVM shutdown.")

view raw JSON →