A comprehensive Python-to-Java bridge enabling seamless integration between Python and Java virtual machines
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Comprehensive type bridging between Python and Java type systems, including primitive types, arrays, strings, and custom type conversions. This module provides seamless data exchange between Python and Java with automatic and explicit type conversions.
Base classes for Java type representation and conversion.
class JObject:
"""Base class for all Java objects with casting functionality.
Provides type conversion and object manipulation methods.
"""
class JString:
"""Java string type representation.
Bridges between Python str and Java String objects.
"""
def __init__(self, value: str):
"""Create a Java String from Python string.
Args:
value: Python string to convert
"""
class JArray:
"""Factory for Java array types.
Creates typed Java arrays from Python sequences.
"""
def __init__(self, type_class, ndims: int = 1):
"""Create array type factory.
Args:
type_class: Java class for array elements
ndims: Number of dimensions (default 1)
"""
def __call__(self, sequence):
"""Create Java array from Python sequence.
Args:
sequence: Python list, tuple, or other sequence
Returns:
Java array of the specified type
"""
class JException(Exception):
"""Base class for all Java exceptions.
Bridges Java exceptions to Python exception system.
"""Python wrappers for Java primitive types with explicit type control.
class JBoolean:
"""Java boolean primitive wrapper.
Converts Python bool to Java boolean primitive.
"""
def __init__(self, value: bool):
"""Create Java boolean from Python bool.
Args:
value: Python boolean value
"""
class JByte:
"""Java byte primitive wrapper.
Converts Python int to Java byte primitive (-128 to 127).
"""
def __init__(self, value: int):
"""Create Java byte from Python int.
Args:
value: Python int (-128 to 127)
Raises:
OverflowError: If value outside byte range
"""
class JChar:
"""Java char primitive wrapper.
Converts Python str (single character) to Java char primitive.
"""
def __init__(self, value: str):
"""Create Java char from Python string.
Args:
value: Single character string
Raises:
ValueError: If string length != 1
"""
class JShort:
"""Java short primitive wrapper.
Converts Python int to Java short primitive (-32768 to 32767).
"""
def __init__(self, value: int):
"""Create Java short from Python int.
Args:
value: Python int (-32768 to 32767)
Raises:
OverflowError: If value outside short range
"""
class JInt:
"""Java int primitive wrapper.
Converts Python int to Java int primitive.
"""
def __init__(self, value: int):
"""Create Java int from Python int.
Args:
value: Python int (32-bit range)
Raises:
OverflowError: If value outside int range
"""
class JLong:
"""Java long primitive wrapper.
Converts Python int to Java long primitive.
"""
def __init__(self, value: int):
"""Create Java long from Python int.
Args:
value: Python int (64-bit range)
"""
class JFloat:
"""Java float primitive wrapper.
Converts Python float to Java float primitive.
"""
def __init__(self, value: float):
"""Create Java float from Python float.
Args:
value: Python float (32-bit precision)
"""
class JDouble:
"""Java double primitive wrapper.
Converts Python float to Java double primitive.
"""
def __init__(self, value: float):
"""Create Java double from Python float.
Args:
value: Python float (64-bit precision)
"""import jpype
jpype.startJVM()
# Automatic string conversion (default)
java_string = jpype.java.lang.String("Hello from Python")
print(type(java_string)) # <class 'str'> (converted back to Python)
# Explicit Java string creation
explicit_string = jpype.JString("Hello Java")
print(type(explicit_string)) # <class 'jpype._jstring.str'>
# String operations
java_str = jpype.java.lang.String("Test")
print(java_str.length()) # 4
print(java_str.toUpperCase()) # "TEST"
jpype.shutdownJVM()import jpype
jpype.startJVM()
# Automatic conversion (JPype chooses appropriate Java type)
result = jpype.java.lang.Math.abs(-42) # int -> int
pi = jpype.java.lang.Math.PI # double -> float
# Explicit primitive type control
byte_val = jpype.JByte(127)
short_val = jpype.JShort(32000)
int_val = jpype.JInt(2000000)
long_val = jpype.JLong(9223372036854775807)
float_val = jpype.JFloat(3.14159)
double_val = jpype.JDouble(3.141592653589793)
boolean_val = jpype.JBoolean(True)
char_val = jpype.JChar('A')
jpype.shutdownJVM()import jpype
jpype.startJVM()
# Create typed arrays
int_array_factory = jpype.JArray(jpype.JInt)
int_array = int_array_factory([1, 2, 3, 4, 5])
string_array_factory = jpype.JArray(jpype.java.lang.String)
string_array = string_array_factory(["hello", "world"])
# Multi-dimensional arrays
int_matrix_factory = jpype.JArray(jpype.JInt, 2)
int_matrix = int_matrix_factory([[1, 2], [3, 4]])
# Array access
print(int_array[0]) # 1
print(len(int_array)) # 5
# Convert back to Python
python_list = list(int_array)
print(python_list) # [1, 2, 3, 4, 5]
jpype.shutdownJVM()import jpype
jpype.startJVM()
# Create Java collections with proper types
ArrayList = jpype.java.util.ArrayList
HashMap = jpype.java.util.HashMap
# String list
string_list = ArrayList()
string_list.add(jpype.JString("item1"))
string_list.add(jpype.JString("item2"))
# Integer list with explicit typing
int_list = ArrayList()
int_list.add(jpype.JInt(10))
int_list.add(jpype.JInt(20))
# Hash map with mixed types
map_obj = HashMap()
map_obj.put(jpype.JString("key1"), jpype.JInt(100))
map_obj.put(jpype.JString("key2"), jpype.JDouble(3.14))
jpype.shutdownJVM()import jpype
jpype.startJVM()
try:
# This will raise a Java exception
string_obj = jpype.java.lang.String("test")
char = string_obj.charAt(10) # Index out of bounds
except jpype.JException as e:
print(f"Java exception caught: {e}")
print(f"Exception type: {type(e)}")
# Catching specific Java exceptions
try:
jpype.java.lang.Integer.parseInt("not_a_number")
except jpype.java.lang.NumberFormatException as e:
print(f"Number format error: {e}")
jpype.shutdownJVM()import jpype
jpype.startJVM()
# Type checking
obj = jpype.java.lang.String("test")
print(isinstance(obj, jpype.JObject)) # True
print(isinstance(obj, str)) # True (automatic conversion)
# Explicit casting for interfaces
list_obj = jpype.java.util.ArrayList()
collection = jpype.JObject(list_obj, jpype.java.util.Collection)
# Check Java types
String = jpype.java.lang.String
string_obj = String("hello")
print(string_obj.getClass().getName()) # "java.lang.String"
jpype.shutdownJVM()import jpype
jpype.startJVM()
# Convert Python data structures to Java
python_dict = {"name": "John", "age": 30}
# Manual conversion to Java HashMap
HashMap = jpype.java.util.HashMap
java_map = HashMap()
for key, value in python_dict.items():
java_map.put(jpype.JString(key), jpype.JObject(value))
# Convert back to Python
python_dict_back = {}
for key in java_map.keySet():
python_dict_back[str(key)] = java_map.get(key)
jpype.shutdownJVM()Install with Tessl CLI
npx tessl i tessl/pypi-jpype1