0
# Value Operations
1
2
Value operations provide the universal interface for working with Python objects from Java. The Value class serves as a language-agnostic wrapper that enables type-safe access to Python values, with automatic conversion capabilities and comprehensive object manipulation methods.
3
4
## Capabilities
5
6
### Type Checking
7
8
Determine the type of Python values for safe conversion and manipulation.
9
10
```java { .api }
11
/**
12
* Checks if the value represents null/None
13
* @return true if the value is null/None
14
*/
15
public boolean isNull();
16
17
/**
18
* Checks if the value represents a number (int, float, complex)
19
* @return true if the value is a numeric type
20
*/
21
public boolean isNumber();
22
23
/**
24
* Checks if the value represents a boolean
25
* @return true if the value is a boolean
26
*/
27
public boolean isBoolean();
28
29
/**
30
* Checks if the value represents a string
31
* @return true if the value is a string
32
*/
33
public boolean isString();
34
35
/**
36
* Checks if the value represents a date object
37
* @return true if the value is a date
38
*/
39
public boolean isDate();
40
41
/**
42
* Checks if the value represents a time object
43
* @return true if the value is a time
44
*/
45
public boolean isTime();
46
47
/**
48
* Checks if the value represents a timezone
49
* @return true if the value is a timezone
50
*/
51
public boolean isTimeZone();
52
53
/**
54
* Checks if the value represents a duration
55
* @return true if the value is a duration
56
*/
57
public boolean isDuration();
58
59
/**
60
* Checks if the value is a Java host object
61
* @return true if the value is a host object
62
*/
63
public boolean isHostObject();
64
65
/**
66
* Checks if the value is a proxy object
67
* @return true if the value is a proxy
68
*/
69
public boolean isProxyObject();
70
71
/**
72
* Checks if the value represents a native pointer
73
* @return true if the value is a native pointer
74
*/
75
public boolean isNativePointer();
76
77
/**
78
* Checks if the value represents an exception
79
* @return true if the value is an exception
80
*/
81
public boolean isException();
82
83
/**
84
* Checks if the value is a meta-object (type/class)
85
* @return true if the value is a meta-object
86
*/
87
public boolean isMetaObject();
88
89
/**
90
* Checks if the value is an iterator
91
* @return true if the value is an iterator
92
*/
93
public boolean isIterator();
94
```
95
96
**Usage Examples:**
97
98
```java
99
Value pythonValue = context.eval("python", "42");
100
if (pythonValue.isNumber()) {
101
int number = pythonValue.asInt();
102
}
103
104
Value pythonList = context.eval("python", "[1, 2, 3]");
105
if (pythonList.hasArrayElements()) {
106
long size = pythonList.getArraySize(); // 3
107
}
108
109
Value pythonDict = context.eval("python", "{'name': 'Alice', 'age': 30}");
110
if (pythonDict.hasMembers()) {
111
Set<String> keys = pythonDict.getMemberKeys(); // ["name", "age"]
112
}
113
```
114
115
### Value Conversion
116
117
Convert Python values to Java types with automatic type coercion.
118
119
```java { .api }
120
/**
121
* Converts to Java boolean
122
* @return boolean representation
123
* @throws ClassCastException if conversion fails
124
*/
125
public boolean asBoolean();
126
127
/**
128
* Converts to Java byte
129
* @return byte representation
130
* @throws ClassCastException if conversion fails
131
*/
132
public byte asByte();
133
134
/**
135
* Converts to Java short
136
* @return short representation
137
* @throws ClassCastException if conversion fails
138
*/
139
public short asShort();
140
141
/**
142
* Converts to Java int
143
* @return int representation
144
* @throws ClassCastException if conversion fails
145
*/
146
public int asInt();
147
148
/**
149
* Converts to Java long
150
* @return long representation
151
* @throws ClassCastException if conversion fails
152
*/
153
public long asLong();
154
155
/**
156
* Converts to Java BigInteger
157
* @return BigInteger representation
158
* @throws ClassCastException if conversion fails
159
*/
160
public BigInteger asBigInteger();
161
162
/**
163
* Converts to Java float
164
* @return float representation
165
* @throws ClassCastException if conversion fails
166
*/
167
public float asFloat();
168
169
/**
170
* Converts to Java double
171
* @return double representation
172
* @throws ClassCastException if conversion fails
173
*/
174
public double asDouble();
175
176
/**
177
* Converts to Java String
178
* @return String representation
179
* @throws ClassCastException if conversion fails
180
*/
181
public String asString();
182
183
/**
184
* Converts to original Java host object
185
* @param <T> the expected type
186
* @return the original host object
187
* @throws ClassCastException if not a host object or wrong type
188
*/
189
public <T> T asHostObject();
190
191
/**
192
* Converts to specific Java type with type coercion
193
* @param <T> target type
194
* @param targetType the target class
195
* @return converted value
196
* @throws ClassCastException if conversion fails
197
*/
198
public <T> T as(Class<T> targetType);
199
200
/**
201
* Converts using generic type literal for complex types
202
* @param <T> target type
203
* @param targetType TypeLiteral describing the target type
204
* @return converted value
205
* @throws ClassCastException if conversion fails
206
*/
207
public <T> T as(TypeLiteral<T> targetType);
208
```
209
210
**Usage Examples:**
211
212
```java
213
// Numeric conversions
214
Value intValue = context.eval("python", "42");
215
int javaInt = intValue.asInt(); // 42
216
double javaDouble = intValue.asDouble(); // 42.0
217
218
Value floatValue = context.eval("python", "3.14159");
219
float javaFloat = floatValue.asFloat(); // 3.14159f
220
221
// String conversion
222
Value stringValue = context.eval("python", "'Hello, World!'");
223
String javaString = stringValue.asString(); // "Hello, World!"
224
225
// Boolean conversion
226
Value boolValue = context.eval("python", "True");
227
boolean javaBool = boolValue.asBoolean(); // true
228
229
// Complex type conversion
230
Value pythonList = context.eval("python", "[1, 2, 3, 4, 5]");
231
List<Integer> javaList = pythonList.as(new TypeLiteral<List<Integer>>() {});
232
233
// Host object retrieval
234
context.getPolyglotBindings().putMember("javaObject", new ArrayList<>());
235
Value hostValue = context.eval("python", "polyglot.import_value('javaObject')");
236
ArrayList<?> originalList = hostValue.asHostObject();
237
```
238
239
### Member Access
240
241
Access and manipulate attributes of Python objects.
242
243
```java { .api }
244
/**
245
* Checks if the value has members (attributes/properties)
246
* @return true if the value has accessible members
247
*/
248
public boolean hasMembers();
249
250
/**
251
* Gets a member by key
252
* @param key the member name
253
* @return Value representing the member
254
* @throws UnsupportedOperationException if no members
255
*/
256
public Value getMember(String key);
257
258
/**
259
* Checks if a specific member exists
260
* @param key the member name
261
* @return true if the member exists
262
*/
263
public boolean hasMember(String key);
264
265
/**
266
* Sets a member value
267
* @param key the member name
268
* @param value the value to set
269
* @throws UnsupportedOperationException if members not writable
270
*/
271
public void putMember(String key, Object value);
272
273
/**
274
* Removes a member
275
* @param key the member name
276
* @return true if the member was removed
277
* @throws UnsupportedOperationException if members not removable
278
*/
279
public boolean removeMember(String key);
280
281
/**
282
* Gets all member keys
283
* @return Set of member names
284
* @throws UnsupportedOperationException if no members
285
*/
286
public Set<String> getMemberKeys();
287
```
288
289
**Usage Examples:**
290
291
```java
292
// Python object attribute access
293
context.eval("python", """
294
class Person:
295
def __init__(self, name, age):
296
self.name = name
297
self.age = age
298
def greet(self):
299
return f"Hi, I'm {self.name}"
300
301
person = Person("Alice", 30)
302
""");
303
304
Value person = context.getBindings("python").getMember("person");
305
306
// Get attributes
307
Value name = person.getMember("name");
308
String nameStr = name.asString(); // "Alice"
309
310
Value age = person.getMember("age");
311
int ageInt = age.asInt(); // 30
312
313
// Call methods
314
Value greetMethod = person.getMember("greet");
315
Value greeting = greetMethod.execute();
316
String greetingStr = greeting.asString(); // "Hi, I'm Alice"
317
318
// Set attributes
319
person.putMember("email", "alice@example.com");
320
321
// List all attributes
322
Set<String> memberKeys = person.getMemberKeys();
323
// Contains: name, age, greet, email, etc.
324
325
// Check attribute existence
326
boolean hasName = person.hasMember("name"); // true
327
boolean hasPhone = person.hasMember("phone"); // false
328
329
// Dictionary access
330
Value pythonDict = context.eval("python", "{'x': 10, 'y': 20}");
331
Value x = pythonDict.getMember("x"); // 10
332
pythonDict.putMember("z", 30);
333
```
334
335
### Array Operations
336
337
Work with Python sequences and lists as arrays.
338
339
```java { .api }
340
/**
341
* Checks if the value has array elements
342
* @return true if the value is array-like
343
*/
344
public boolean hasArrayElements();
345
346
/**
347
* Gets an array element by index
348
* @param index the element index (0-based)
349
* @return Value representing the element
350
* @throws UnsupportedOperationException if not array-like
351
* @throws InvalidArrayIndexException if index invalid
352
*/
353
public Value getArrayElement(long index);
354
355
/**
356
* Sets an array element
357
* @param index the element index
358
* @param value the value to set
359
* @throws UnsupportedOperationException if not array-like or not writable
360
*/
361
public void setArrayElement(long index, Object value);
362
363
/**
364
* Removes an array element
365
* @param index the element index
366
* @return true if the element was removed
367
* @throws UnsupportedOperationException if not removable
368
*/
369
public boolean removeArrayElement(long index);
370
371
/**
372
* Gets the array size
373
* @return number of array elements
374
* @throws UnsupportedOperationException if not array-like
375
*/
376
public long getArraySize();
377
```
378
379
**Usage Examples:**
380
381
```java
382
// Python list operations
383
Value pythonList = context.eval("python", "[10, 20, 30, 40, 50]");
384
385
// Check if it's array-like
386
if (pythonList.hasArrayElements()) {
387
long size = pythonList.getArraySize(); // 5
388
389
// Get elements
390
Value firstElement = pythonList.getArrayElement(0);
391
int first = firstElement.asInt(); // 10
392
393
Value lastElement = pythonList.getArrayElement(size - 1);
394
int last = lastElement.asInt(); // 50
395
396
// Set elements
397
pythonList.setArrayElement(2, 999);
398
// List is now [10, 20, 999, 40, 50]
399
400
// Iterate through elements
401
for (long i = 0; i < size; i++) {
402
Value element = pythonList.getArrayElement(i);
403
System.out.println("Element " + i + ": " + element.asString());
404
}
405
}
406
407
// Tuple operations
408
Value pythonTuple = context.eval("python", "(1, 'hello', 3.14)");
409
long tupleSize = pythonTuple.getArraySize(); // 3
410
Value stringElement = pythonTuple.getArrayElement(1);
411
String str = stringElement.asString(); // "hello"
412
413
// String as character array
414
Value pythonString = context.eval("python", "'Hello'");
415
if (pythonString.hasArrayElements()) {
416
long length = pythonString.getArraySize(); // 5
417
Value firstChar = pythonString.getArrayElement(0);
418
String ch = firstChar.asString(); // "H"
419
}
420
```
421
422
### Function Execution
423
424
Execute Python functions and callable objects.
425
426
```java { .api }
427
/**
428
* Checks if the value is executable (callable)
429
* @return true if the value can be executed
430
*/
431
public boolean canExecute();
432
433
/**
434
* Executes the callable with arguments
435
* @param arguments the arguments to pass
436
* @return Value representing the execution result
437
* @throws UnsupportedOperationException if not executable
438
* @throws PolyglotException if execution fails
439
*/
440
public Value execute(Object... arguments);
441
442
/**
443
* Checks if the value can be instantiated (is a constructor)
444
* @return true if the value can create new instances
445
*/
446
public boolean canInstantiate();
447
448
/**
449
* Creates a new instance using this value as constructor
450
* @param arguments the constructor arguments
451
* @return Value representing the new instance
452
* @throws UnsupportedOperationException if not instantiable
453
* @throws PolyglotException if instantiation fails
454
*/
455
public Value newInstance(Object... arguments);
456
```
457
458
**Usage Examples:**
459
460
```java
461
// Python function execution
462
context.eval("python", """
463
def add(a, b):
464
return a + b
465
466
def greet(name, greeting="Hello"):
467
return f"{greeting}, {name}!"
468
469
class Calculator:
470
def __init__(self, name):
471
self.name = name
472
def multiply(self, a, b):
473
return a * b
474
""");
475
476
Value bindings = context.getBindings("python");
477
478
// Execute functions
479
Value addFunc = bindings.getMember("add");
480
if (addFunc.canExecute()) {
481
Value result = addFunc.execute(5, 3);
482
int sum = result.asInt(); // 8
483
}
484
485
Value greetFunc = bindings.getMember("greet");
486
Value greeting1 = greetFunc.execute("Alice");
487
String msg1 = greeting1.asString(); // "Hello, Alice!"
488
489
Value greeting2 = greetFunc.execute("Bob", "Hi");
490
String msg2 = greeting2.asString(); // "Hi, Bob!"
491
492
// Class instantiation
493
Value calculatorClass = bindings.getMember("Calculator");
494
if (calculatorClass.canInstantiate()) {
495
Value calculator = calculatorClass.newInstance("MyCalc");
496
497
// Call instance methods
498
Value multiplyMethod = calculator.getMember("multiply");
499
Value product = multiplyMethod.execute(6, 7);
500
int result = product.asInt(); // 42
501
}
502
503
// Built-in function execution
504
Value lenFunc = bindings.getMember("len");
505
Value listLen = lenFunc.execute(Arrays.asList(1, 2, 3, 4));
506
int length = listLen.asInt(); // 4
507
508
// Lambda execution
509
Value pythonLambda = context.eval("python", "lambda x: x ** 2");
510
Value squared = pythonLambda.execute(5);
511
int result = squared.asInt(); // 25
512
```
513
514
### Iterator Operations
515
516
Work with Python iterators and iterables.
517
518
```java { .api }
519
/**
520
* Checks if the value is an iterator
521
* @return true if the value is an iterator
522
*/
523
public boolean isIterator();
524
525
/**
526
* Checks if the value is iterable
527
* @return true if the value can produce an iterator
528
*/
529
public boolean hasIterator();
530
531
/**
532
* Gets an iterator for this iterable value
533
* @return Value representing the iterator
534
* @throws UnsupportedOperationException if not iterable
535
*/
536
public Value getIterator();
537
538
/**
539
* Checks if the iterator has more elements
540
* @return true if more elements available
541
* @throws UnsupportedOperationException if not an iterator
542
*/
543
public boolean hasIteratorNextElement();
544
545
/**
546
* Gets the next element from the iterator
547
* @return Value representing the next element
548
* @throws UnsupportedOperationException if not an iterator
549
* @throws NoSuchElementException if no more elements
550
*/
551
public Value getIteratorNextElement();
552
```
553
554
**Usage Examples:**
555
556
```java
557
// Iterate over Python list
558
Value pythonList = context.eval("python", "[1, 2, 3, 4, 5]");
559
if (pythonList.hasIterator()) {
560
Value iterator = pythonList.getIterator();
561
while (iterator.hasIteratorNextElement()) {
562
Value element = iterator.getIteratorNextElement();
563
System.out.println(element.asInt());
564
}
565
}
566
567
// Iterate over Python generator
568
context.eval("python", """
569
def fibonacci():
570
a, b = 0, 1
571
while True:
572
yield a
573
a, b = b, a + b
574
575
fib_gen = fibonacci()
576
""");
577
578
Value fibGen = context.getBindings("python").getMember("fib_gen");
579
if (fibGen.hasIterator()) {
580
Value iterator = fibGen.getIterator();
581
// Get first 10 Fibonacci numbers
582
for (int i = 0; i < 10; i++) {
583
if (iterator.hasIteratorNextElement()) {
584
Value fibNumber = iterator.getIteratorNextElement();
585
System.out.println("Fib " + i + ": " + fibNumber.asInt());
586
}
587
}
588
}
589
590
// Dictionary iteration
591
Value pythonDict = context.eval("python", "{'a': 1, 'b': 2, 'c': 3}");
592
Value dictKeys = pythonDict.getMember("keys").execute();
593
if (dictKeys.hasIterator()) {
594
Value keyIterator = dictKeys.getIterator();
595
while (keyIterator.hasIteratorNextElement()) {
596
Value key = keyIterator.getIteratorNextElement();
597
Value value = pythonDict.getMember(key.asString());
598
System.out.println(key.asString() + " -> " + value.asInt());
599
}
600
}
601
```
602
603
## Types
604
605
```java { .api }
606
/**
607
* Type literal for specifying generic types in conversions
608
* @param <T> the generic type
609
*/
610
public abstract class TypeLiteral<T> {
611
/**
612
* Gets the generic type information
613
* @return Type representing the generic type
614
*/
615
public final Type getType();
616
617
/**
618
* Gets the raw class type
619
* @return Class representing the raw type
620
*/
621
public final Class<T> getRawType();
622
}
623
624
/**
625
* Exception thrown when array index is invalid
626
*/
627
public final class InvalidArrayIndexException extends PolyglotException {
628
public long getInvalidIndex();
629
}
630
631
/**
632
* Exception thrown when trying to access members that don't exist
633
*/
634
public final class UnsupportedMessageException extends PolyglotException {
635
public String getUnsupportedMessage();
636
}
637
```