GraalVM Polyglot API for embedding multiple programming languages in Java applications with secure language interoperability
npx @tessl/cli install tessl/maven-org-graalvm-polyglot--polyglot@25.0.00
# GraalVM Polyglot API
1
2
The GraalVM Polyglot API provides a comprehensive framework for embedding multiple programming languages in Java applications. It enables secure, high-performance polyglot programming with seamless language interoperability, allowing Java applications to execute code in languages like JavaScript, Python, R, Ruby, and LLVM-based languages while maintaining security boundaries and sharing data efficiently.
3
4
## Package Information
5
6
- **Package Name**: org.graalvm.polyglot:polyglot
7
- **Package Type**: Maven
8
- **Language**: Java (JDK 17+)
9
- **Installation**: Add to Maven dependencies: `<groupId>org.graalvm.polyglot</groupId><artifactId>polyglot</artifactId><version>25.0.0</version>`
10
11
## Core Imports
12
13
```java
14
import org.graalvm.polyglot.Context;
15
import org.graalvm.polyglot.Engine;
16
import org.graalvm.polyglot.Value;
17
import org.graalvm.polyglot.Source;
18
```
19
20
## Basic Usage
21
22
```java
23
import org.graalvm.polyglot.*;
24
25
// Create a context for JavaScript execution
26
try (Context context = Context.create("js")) {
27
// Execute JavaScript code
28
Value result = context.eval("js", "40 + 2");
29
System.out.println("Result: " + result.asInt()); // 42
30
31
// Work with polyglot values
32
context.getBindings("js").putMember("javaNumber", 123);
33
Value jsFunction = context.eval("js", "(function(x) { return x * 2; })");
34
Value doubled = jsFunction.execute(result);
35
System.out.println("Doubled: " + doubled.asInt()); // 84
36
}
37
38
// Create an engine for reuse across contexts
39
try (Engine engine = Engine.create()) {
40
Context.Builder builder = Context.newBuilder()
41
.engine(engine)
42
.allowHostAccess(HostAccess.ALL)
43
.allowPolyglotAccess(PolyglotAccess.ALL);
44
45
try (Context context = builder.build()) {
46
// Share Java objects with guest languages
47
MyJavaObject javaObj = new MyJavaObject();
48
context.getBindings("js").putMember("javaObj", javaObj);
49
context.eval("js", "javaObj.someMethod('hello from JS')");
50
}
51
}
52
```
53
54
## Architecture
55
56
The GraalVM Polyglot API is built around several key components:
57
58
- **Engine**: Central execution engine managing language implementations, shared caches, and instrument coordination
59
- **Context**: Isolated execution environment for polyglot code with configurable security and resource policies
60
- **Value**: Universal representation for values exchanged between languages, supporting all data types and operations
61
- **Source**: Abstraction for executable source code with metadata support and caching capabilities
62
- **Proxy System**: Interfaces enabling Java objects to be seamlessly used in guest languages with custom behaviors
63
- **Security Framework**: Comprehensive access controls for host system resources, cross-language interactions, and sandboxing
64
- **I/O Abstraction**: Pluggable file systems, process handlers, and message transports for controlled environment interaction
65
66
## Capabilities
67
68
### Context Management
69
70
Core context creation and lifecycle management for polyglot execution environments. Provides isolated execution spaces with configurable security policies, resource limits, and language access controls.
71
72
```java { .api }
73
public final class Context implements AutoCloseable {
74
// Static factory methods
75
public static Context create(String... permittedLanguages);
76
public static Context.Builder newBuilder(String... permittedLanguages);
77
public static Context getCurrent();
78
79
// Evaluation methods
80
public Value eval(String languageId, CharSequence source);
81
public Value eval(Source source);
82
public Value parse(String languageId, CharSequence source);
83
public Value parse(Source source);
84
85
// Bindings and initialization
86
public Value getBindings(String languageId);
87
public Value getPolyglotBindings();
88
public boolean initialize(String languageId);
89
90
// Value conversion
91
public Value asValue(Object hostValue);
92
93
// Context lifecycle and thread management
94
public void enter();
95
public void leave();
96
public void close();
97
public void close(boolean cancelIfExecuting);
98
public void interrupt(Duration timeout) throws TimeoutException;
99
public void safepoint();
100
101
// Resource management
102
public void resetLimits();
103
public Engine getEngine();
104
}
105
```
106
107
[Context Management](./context-management.md)
108
109
### Engine Management
110
111
Engine creation and management for shared polyglot execution infrastructure. Engines coordinate multiple contexts, manage compilation caches, and provide access to installed languages and instruments.
112
113
```java { .api }
114
public final class Engine implements AutoCloseable {
115
// Static factory methods
116
public static Engine create();
117
public static Engine create(String... permittedLanguages);
118
public static Engine.Builder newBuilder();
119
public static Engine.Builder newBuilder(String... permittedLanguages);
120
public static Path findHome();
121
public static boolean copyResources(Path targetFolder, String... components) throws IOException;
122
123
// Engine information
124
public Map<String, Language> getLanguages();
125
public Map<String, Instrument> getInstruments();
126
public OptionDescriptors getOptions();
127
public String getVersion();
128
public String getImplementationName();
129
130
// Cache operations
131
public Set<Source> getCachedSources();
132
public boolean storeCache(Path targetFile) throws UnsupportedOperationException;
133
public boolean storeCache(Path targetFile, WordPointer cancelledWord) throws CancellationException, UnsupportedOperationException;
134
135
// Engine lifecycle
136
public void close();
137
public void close(boolean cancelIfExecuting);
138
}
139
```
140
141
[Engine Management](./engine-management.md)
142
143
### Value Operations
144
145
Universal value representation and manipulation for cross-language data exchange. Values provide unified access to all language types including objects, arrays, functions, and primitives with automatic type conversions.
146
147
```java { .api }
148
public final class Value extends AbstractValue {
149
// Type checking
150
public boolean isNull();
151
public boolean isBoolean();
152
public boolean isNumber();
153
public boolean isString();
154
public boolean isDate();
155
public boolean isTime();
156
public boolean isTimeZone();
157
public boolean isInstant();
158
public boolean isDuration();
159
public boolean isHostObject();
160
public boolean isProxyObject();
161
public boolean isNativePointer();
162
public boolean isException();
163
public boolean isMetaObject();
164
public boolean isScope();
165
166
// Value conversion - basic types
167
public boolean asBoolean();
168
public String asString();
169
public byte asByte();
170
public short asShort();
171
public int asInt();
172
public long asLong();
173
public BigInteger asBigInteger();
174
public float asFloat();
175
public double asDouble();
176
public <T> T asHostObject();
177
public long asNativePointer();
178
179
// Advanced type fitting checks
180
public boolean fitsInByte();
181
public boolean fitsInShort();
182
public boolean fitsInInt();
183
public boolean fitsInLong();
184
public boolean fitsInBigInteger();
185
public boolean fitsInFloat();
186
public boolean fitsInDouble();
187
188
// Date/Time conversion
189
public LocalDate asDate();
190
public LocalTime asTime();
191
public ZoneId asTimeZone();
192
public Instant asInstant();
193
public Duration asDuration();
194
195
// Advanced conversion
196
public <T> T as(Class<T> targetType);
197
public <T> T as(TypeLiteral<T> targetType);
198
199
// Member operations
200
public boolean hasMembers();
201
public Object getMemberKeys();
202
public Value getMember(String key);
203
public boolean hasMember(String key);
204
public void putMember(String key, Object value);
205
public boolean removeMember(String key);
206
207
// Array operations
208
public boolean hasArrayElements();
209
public Value getArrayElement(long index);
210
public void setArrayElement(long index, Object value);
211
public boolean removeArrayElement(long index);
212
public long getArraySize();
213
214
// Buffer operations
215
public boolean hasBufferElements();
216
public boolean isBufferWritable();
217
public long getBufferSize();
218
public byte readBufferByte(long byteOffset);
219
public void writeBufferByte(long byteOffset, byte value);
220
// ... additional buffer read/write methods for other primitive types with ByteOrder
221
222
// Execution
223
public boolean canExecute();
224
public Value execute(Object... arguments);
225
public boolean canInstantiate();
226
public Value newInstance(Object... arguments);
227
228
// Iterator operations
229
public boolean hasIterator();
230
public Value getIterator();
231
public boolean isIterator();
232
public boolean hasIteratorNextElement();
233
public Value getIteratorNextElement();
234
235
// Hash/Map operations
236
public boolean hasHashEntries();
237
public long getHashSize();
238
public boolean hasHashEntry(Object key);
239
public Value getHashValue(Object key);
240
public Value getHashValueOrDefault(Object key, Object defaultValue);
241
public void putHashEntry(Object key, Object value);
242
public boolean removeHashEntry(Object key);
243
public Value getHashEntriesIterator();
244
public Value getHashKeysIterator();
245
public Value getHashValuesIterator();
246
247
// Meta-object operations
248
public Value getMetaObject();
249
public String getMetaQualifiedName();
250
public String getMetaSimpleName();
251
public boolean isMetaInstance(Object instance);
252
public boolean hasMetaParents();
253
public Value getMetaParents();
254
255
// Exception handling
256
public RuntimeException throwException();
257
258
// Scoped values
259
public Value pin();
260
}
261
```
262
263
[Value Operations](./value-operations.md)
264
265
### Source Management
266
267
Source code representation and management for polyglot execution. Provides creation from various inputs, metadata handling, and caching support for optimal performance.
268
269
```java { .api }
270
public final class Source {
271
public static Source create(String language, CharSequence source);
272
public static Source.Builder newBuilder(String language, File file);
273
public static Source.Builder newBuilder(String language, URL url);
274
public static Source.Builder newBuilder(String language, Reader source, String name);
275
public CharSequence getCharacters();
276
public String getName();
277
public String getMimeType();
278
public String getLanguage();
279
}
280
```
281
282
[Source Management](./source-management.md)
283
284
### Security Configuration
285
286
Comprehensive security and access control configuration for polyglot environments. Enables fine-grained control over host system access, cross-language interactions, and resource consumption.
287
288
```java { .api }
289
public final class HostAccess {
290
public static final HostAccess ALL;
291
public static final HostAccess EXPLICIT;
292
public static final HostAccess SCOPED;
293
public static final HostAccess NONE;
294
public static final HostAccess CONSTRAINED;
295
public static final HostAccess ISOLATED;
296
public static final HostAccess UNTRUSTED;
297
public static HostAccess.Builder newBuilder();
298
public static HostAccess.Builder newBuilder(HostAccess prototype);
299
}
300
301
public final class PolyglotAccess {
302
public static final PolyglotAccess ALL;
303
public static final PolyglotAccess NONE;
304
public static PolyglotAccess.Builder newBuilder();
305
}
306
307
public final class IOAccess {
308
public static final IOAccess ALL;
309
public static final IOAccess NONE;
310
public static IOAccess.Builder newBuilder();
311
public static IOAccess.Builder newBuilder(IOAccess prototype);
312
}
313
314
public enum SandboxPolicy {
315
TRUSTED, CONSTRAINED, ISOLATED, UNTRUSTED
316
}
317
```
318
319
[Security Configuration](./security-configuration.md)
320
321
### Proxy System
322
323
Interfaces for exposing Java objects to guest languages with customizable behaviors. Enables seamless integration of Java objects into polyglot environments with support for object members, arrays, functions, and specialized types.
324
325
```java { .api }
326
public interface Proxy {
327
// Base marker interface for all proxy types
328
}
329
330
public interface ProxyObject extends Proxy {
331
Object getMember(String key);
332
Object getMemberKeys();
333
boolean hasMember(String key);
334
void putMember(String key, Value value);
335
default boolean removeMember(String key) { return false; }
336
}
337
338
public interface ProxyExecutable extends Proxy {
339
Object execute(Value... arguments);
340
}
341
342
public interface ProxyInstantiable extends Proxy {
343
Object newInstance(Value... arguments);
344
}
345
346
public interface ProxyArray extends Proxy {
347
Object get(long index);
348
void set(long index, Value value);
349
long getSize();
350
default boolean remove(long index) { return false; }
351
}
352
353
public interface ProxyIterable extends Proxy {
354
Object getIterator();
355
}
356
357
public interface ProxyIterator extends Proxy {
358
boolean hasIteratorNextElement();
359
Object getIteratorNextElement();
360
}
361
362
public interface ProxyHashMap extends Proxy {
363
long getHashSize();
364
boolean hasHashEntry(Object key);
365
Object getHashValue(Object key);
366
void putHashEntry(Object key, Value value);
367
boolean removeHashEntry(Object key);
368
Object getHashEntriesIterator();
369
}
370
371
public interface ProxyNativeObject extends Proxy {
372
// Native object representation
373
}
374
375
// Temporal proxy interfaces
376
public interface ProxyDate extends Proxy {
377
LocalDate asDate();
378
}
379
380
public interface ProxyTime extends Proxy {
381
LocalTime asTime();
382
}
383
384
public interface ProxyTimeZone extends Proxy {
385
ZoneId asTimeZone();
386
}
387
388
public interface ProxyInstant extends Proxy {
389
Instant asInstant();
390
}
391
392
public interface ProxyDuration extends Proxy {
393
Duration asDuration();
394
}
395
```
396
397
[Proxy System](./proxy-system.md)
398
399
### I/O Abstractions
400
401
Pluggable I/O system for controlled file system access, process execution, and message communication. Enables sandboxed environments with custom I/O behavior while maintaining security boundaries.
402
403
```java { .api }
404
public interface FileSystem {
405
Path parsePath(URI uri);
406
void checkAccess(Path path, Set<AccessMode> modes);
407
void createDirectory(Path dir);
408
SeekableByteChannel newByteChannel(Path path, Set<OpenOption> options);
409
DirectoryStream<Path> newDirectoryStream(Path dir);
410
}
411
412
public interface ProcessHandler {
413
Process start(ProcessCommand command);
414
}
415
416
public interface MessageTransport {
417
MessageEndpoint open(URI uri, MessageEndpoint endpoint);
418
}
419
420
public final class IOHelper {
421
// Utility methods for I/O operations
422
public static FileSystem newDefaultFileSystem();
423
public static ProcessHandler newDefaultProcessHandler();
424
}
425
```
426
427
[I/O Abstractions](./io-abstractions.md)
428
429
### Execution Monitoring
430
431
Advanced execution monitoring and instrumentation capabilities for polyglot environments. Provides detailed execution events, performance metrics, and debugging support across all supported languages.
432
433
```java { .api }
434
public final class ExecutionListener implements AutoCloseable {
435
public static ExecutionListener.Builder newBuilder();
436
public ExecutionListener attach(Engine engine);
437
public void close();
438
}
439
440
public final class ExecutionEvent {
441
public SourceSection getLocation();
442
public Value getReturnValue();
443
public RuntimeException getException();
444
public List<Value> getInputValues();
445
}
446
```
447
448
[Execution Monitoring](./execution-monitoring.md)
449
450
## Types
451
452
```java { .api }
453
public final class Language {
454
public String getId();
455
public String getName();
456
public String getImplementationName();
457
public String getVersion();
458
public Set<String> getMimeTypes();
459
public OptionValues getOptions();
460
}
461
462
public final class Instrument {
463
public String getId();
464
public String getName();
465
public String getVersion();
466
public OptionValues getOptions();
467
public <T> T lookup(Class<T> type);
468
}
469
470
public final class PolyglotException extends RuntimeException {
471
public boolean isGuestException();
472
public boolean isHostException();
473
public RuntimeException asHostException();
474
public Value getGuestObject();
475
public StackTraceElement[] getPolyglotStackTrace();
476
public SourceSection getSourceLocation();
477
}
478
479
public final class SourceSection {
480
public Source getSource();
481
public int getStartLine();
482
public int getEndLine();
483
public int getStartColumn();
484
public int getEndColumn();
485
public CharSequence getCharacters();
486
}
487
488
public final class ResourceLimits {
489
public static ResourceLimits.Builder newBuilder();
490
}
491
492
public final class ResourceLimitEvent {
493
public String getLimit();
494
public Context getContext();
495
}
496
497
public final class EnvironmentAccess {
498
public static final EnvironmentAccess INHERIT;
499
public static final EnvironmentAccess NONE;
500
public static EnvironmentAccess.Builder newBuilder();
501
}
502
503
public final class TypeLiteral<T> {
504
// Factory and utility methods for generic type handling
505
}
506
507
public interface ByteSequence {
508
byte byteAt(int index);
509
int length();
510
ByteSequence subSequence(int start, int end);
511
byte[] toByteArray();
512
}
513
514
public final class ByteArraySequence implements ByteSequence {
515
public static ByteSequence create(byte[] buffer);
516
public static ByteSequence create(byte[] buffer, int byteOffset, int length);
517
}
518
519
public interface MessageEndpoint {
520
MessageEndpoint open(URI uri, MessageEndpoint endpoint) throws IOException;
521
void sendText(String text) throws IOException;
522
void sendBinary(ByteBuffer data) throws IOException;
523
void sendPing(ByteBuffer data) throws IOException;
524
void sendPong(ByteBuffer data) throws IOException;
525
void sendClose();
526
}
527
```