A Python module to access Java classes as Python classes using JNI.
npx @tessl/cli install tessl/pypi-pyjnius@1.6.00
# PyJNIus
1
2
PyJNIus is a Python module that provides seamless access to Java classes as Python classes using the Java Native Interface (JNI). It enables Python applications to call Java methods, access Java fields, and create Java objects directly, supporting both automatic class discovery and manual class declaration patterns.
3
4
## Package Information
5
6
- **Package Name**: pyjnius
7
- **Language**: Python
8
- **Installation**: `pip install pyjnius`
9
- **Documentation**: http://pyjnius.readthedocs.org
10
11
## Core Imports
12
13
```python
14
from jnius import autoclass
15
```
16
17
For manual class definitions:
18
19
```python
20
from jnius import JavaClass, MetaJavaClass, JavaMethod, JavaStaticMethod, JavaField, JavaStaticField, PythonJavaClass, java_method
21
```
22
23
For utility functions:
24
25
```python
26
from jnius import cast, find_javaclass, detach, JavaException, HASHCODE_MAX
27
```
28
29
For signature helpers:
30
31
```python
32
from jnius import signature, JArray, jint, jlong, jfloat, jdouble, jboolean, jbyte, jchar, jshort, jvoid
33
```
34
35
For JVM configuration (before importing jnius):
36
37
```python
38
import jnius_config
39
```
40
41
## Basic Usage
42
43
```python
44
from jnius import autoclass
45
46
# Automatic class loading - easiest approach
47
String = autoclass('java.lang.String')
48
string_obj = String('Hello World')
49
print(string_obj.length()) # 11
50
51
# Java collections work with Python protocols
52
Stack = autoclass('java.util.Stack')
53
stack = Stack()
54
stack.push('hello')
55
stack.push('world')
56
print(len(stack)) # 2
57
print(stack.pop()) # world
58
59
# Access static methods and fields
60
System = autoclass('java.lang.System')
61
System.out.println('Hello from Java!')
62
print('Java version:', System.getProperty('java.version'))
63
```
64
65
## Architecture
66
67
PyJNIus uses a multi-layered architecture for Java interoperability:
68
69
- **JNI Layer**: Low-level C/Cython interface to the Java Virtual Machine
70
- **Object Wrappers**: Python classes that wrap Java objects with automatic method binding
71
- **Metaclass System**: MetaJavaClass automatically discovers and binds Java class members
72
- **Type Conversion**: Bidirectional conversion between Python and Java data types
73
- **Protocol Mapping**: Makes Java collections behave like Python collections
74
75
This design enables seamless integration between Python and Java applications, supporting complex scenarios like Android app development via python-for-android, enterprise Java integration, and cross-platform development.
76
77
## Capabilities
78
79
### Automatic Class Loading
80
81
Automatically discover and bind Java classes with full method and field access using runtime reflection. This is the recommended approach for most use cases.
82
83
```python { .api }
84
def autoclass(clsname: str, include_protected: bool = True, include_private: bool = True) -> type:
85
"""
86
Create Python wrapper class for Java class with automatic member discovery.
87
88
Args:
89
clsname: Fully qualified Java class name (e.g., 'java.lang.String')
90
include_protected: Include protected methods and fields
91
include_private: Include private methods and fields
92
93
Returns:
94
Python class that wraps the Java class
95
"""
96
97
def ensureclass(clsname: str) -> None:
98
"""Ensure Java class is loaded and registered."""
99
```
100
101
[Automatic Class Loading](./autoclass.md)
102
103
### Manual Class Definition
104
105
Define Python wrapper classes manually for precise control over exposed methods and fields. Includes support for creating Python classes that implement Java interfaces (proxies). Useful for performance optimization and custom behavior.
106
107
```python { .api }
108
class JavaClass:
109
"""Base class for manual Java class wrappers."""
110
111
class MetaJavaClass(type):
112
"""Metaclass for Java class wrappers with member binding."""
113
114
def JavaMethod(signature: str, varargs: bool = False) -> callable:
115
"""Wrap Java instance method."""
116
117
def JavaStaticMethod(signature: str, varargs: bool = False) -> callable:
118
"""Wrap Java static method."""
119
120
def JavaField(signature: str) -> property:
121
"""Wrap Java instance field."""
122
123
def JavaStaticField(signature: str) -> property:
124
"""Wrap Java static field."""
125
126
def JavaMultipleMethod(signatures: list) -> callable:
127
"""Wrap overloaded Java methods."""
128
129
class PythonJavaClass:
130
"""Base class for creating Python classes that implement Java interfaces."""
131
132
def java_method(signature: str, name: str = None) -> callable:
133
"""Decorator for binding Java methods to Python methods."""
134
```
135
136
[Manual Class Definition](./manual-classes.md)
137
138
### Type System and Signatures
139
140
Generate JNI method signatures and handle type conversions between Python and Java.
141
142
```python { .api }
143
def signature(returns: type, takes: list) -> str:
144
"""Generate JNI method signature string."""
145
146
def JArray(of_type: type) -> type:
147
"""Create array type specifier."""
148
149
# Primitive type specifiers
150
jboolean: type
151
jbyte: type
152
jchar: type
153
jdouble: type
154
jfloat: type
155
jint: type
156
jlong: type
157
jshort: type
158
jvoid: type
159
```
160
161
[Type System and Signatures](./signatures.md)
162
163
### Object Management and Utilities
164
165
Manage Java object lifecycle, type casting, and JVM interaction.
166
167
```python { .api }
168
def cast(target_class: type, obj: object) -> object:
169
"""Cast Java object to target Java class type."""
170
171
def find_javaclass(class_name: str) -> object:
172
"""Find and load Java class by name."""
173
174
def detach() -> None:
175
"""Detach current thread from JVM."""
176
177
class JavaException(Exception):
178
"""Exception wrapper for Java exceptions."""
179
180
HASHCODE_MAX: int # Maximum Java hash code value (2^31 - 1)
181
```
182
183
[Object Management and Utilities](./utilities.md)
184
185
### Environment and Setup
186
187
Configure Java environment, handle platform-specific JVM setup, and set JVM options before startup.
188
189
```python { .api }
190
def get_java_setup(platform: str = None) -> object:
191
"""Get platform-specific Java environment configuration."""
192
193
# JVM Configuration (jnius_config module)
194
def set_options(*opts: str) -> None:
195
"""Set JVM options before startup."""
196
197
def add_options(*opts: str) -> None:
198
"""Append options to JVM options list."""
199
200
def get_options() -> list:
201
"""Get current list of JVM options."""
202
203
def set_classpath(*path: str) -> None:
204
"""Set JVM classpath before startup."""
205
206
def add_classpath(*path: str) -> None:
207
"""Append items to JVM classpath."""
208
209
def get_classpath() -> list:
210
"""Get current JVM classpath."""
211
212
def expand_classpath() -> str:
213
"""Expand classpath with wildcard resolution."""
214
```
215
216
[Environment and Setup](./environment.md)