PemJa

0.6.1 · active · verified Fri Apr 17

PemJa is a Python-Java bridge that enables embedding a JVM within a Python process, allowing dynamic interaction with Java objects and classes. It simplifies calling Java methods from Python and provides mechanisms for classpath management. The current version is 0.6.1, with releases occurring as features are added or bugs are fixed, but without a strict regular cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates launching a JVM, accessing static Java methods, creating Java object instances, calling instance methods, and basic Java exception handling. It's crucial to have JDK 8+ installed on your system for PemJa to function.

import pemja

# Ensure JDK 8+ is installed and accessible in your system's PATH or JAVA_HOME.
# In a production environment, consider explicit JVM options or classpath management.

try:
    print("Launching JVM...")
    # Using a context manager ensures the JVM is shut down cleanly
    with pemja.launch_jvm() as jvm:
        print("JVM launched successfully.")

        # 1. Access a static method from a core Java class
        System = jvm.find_class("java.lang.System")
        java_version = System.getProperty("java.version")
        print(f"Java version reported by JVM: {java_version}")

        # 2. Create an instance of a Java class and call a method
        String = jvm.find_class("java.lang.String")
        greeting = jvm.create_instance(String, "Hello from PemJa in Python!")
        print(f"Original Java string: {greeting}")
        print(f"Uppercase Java string: {greeting.toUpperCase()}")

        # 3. Handle exceptions from Java
        # This is a simple example; real error handling would be more robust
        try:
            Integer = jvm.find_class("java.lang.Integer")
            Integer.parseInt("not_a_number") # This will throw a Java NumberFormatException
        except jvm.JavaException as e:
            print(f"Caught Java Exception: {e.get_stack_trace()}")

except pemja.PemjaException as e:
    print(f"PemJa specific error: {e}")
    print("Please ensure JDK 8+ is correctly installed and configured.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →