or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdclass-object-access.mdclasspath-management.mdexception-handling.mdindex.mdinterface-implementation.mdjvm-management.mdtype-system.md

type-system.mddocs/

0

# Type System and Conversion

1

2

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.

3

4

## Capabilities

5

6

### Core Type Classes

7

8

Base classes for Java type representation and conversion.

9

10

```python { .api }

11

class JObject:

12

"""Base class for all Java objects with casting functionality.

13

14

Provides type conversion and object manipulation methods.

15

"""

16

17

class JString:

18

"""Java string type representation.

19

20

Bridges between Python str and Java String objects.

21

"""

22

23

def __init__(self, value: str):

24

"""Create a Java String from Python string.

25

26

Args:

27

value: Python string to convert

28

"""

29

30

class JArray:

31

"""Factory for Java array types.

32

33

Creates typed Java arrays from Python sequences.

34

"""

35

36

def __init__(self, type_class, ndims: int = 1):

37

"""Create array type factory.

38

39

Args:

40

type_class: Java class for array elements

41

ndims: Number of dimensions (default 1)

42

"""

43

44

def __call__(self, sequence):

45

"""Create Java array from Python sequence.

46

47

Args:

48

sequence: Python list, tuple, or other sequence

49

50

Returns:

51

Java array of the specified type

52

"""

53

54

class JException(Exception):

55

"""Base class for all Java exceptions.

56

57

Bridges Java exceptions to Python exception system.

58

"""

59

```

60

61

### Primitive Type Wrappers

62

63

Python wrappers for Java primitive types with explicit type control.

64

65

```python { .api }

66

class JBoolean:

67

"""Java boolean primitive wrapper.

68

69

Converts Python bool to Java boolean primitive.

70

"""

71

72

def __init__(self, value: bool):

73

"""Create Java boolean from Python bool.

74

75

Args:

76

value: Python boolean value

77

"""

78

79

class JByte:

80

"""Java byte primitive wrapper.

81

82

Converts Python int to Java byte primitive (-128 to 127).

83

"""

84

85

def __init__(self, value: int):

86

"""Create Java byte from Python int.

87

88

Args:

89

value: Python int (-128 to 127)

90

91

Raises:

92

OverflowError: If value outside byte range

93

"""

94

95

class JChar:

96

"""Java char primitive wrapper.

97

98

Converts Python str (single character) to Java char primitive.

99

"""

100

101

def __init__(self, value: str):

102

"""Create Java char from Python string.

103

104

Args:

105

value: Single character string

106

107

Raises:

108

ValueError: If string length != 1

109

"""

110

111

class JShort:

112

"""Java short primitive wrapper.

113

114

Converts Python int to Java short primitive (-32768 to 32767).

115

"""

116

117

def __init__(self, value: int):

118

"""Create Java short from Python int.

119

120

Args:

121

value: Python int (-32768 to 32767)

122

123

Raises:

124

OverflowError: If value outside short range

125

"""

126

127

class JInt:

128

"""Java int primitive wrapper.

129

130

Converts Python int to Java int primitive.

131

"""

132

133

def __init__(self, value: int):

134

"""Create Java int from Python int.

135

136

Args:

137

value: Python int (32-bit range)

138

139

Raises:

140

OverflowError: If value outside int range

141

"""

142

143

class JLong:

144

"""Java long primitive wrapper.

145

146

Converts Python int to Java long primitive.

147

"""

148

149

def __init__(self, value: int):

150

"""Create Java long from Python int.

151

152

Args:

153

value: Python int (64-bit range)

154

"""

155

156

class JFloat:

157

"""Java float primitive wrapper.

158

159

Converts Python float to Java float primitive.

160

"""

161

162

def __init__(self, value: float):

163

"""Create Java float from Python float.

164

165

Args:

166

value: Python float (32-bit precision)

167

"""

168

169

class JDouble:

170

"""Java double primitive wrapper.

171

172

Converts Python float to Java double primitive.

173

"""

174

175

def __init__(self, value: float):

176

"""Create Java double from Python float.

177

178

Args:

179

value: Python float (64-bit precision)

180

"""

181

```

182

183

## Usage Examples

184

185

### String Conversion

186

187

```python

188

import jpype

189

190

jpype.startJVM()

191

192

# Automatic string conversion (default)

193

java_string = jpype.java.lang.String("Hello from Python")

194

print(type(java_string)) # <class 'str'> (converted back to Python)

195

196

# Explicit Java string creation

197

explicit_string = jpype.JString("Hello Java")

198

print(type(explicit_string)) # <class 'jpype._jstring.str'>

199

200

# String operations

201

java_str = jpype.java.lang.String("Test")

202

print(java_str.length()) # 4

203

print(java_str.toUpperCase()) # "TEST"

204

205

jpype.shutdownJVM()

206

```

207

208

### Primitive Type Conversion

209

210

```python

211

import jpype

212

213

jpype.startJVM()

214

215

# Automatic conversion (JPype chooses appropriate Java type)

216

result = jpype.java.lang.Math.abs(-42) # int -> int

217

pi = jpype.java.lang.Math.PI # double -> float

218

219

# Explicit primitive type control

220

byte_val = jpype.JByte(127)

221

short_val = jpype.JShort(32000)

222

int_val = jpype.JInt(2000000)

223

long_val = jpype.JLong(9223372036854775807)

224

225

float_val = jpype.JFloat(3.14159)

226

double_val = jpype.JDouble(3.141592653589793)

227

228

boolean_val = jpype.JBoolean(True)

229

char_val = jpype.JChar('A')

230

231

jpype.shutdownJVM()

232

```

233

234

### Array Creation and Manipulation

235

236

```python

237

import jpype

238

239

jpype.startJVM()

240

241

# Create typed arrays

242

int_array_factory = jpype.JArray(jpype.JInt)

243

int_array = int_array_factory([1, 2, 3, 4, 5])

244

245

string_array_factory = jpype.JArray(jpype.java.lang.String)

246

string_array = string_array_factory(["hello", "world"])

247

248

# Multi-dimensional arrays

249

int_matrix_factory = jpype.JArray(jpype.JInt, 2)

250

int_matrix = int_matrix_factory([[1, 2], [3, 4]])

251

252

# Array access

253

print(int_array[0]) # 1

254

print(len(int_array)) # 5

255

256

# Convert back to Python

257

python_list = list(int_array)

258

print(python_list) # [1, 2, 3, 4, 5]

259

260

jpype.shutdownJVM()

261

```

262

263

### Working with Collections

264

265

```python

266

import jpype

267

268

jpype.startJVM()

269

270

# Create Java collections with proper types

271

ArrayList = jpype.java.util.ArrayList

272

HashMap = jpype.java.util.HashMap

273

274

# String list

275

string_list = ArrayList()

276

string_list.add(jpype.JString("item1"))

277

string_list.add(jpype.JString("item2"))

278

279

# Integer list with explicit typing

280

int_list = ArrayList()

281

int_list.add(jpype.JInt(10))

282

int_list.add(jpype.JInt(20))

283

284

# Hash map with mixed types

285

map_obj = HashMap()

286

map_obj.put(jpype.JString("key1"), jpype.JInt(100))

287

map_obj.put(jpype.JString("key2"), jpype.JDouble(3.14))

288

289

jpype.shutdownJVM()

290

```

291

292

### Exception Handling

293

294

```python

295

import jpype

296

297

jpype.startJVM()

298

299

try:

300

# This will raise a Java exception

301

string_obj = jpype.java.lang.String("test")

302

char = string_obj.charAt(10) # Index out of bounds

303

except jpype.JException as e:

304

print(f"Java exception caught: {e}")

305

print(f"Exception type: {type(e)}")

306

307

# Catching specific Java exceptions

308

try:

309

jpype.java.lang.Integer.parseInt("not_a_number")

310

except jpype.java.lang.NumberFormatException as e:

311

print(f"Number format error: {e}")

312

313

jpype.shutdownJVM()

314

```

315

316

### Type Checking and Casting

317

318

```python

319

import jpype

320

321

jpype.startJVM()

322

323

# Type checking

324

obj = jpype.java.lang.String("test")

325

print(isinstance(obj, jpype.JObject)) # True

326

print(isinstance(obj, str)) # True (automatic conversion)

327

328

# Explicit casting for interfaces

329

list_obj = jpype.java.util.ArrayList()

330

collection = jpype.JObject(list_obj, jpype.java.util.Collection)

331

332

# Check Java types

333

String = jpype.java.lang.String

334

string_obj = String("hello")

335

print(string_obj.getClass().getName()) # "java.lang.String"

336

337

jpype.shutdownJVM()

338

```

339

340

### Custom Type Conversions

341

342

```python

343

import jpype

344

345

jpype.startJVM()

346

347

# Convert Python data structures to Java

348

python_dict = {"name": "John", "age": 30}

349

350

# Manual conversion to Java HashMap

351

HashMap = jpype.java.util.HashMap

352

java_map = HashMap()

353

for key, value in python_dict.items():

354

java_map.put(jpype.JString(key), jpype.JObject(value))

355

356

# Convert back to Python

357

python_dict_back = {}

358

for key in java_map.keySet():

359

python_dict_back[str(key)] = java_map.get(key)

360

361

jpype.shutdownJVM()

362

```