0
# Automatic Class Loading
1
2
Automatic class loading provides the simplest way to access Java classes from Python. PyJNIus uses Java reflection to automatically discover all public methods, fields, and constructors, creating Python wrapper classes with full access to Java functionality.
3
4
## Capabilities
5
6
### Main Autoclass Function
7
8
Creates Python wrapper classes automatically by analyzing Java classes at runtime using reflection.
9
10
```python { .api }
11
def autoclass(clsname: str, include_protected: bool = True, include_private: bool = True) -> type:
12
"""
13
Create Python wrapper class for Java class with automatic member discovery.
14
15
Args:
16
clsname: Fully qualified Java class name (e.g., 'java.lang.String')
17
include_protected: Include protected methods and fields in wrapper
18
include_private: Include private methods and fields in wrapper
19
20
Returns:
21
Python class that wraps the Java class with bound methods and fields
22
23
Raises:
24
Exception: If Java class cannot be found or loaded
25
"""
26
```
27
28
**Usage Examples:**
29
30
```python
31
from jnius import autoclass
32
33
# Load standard Java classes
34
String = autoclass('java.lang.String')
35
ArrayList = autoclass('java.util.ArrayList')
36
HashMap = autoclass('java.util.HashMap')
37
38
# Create instances and call methods
39
text = String('Hello World')
40
print(text.length()) # 11
41
print(text.toUpperCase()) # HELLO WORLD
42
43
# Work with collections
44
list_obj = ArrayList()
45
list_obj.add('item1')
46
list_obj.add('item2')
47
print(list_obj.size()) # 2
48
print(list_obj.get(0)) # item1
49
50
# Access static methods
51
System = autoclass('java.lang.System')
52
System.out.println('Hello from Java!')
53
current_time = System.currentTimeMillis()
54
```
55
56
### Class Registration
57
58
Ensures Java classes are loaded and registered in the PyJNIus class cache.
59
60
```python { .api }
61
def ensureclass(clsname: str) -> None:
62
"""
63
Ensure Java class is loaded and registered in class cache.
64
65
Args:
66
clsname: Fully qualified Java class name
67
68
Note:
69
This function is called automatically by autoclass but can be used
70
to pre-load classes for performance optimization.
71
"""
72
```
73
74
### Java Standard Library Reflection Wrappers
75
76
Pre-built wrapper classes for Java reflection API, used internally by autoclass for class analysis.
77
78
```python { .api }
79
class Class:
80
"""Wrapper for java.lang.Class with reflection methods."""
81
82
def forName(class_name: str) -> 'Class': ...
83
def getName() -> str: ...
84
def getMethods() -> list: ...
85
def getFields() -> list: ...
86
def getConstructors() -> list: ...
87
def getSuperclass() -> 'Class': ...
88
def getInterfaces() -> list: ...
89
def isInterface() -> bool: ...
90
def isArray() -> bool: ...
91
def isPrimitive() -> bool: ...
92
93
class Method:
94
"""Wrapper for java.lang.reflect.Method."""
95
96
def getName() -> str: ...
97
def getParameterTypes() -> list: ...
98
def getReturnType() -> 'Class': ...
99
def getModifiers() -> int: ...
100
def isVarArgs() -> bool: ...
101
102
class Field:
103
"""Wrapper for java.lang.reflect.Field."""
104
105
def getName() -> str: ...
106
def getType() -> 'Class': ...
107
def getModifiers() -> int: ...
108
109
class Constructor:
110
"""Wrapper for java.lang.reflect.Constructor."""
111
112
def getParameterTypes() -> list: ...
113
def getModifiers() -> int: ...
114
def isVarArgs() -> bool: ...
115
116
class Modifier:
117
"""Wrapper for java.lang.reflect.Modifier with static methods."""
118
119
@staticmethod
120
def isPublic(mod: int) -> bool: ...
121
@staticmethod
122
def isPrivate(mod: int) -> bool: ...
123
@staticmethod
124
def isProtected(mod: int) -> bool: ...
125
@staticmethod
126
def isStatic(mod: int) -> bool: ...
127
@staticmethod
128
def isFinal(mod: int) -> bool: ...
129
@staticmethod
130
def isAbstract(mod: int) -> bool: ...
131
```
132
133
### Protocol Mapping
134
135
Built-in protocol mappings that make Java collections behave like Python collections.
136
137
```python { .api }
138
protocol_map: dict
139
```
140
141
The `protocol_map` dictionary automatically adds Python magic methods to Java classes:
142
143
- **java.util.Collection**: `__len__`, `__contains__`, `__delitem__`
144
- **java.util.List**: `__getitem__` (with IndexError for iteration)
145
- **java.util.Map**: `__setitem__`, `__getitem__`, `__delitem__`, `__len__`, `__contains__`, `__iter__`
146
- **java.util.Iterator**: `__iter__`, `__next__` (StopIteration support)
147
- **java.lang.Iterable**: `__iter__`
148
- **java.lang.AutoCloseable**: `__enter__`, `__exit__` (context manager support)
149
- **java.lang.Comparable**: `__eq__`, `__ne__`, `__lt__`, `__gt__`, `__le__`, `__ge__`
150
151
**Usage Examples:**
152
153
```python
154
from jnius import autoclass
155
156
# Java collections work with Python syntax
157
ArrayList = autoclass('java.util.ArrayList')
158
list_obj = ArrayList()
159
list_obj.add('hello')
160
list_obj.add('world')
161
162
# Python protocols work automatically
163
print(len(list_obj)) # 2
164
print('hello' in list_obj) # True
165
166
# Iteration works naturally
167
for item in list_obj:
168
print(item)
169
170
# Maps work like Python dictionaries
171
HashMap = autoclass('java.util.HashMap')
172
map_obj = HashMap()
173
map_obj['key1'] = 'value1'
174
map_obj['key2'] = 'value2'
175
print(len(map_obj)) # 2
176
print(map_obj['key1']) # value1
177
178
# Context manager support for closeable resources
179
FileInputStream = autoclass('java.io.FileInputStream')
180
with FileInputStream('file.txt') as stream:
181
# stream.close() called automatically
182
pass
183
```
184
185
### Class Hierarchy Analysis
186
187
Internal functions used by autoclass to analyze Java class inheritance and interface implementation.
188
189
```python { .api }
190
def identify_hierarchy(cls: 'Class', level: int, concrete: bool = True) -> list:
191
"""
192
Analyze Java class hierarchy including superclasses and interfaces.
193
194
Args:
195
cls: Java Class object to analyze
196
level: Current hierarchy depth level
197
concrete: Whether to include concrete classes only
198
199
Returns:
200
List of (class, level) tuples representing hierarchy
201
"""
202
```
203
204
This function enables autoclass to properly handle method resolution order and interface implementation when creating Python wrapper classes.