# ⬢ polyglot 25.6.0-elide.4
Every page: [llms.txt](llms.txt), or all in one file: [llms-full.txt](llms-full.txt)
API reference for polyglot.
## Packages
- [`org.graalvm.home`](org/graalvm/home/index.md): The GraalVM SDK home API allows query home paths for the GraalVM, its languages and its tools.
- [`org.graalvm.options`](org/graalvm/options/index.md): The GraalVM SDK options package contains reusable collection classes for options.
- [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md): The GraalVM SDK polyglot API allows to embed Graal languages in Java applications.
- [`org.graalvm.polyglot.io`](org/graalvm/polyglot/io/index.md): Input/Output support for the GraalVM SDK polyglot API.
- [`org.graalvm.polyglot.management`](org/graalvm/polyglot/management/index.md): The management package provides tools that monitor and instrument the behavior of guest language programs.
- [`org.graalvm.polyglot.proxy`](org/graalvm/polyglot/proxy/index.md): The GraalVM SDK proxy interfaces allow to mimic guest language objects, arrays, executables, primitives and native objects in Graal languages.
## Types in `org.graalvm.home`
`HomeFinder`, `Version`
## Types in `org.graalvm.options`
`ConstantOptionKey`, `OptionCategory`, `OptionDescriptor`, `OptionDescriptor.Builder`, `OptionDescriptors`, `OptionKey`, `OptionMap`, `OptionStability`, `OptionType`, `OptionValues`
## Types in `org.graalvm.polyglot`
`Context`, `Context.Builder`, `Engine`, `Engine.Builder`, `Engine.CancellationCallback`, `Engine.Preinitialized`, `EnvironmentAccess`, `HostAccess`, `HostAccess.Builder`, `HostAccess.DisableMethodScoping`, `HostAccess.Export`, `HostAccess.Implementable`, `HostAccess.MutableTargetMapping`, `HostAccess.Optimized`, `HostAccess.TargetMappingPrecedence`, `Instrument`, `Language`, `PolyglotAccess`, `PolyglotAccess.Builder`, `PolyglotException`, `PolyglotException.StackFrame`, `PreinitializedSources`, `ResourceLimitEvent`, `ResourceLimits`, `ResourceLimits.Builder`, `SandboxPolicy`, `Source`, `Source.Builder`, `SourceSection`, `TypeLiteral`, `Value`, `Value.StringEncoding`
## Types in `org.graalvm.polyglot.io`
`ByteSequence`, `FileChannel`, `FileLock`, `FileSystem`, `FileSystem.Selector`, `IOAccess`, `IOAccess.Builder`, `MessageEndpoint`, `MessageTransport`, `MessageTransport.VetoException`, `ProcessHandler`, `ProcessHandler.ProcessCommand`, `ProcessHandler.Redirect`
## Types in `org.graalvm.polyglot.management`
`ExecutionEvent`, `ExecutionListener`, `ExecutionListener.Builder`
## Types in `org.graalvm.polyglot.proxy`
`Proxy`, `ProxyArray`, `ProxyDate`, `ProxyDuration`, `ProxyExecutable`, `ProxyHashMap`, `ProxyInstant`, `ProxyInstantiable`, `ProxyIterable`, `ProxyIterator`, `ProxyNativeObject`, `ProxyObject`, `ProxyTime`, `ProxyTimeZone`
# ▣ org.graalvm.home
[polyglot](index.md) · Every page: [llms.txt](llms.txt)
Package in polyglot. Since 19.3.
The GraalVM SDK home API allows query home paths for the GraalVM, its languages and its tools.
**See also**
- [`for querying home paths.`](org/graalvm/home/HomeFinder.md)
## Classes
- [`HomeFinder`](org/graalvm/home/HomeFinder.md): A utility class to find various paths of the running GraalVM, as well as the version.
- [`Version`](org/graalvm/home/Version.md): A version utility to canonicalize and compare GraalVM versions.
# ◆ HomeFinder
[polyglot](index.md) › [org.graalvm.home](org/graalvm/home/index.md) · Every page: [llms.txt](llms.txt)
Abstract class in [`org.graalvm.home`](org/graalvm/home/index.md). Since 19.3.
```java
public abstract class HomeFinder
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `HomeFinder`
A utility class to find various paths of the running GraalVM, as well as the version. Use [`HomeFinder.getInstance()`](org/graalvm/home/HomeFinder.md#getInstance%28%29) to get the singleton instance.
## Constructors
### HomeFinder()
`public HomeFinder()`. Since 19.3. Cite: `org/graalvm/home/HomeFinder.html#()`
## Methods
### getHomeFolder()
`public abstract Path getHomeFolder()`. Since 19.3. Returns `Path`: the GraalVM home folder if inside GraalVM or `null` otherwise. Cite: `org/graalvm/home/HomeFinder.html#getHomeFolder()`
### getVersion()
`public abstract String getVersion()`. Since 19.3. Returns `String`: the GraalVM version or `"snapshot"` if unknown. Cite: `org/graalvm/home/HomeFinder.html#getVersion()`
### getLanguageHomes()
`public abstract Map getLanguageHomes()`. Since 19.3. Returns `Map`: a Map of language ids to their home path. Cite: `org/graalvm/home/HomeFinder.html#getLanguageHomes()`
### getToolHomes()
`public abstract Map getToolHomes()`. Since 19.3. Returns `Map`: a Map of tool ids to their home path. Cite: `org/graalvm/home/HomeFinder.html#getToolHomes()`
### getInstance()
`public static HomeFinder getInstance()`. Since 19.3. Returns `HomeFinder`: the HomeFinder instance by using a ServiceLoader. Throws: `IllegalStateException` (unchecked): if no implementation could be found. Cite: `org/graalvm/home/HomeFinder.html#getInstance()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`toString`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ Version
[polyglot](index.md) › [org.graalvm.home](org/graalvm/home/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.home`](org/graalvm/home/index.md). Since 19.3.
```java
public final class Version implements Comparable
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `Version`
Implements: [`Comparable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Comparable.html)`<`[`Version`](org/graalvm/home/Version.md)`>`
A version utility to canonicalize and compare GraalVM versions. The GraalVM version string is not standardized and may change without notice. This class is designed to evolve with GraalVM to cover all used version formats in use. It allows to create, validate and compare GraalVM versions. Do not rely on the format of the raw version string or the result of [`toString()`](org/graalvm/home/Version.md#toString%28%29), only use it to produce output for humans.
To create version instances of a particular version use the [`create(int...)`](org/graalvm/home/Version.md#create%28int...%29) factory method. Use [`getCurrent()`](org/graalvm/home/Version.md#getCurrent%28%29) to lookup the current GraalVM version or [`parse(String)`](org/graalvm/home/Version.md#parse%28java.lang.String%29) to parse it from a raw string.
### Usage example:
This code example compares the current GraalVM version to be at least 19.3 and fails if it is not.
```java
if (Version.getCurrent().compareTo(19, 3) < 0) {
throw new IllegalStateException("Invalid GraalVM version. Must be at least 19.3.");
}
```
Note: this class has a natural ordering that is inconsistent with equals.
**See also**
- [`HomeFinder.getVersion()`](org/graalvm/home/HomeFinder.md#getVersion%28%29)
## Methods
### isRelease()
`public boolean isRelease()`. Since 19.3. Returns `true` if this is a supported release build of GraalVM else `false`. Use this for implementation assertions that verify that only releases are deployed to production. See also: `isSnapshot()`. Cite: `org/graalvm/home/Version.html#isRelease()`
### isSnapshot()
`public boolean isSnapshot()`. Since 19.3. Returns `true` if this is an unsupported snapshot build of GraalVM else `false`. Use this for implementation assertions that verify that only releases are deployed to production. See also: `isSnapshot()`. Cite: `org/graalvm/home/Version.html#isSnapshot()`
### compareTo(Version)
`public int compareTo(Version o)`. Since 19.3. Overrides `compareTo(T)`. Cite: `org/graalvm/home/Version.html#compareTo(org.graalvm.home.Version)`
### compareTo(int...)
`public int compareTo(int... compareVersions)`. Since 19.3. Compares this version to another GraalVM version. This is equivalent to using: ` compareTo(Version.create(compareVersions)) `. Cite: `org/graalvm/home/Version.html#compareTo(int...)`
### equals(Object)
`public boolean equals(Object obj)`. Since 19.3. Overrides `equals(java.lang.Object)`. Cite: `org/graalvm/home/Version.html#equals(java.lang.Object)`
### hashCode()
`public int hashCode()`. Since 19.3. Overrides `hashCode()`. Cite: `org/graalvm/home/Version.html#hashCode()`
### toString()
`public String toString()`. Since 19.3. Overrides `toString()`. Cite: `org/graalvm/home/Version.html#toString()`
### format(String)
`public String format(String format)`. Since 23.0. Format the GraalVM version with a custom format string. The format string can contain any of the standard conversions of [`java.util.Formatter`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Formatter.html). At least four version components (possibly zero) are available as formatter arguments. In addition to the standard conversions, these special conversions are available: `"%[R...]"` includes a given part only if `isRelease`; `"%[S...]"` includes a given part only if `isSnapshot`; `"%[...]"` includes a given part only if the version contains at least `` non-zero version components (`` can be 0 to 9) Examples: Cite: `org/graalvm/home/Version.html#format(java.lang.String)`
```java
Version.parse("22.3.0.1").format("%d.%d"); // returns "22.3"
Version.parse("22.3.0.1").format("%4$d"); // returns "1"
Version.parse("22.3.0.1").format("%[R%d.%d]%[Sdev]"); // returns "22.3"
Version.parse("22.3.0.1").format("%[2XX]"); // returns "XX"
Version.parse("23.0-dev").format("%3$d"); // returns "0"
Version.parse("23.0-dev").format("%[R%d.%d]%[Sdev]"); // returns "dev"
Version.parse("23.0-dev").format("%[2XX]"); // returns ""
```
### getComponent(int)
`public int getComponent(int componentIndex)`. Since 24.2. Retrieves the numeric value of the version component at the specified index. Version components are indexed as follows: `componentIndex = 0` represents the major version; `componentIndex = 1` represents the minor version; `componentIndex = 2` represents the update version If the specified `componentIndex` exceeds the number of available components, the method returns `0`. For example, a version `23.1` will return `0` for `componentIndex = 2`. Parameters: `componentIndex` `int`: the index of the version component to retrieve; must be non-negative. Throws: `IllegalArgumentException` (unchecked): if `componentIndex` is negative. See also: `Version.create(int...)`. Cite: `org/graalvm/home/Version.html#getComponent(int)`
### parse(String)
`public static Version parse(String versionString) throws IllegalArgumentException`. Since 19.3. Parses a GraalVM version from its String raw format. Throws [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) if the passed string is not a valid GraalVM version. Cite: `org/graalvm/home/Version.html#parse(java.lang.String)`
### create(int...)
`public static Version create(int... versions) throws IllegalArgumentException`. Since 19.3. Constructs a new GraalVM version from a list of version numbers. The versions must not be `null` and none of the version numbers must be negative. At least one version number must be non-zero. See also: `compareTo(int...)`. Cite: `org/graalvm/home/Version.html#create(int...)`
### getCurrent()
`public static Version getCurrent()`. Since 19.3. Returns the current GraalVM version of the installed component. Never `null`. See also: `HomeFinder.getVersion()`. Cite: `org/graalvm/home/Version.html#getCurrent()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ▣ org.graalvm.options
[polyglot](index.md) · Every page: [llms.txt](llms.txt)
Package in polyglot. Since 19.0.
The GraalVM SDK options package contains reusable collection classes for options.
**See also**
- [`org.graalvm.options.OptionDescriptor`](org/graalvm/options/OptionDescriptor.md)
- [`org.graalvm.options.OptionValues`](org/graalvm/options/OptionValues.md)
## Interfaces
- [`OptionDescriptors`](org/graalvm/options/OptionDescriptors.md): An interface to a set of OptionDescriptors.
- [`OptionValues`](org/graalvm/options/OptionValues.md): Represents a set of option values based on an OptionDescriptor.
## Classes
- [`ConstantOptionKey`](org/graalvm/options/ConstantOptionKey.md): Represents an OptionKey whose value is fixed before the polyglot runtime is initialized and cannot be changed afterwards.
- [`OptionDescriptor`](org/graalvm/options/OptionDescriptor.md): Represents metadata for a single option.
- [`OptionKey`](org/graalvm/options/OptionKey.md): Represents the option key for an option specification.
- [`OptionMap`](org/graalvm/options/OptionMap.md): Represents a mapping between String keys and values.
- [`OptionType`](org/graalvm/options/OptionType.md): Represents a type of an option that allows to convert string values to Java values.
## Enums
- [`OptionCategory`](org/graalvm/options/OptionCategory.md): Categorizes options according to user relevance.
- [`OptionStability`](org/graalvm/options/OptionStability.md): Categorizes options according to their stability.
# ◆ ConstantOptionKey
[polyglot](index.md) › [org.graalvm.options](org/graalvm/options/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.options`](org/graalvm/options/index.md). Since 25.1.
```java
public final class ConstantOptionKey extends OptionKey
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > [`OptionKey`](org/graalvm/options/OptionKey.md) > `ConstantOptionKey`
Represents an [`OptionKey`](org/graalvm/options/OptionKey.md) whose value is fixed before the polyglot runtime is initialized and cannot be changed afterwards. Because the value is immutable after initialization, [`getConstantValue()`](org/graalvm/options/ConstantOptionKey.md#getConstantValue%28%29) is eligible for constant folding by the compiler, allowing branches guarded by this option to be eliminated from compiled code.
The option value is initialized from the system property `-Dpolyglot.=`, which must be set before the polyglot runtime is initialized (i.e. before the containing class is loaded). If the system property is absent, the [`default value`](org/graalvm/options/OptionKey.md#getDefaultValue%28%29) is used. On HotSpot, this means the property must be present on the JVM command line. In a GraalVM native image, the property is read during image building, so the value is baked into the image.
Once the value has been set, [`getConstantValue()`](org/graalvm/options/ConstantOptionKey.md#getConstantValue%28%29) returns the same value for the lifetime of the runtime. The GraalVM compiler constant-folds calls to this method when the receiver is a known heap constant (e.g. a `static final` field), enabling dead-branch elimination.
## Constructors
### ConstantOptionKey(T)
`public ConstantOptionKey(T defaultValue)`. Since 25.1. Constructs a new constant option key with the given default value. The default value is used when no value is specified via the system property `-Dpolyglot.`. Throws [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) if no default `OptionType` could be `resolved` for the given type. The default value must not be `null`. Cite: `org/graalvm/options/ConstantOptionKey.html#(T)`
### ConstantOptionKey(T, OptionType)
`public ConstantOptionKey(T defaultValue, OptionType type)`. Since 25.1. Constructs a new constant option key with an explicit option type and default value. The default value is used when no value is specified via the system property `-Dpolyglot.`. Cite: `org/graalvm/options/ConstantOptionKey.html#(T,org.graalvm.options.OptionType)`
## Methods
### getConstantValue()
`public T getConstantValue()`. Since 25.1. Returns the constant value of this option key. The value is fixed at class initialization time and remains immutable for the lifetime of the runtime, making this method eligible for constant folding by the GraalVM compiler when the receiver is a heap constant. Throws: `IllegalStateException` (unchecked): if the value has not been set yet, which should not happen in normal usage as the generated option descriptors static initializer sets the value at class load time. Cite: `org/graalvm/options/ConstantOptionKey.html#getConstantValue()`
### setConstantValue(T)
`public void setConstantValue(T value)`. Since 25.1. Sets the constant value of this option key. This method is intended to be called from the generated option descriptors static initializer and must not be called after the polyglot runtime has started. In a native image, it must not be called at image run time. Throws: `IllegalStateException` (unchecked): if the value has already been set, or if called at native image run time. Cite: `org/graalvm/options/ConstantOptionKey.html#setConstantValue(T)`
## Inherited members
- From class [`OptionKey`](org/graalvm/options/OptionKey.md): [`getDefaultValue`](org/graalvm/options/OptionKey.md#getDefaultValue%28%29), [`getType`](org/graalvm/options/OptionKey.md#getType%28%29), [`getValue`](org/graalvm/options/OptionKey.md#getValue%28org.graalvm.options.OptionValues%29), [`hasBeenSet`](org/graalvm/options/OptionKey.md#hasBeenSet%28org.graalvm.options.OptionValues%29), [`mapOf`](org/graalvm/options/OptionKey.md#mapOf%28java.lang.Class%29)
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`toString`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ≡ OptionCategory
[polyglot](index.md) › [org.graalvm.options](org/graalvm/options/index.md) · Every page: [llms.txt](llms.txt)
Enum class in [`org.graalvm.options`](org/graalvm/options/index.md). Since 19.0.
```java
public enum OptionCategory
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > [`Enum`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html) > `OptionCategory`
Categorizes options according to user relevance.
## Enum constants
### USER
`USER`. Since 19.0. An option common for users to apply. Cite: `org/graalvm/options/OptionCategory.html#USER`
### EXPERT
`EXPERT`. Since 19.0. An option only relevant in corner cases and for fine-tuning. Cite: `org/graalvm/options/OptionCategory.html#EXPERT`
### INTERNAL
`INTERNAL`. Since 19.0. An option only relevant when debugging a language implementation or an instrument. Cite: `org/graalvm/options/OptionCategory.html#INTERNAL`
## Methods
### values()
`public static OptionCategory[] values()`. Returns the enum constants in declaration order. Returns `OptionCategory[]`: Returns the enum constants in declaration order. Cite: `org/graalvm/options/OptionCategory.html#values()`
### valueOf(String)
`public static OptionCategory valueOf(String name)`. Returns the enum constant with the given name. Parameters: `name` `String`: The exact name of the enum constant. Returns `OptionCategory`: Returns the enum constant with the given name. Cite: `org/graalvm/options/OptionCategory.html#valueOf(java.lang.String)`
## Inherited members
- From class [`Enum`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#clone%28%29), [`compareTo`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#compareTo%28E%29), [`describeConstable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#describeConstable%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#finalize%28%29), [`getDeclaringClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#getDeclaringClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#hashCode%28%29), [`name`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#name%28%29), [`ordinal`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#ordinal%28%29), [`toString`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#toString%28%29), [`valueOf`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#valueOf%28java.lang.Class,java.lang.String%29)
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ OptionDescriptor
[polyglot](index.md) › [org.graalvm.options](org/graalvm/options/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.options`](org/graalvm/options/index.md). Since 19.0.
```java
public final class OptionDescriptor
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `OptionDescriptor`
Represents metadata for a single option.
## Nested types
- [`OptionDescriptor.Builder`](org/graalvm/options/OptionDescriptor.Builder.md) (class): Represents an option descriptor builder.
## Methods
### getName()
`public String getName()`. Since 19.0. Returns the name of the option that this descriptor represents. Cite: `org/graalvm/options/OptionDescriptor.html#getName()`
### getKey()
`public OptionKey> getKey()`. Since 19.0. Returns the key for this option. Cite: `org/graalvm/options/OptionDescriptor.html#getKey()`
### isDeprecated()
`public boolean isDeprecated()`. Since 19.0. Returns `true` if this option was marked deprecated. This indicates that the option is going to be removed in a future release or its use is not recommended. Cite: `org/graalvm/options/OptionDescriptor.html#isDeprecated()`
### getDeprecationMessage()
`public String getDeprecationMessage()`. Since 20.1.0. Returns the deprecation reason and the recommended fix. For newlines, use `%n`. Cite: `org/graalvm/options/OptionDescriptor.html#getDeprecationMessage()`
### isOptionMap()
`public boolean isOptionMap()`. Since 19.2. Returns `true` if this option is an option map. Options maps allow to collect key=value pairs whose keys are unknown beforehand e.g. user defined properties. Cite: `org/graalvm/options/OptionDescriptor.html#isOptionMap()`
### getCategory()
`public OptionCategory getCategory()`. Since 19.0. Returns the user category of this option. Cite: `org/graalvm/options/OptionDescriptor.html#getCategory()`
### getStability()
`public OptionStability getStability()`. Since 19.0. Returns the stability of this option. Cite: `org/graalvm/options/OptionDescriptor.html#getStability()`
### getHelp()
`public String getHelp()`. Since 19.0. Returns a human-readable description on how to use the option. For newlines, use `%n`. Cite: `org/graalvm/options/OptionDescriptor.html#getHelp()`
### getUsageSyntax()
`public String getUsageSyntax()`. Since 22.1. Specifies a human-readable syntax describing the accepted values for this option. Returns `String`: null if no usage syntax should be used, the usage syntax otherwise. Cite: `org/graalvm/options/OptionDescriptor.html#getUsageSyntax()`
### isConstant()
`public boolean isConstant()`. Since 25.1. Returns `true` if this option is constant. Constant options value is static and final before the polyglot runtime is initialized and cannot be changed at runtime. The value is read from the system property `-Dpolyglot.=` during class initialization. If absent, the `default value` is used. Once set, calls to `org.graalvm.options.ConstantOptionKey.getConstantValue()` on a `static final` field are eligible for constant folding by the GraalVM compiler, allowing dead branches to be eliminated. See also: `ConstantOptionKey`. Cite: `org/graalvm/options/OptionDescriptor.html#isConstant()`
### toString()
`public String toString()`. Since 19.0. Overrides `toString()`. Cite: `org/graalvm/options/OptionDescriptor.html#toString()`
### hashCode()
`public int hashCode()`. Since 19.0. Overrides `hashCode()`. Cite: `org/graalvm/options/OptionDescriptor.html#hashCode()`
### equals(Object)
`public boolean equals(Object obj)`. Since 19.0. Overrides `equals(java.lang.Object)`. Cite: `org/graalvm/options/OptionDescriptor.html#equals(java.lang.Object)`
### newBuilder(OptionKey, String)
`public static OptionDescriptor.Builder newBuilder(OptionKey key, String name)`. Since 19.0. Creates a new option descriptor builder by key. The option group and name is inferred by the key. Cite: `org/graalvm/options/OptionDescriptor.html#newBuilder(org.graalvm.options.OptionKey,java.lang.String)`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ OptionDescriptor.Builder
[polyglot](index.md) › [org.graalvm.options](org/graalvm/options/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.options`](org/graalvm/options/index.md). Since 19.0. Nested in [`OptionDescriptor`](org/graalvm/options/OptionDescriptor.md).
```java
public final class OptionDescriptor.Builder
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `Builder`
Represents an option descriptor builder.
## Methods
### category(OptionCategory)
`public OptionDescriptor.Builder category(OptionCategory category)`. Since 19.0. Defines the user category for this option. The default value is `OptionCategory.INTERNAL`. Cite: `org/graalvm/options/OptionDescriptor.Builder.html#category(org.graalvm.options.OptionCategory)`
### stability(OptionStability)
`public OptionDescriptor.Builder stability(OptionStability stability)`. Since 19.0. Defines the stability of this option. The default value is `OptionStability.EXPERIMENTAL`. Cite: `org/graalvm/options/OptionDescriptor.Builder.html#stability(org.graalvm.options.OptionStability)`
### deprecated(boolean)
`public OptionDescriptor.Builder deprecated(boolean deprecated)`. Since 19.0. Defines if this option is deprecated. The default value for deprecated is `false`. This can be used to evolve options between releases. Cite: `org/graalvm/options/OptionDescriptor.Builder.html#deprecated(boolean)`
### help(String)
`public OptionDescriptor.Builder help(String help)`. Since 19.0. Specifies a human-readable description on how to use the option. Cite: `org/graalvm/options/OptionDescriptor.Builder.html#help(java.lang.String)`
### usageSyntax(String)
`public OptionDescriptor.Builder usageSyntax(String usageSyntax)`. Since 22.1. Specifies a human-readable syntax describing the accepted values for this option. Cite: `org/graalvm/options/OptionDescriptor.Builder.html#usageSyntax(java.lang.String)`
### deprecationMessage(String)
`public OptionDescriptor.Builder deprecationMessage(String deprecationMessage)`. Since 20.1.0. Specifies a human-readable deprecation reason and the recommended fix. Cite: `org/graalvm/options/OptionDescriptor.Builder.html#deprecationMessage(java.lang.String)`
### constant(boolean)
`public OptionDescriptor.Builder constant(boolean value)`. Since 25.1. Marks this option as constant. Constant options use `ConstantOptionKey` as their key type and must be configured using the system property `-Dpolyglot.=` before the polyglot runtime is initialized. Setting a constant option at runtime via `org.graalvm.polyglot.Engine.Builder.option(String, String)` throws an [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html). The default value is `false`. See also: `ConstantOptionKey`. Cite: `org/graalvm/options/OptionDescriptor.Builder.html#constant(boolean)`
### build()
`public OptionDescriptor build()`. Since 19.0. Builds and returns a new option descriptor. Throws: `IllegalArgumentException` (unchecked): if this descriptor is marked with `constant(true)` but the key is not a `ConstantOptionKey`, or if the key is a `ConstantOptionKey` but the descriptor is not marked with `constant(true)`. Cite: `org/graalvm/options/OptionDescriptor.Builder.html#build()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`toString`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◇ OptionDescriptors
[polyglot](index.md) › [org.graalvm.options](org/graalvm/options/index.md) · Every page: [llms.txt](llms.txt)
Interface in [`org.graalvm.options`](org/graalvm/options/index.md). Since 19.0.
```java
public interface OptionDescriptors extends Iterable
```
Extends: [`Iterable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Iterable.html)`<`[`OptionDescriptor`](org/graalvm/options/OptionDescriptor.md)`>`
An interface to a set of [`OptionDescriptor`](org/graalvm/options/OptionDescriptor.md)s.
## Fields
### EMPTY
`OptionDescriptors EMPTY`. Since 19.0. An empty set of option descriptors. Cite: `org/graalvm/options/OptionDescriptors.html#EMPTY`
## Methods
### get(String)
`OptionDescriptor get(String optionName)`. Since 19.0. Gets the `OptionDescriptor` matching a given option name or `null` if this option descriptor set does not contain a matching option name. Cite: `org/graalvm/options/OptionDescriptors.html#get(java.lang.String)`
### createUnion(OptionDescriptors...)
`static OptionDescriptors createUnion(OptionDescriptors... descriptors)`. Since 19.0. Creates a union options descriptor out of multiple given descriptors. The operation descriptors are not checked for duplicate keys. The option descriptors are iterated in declaration order. Cite: `org/graalvm/options/OptionDescriptors.html#createUnion(org.graalvm.options.OptionDescriptors...)`
### iterator()
`Iterator iterator()`. Since 19.0. Overrides `iterator()`. Cite: `org/graalvm/options/OptionDescriptors.html#iterator()`
### create(List)
`static OptionDescriptors create(List descriptors)`. Since 19.0. Creates an `OptionDescriptors` instance from a list. The option descriptors implementation is backed by a [`LinkedHashMap`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/LinkedHashMap.html) that preserves ordering. Cite: `org/graalvm/options/OptionDescriptors.html#create(java.util.List)`
## Inherited members
- From interface [`Iterable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Iterable.html): [`forEach`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Iterable.html#forEach%28java.util.function.Consumer%29), [`spliterator`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Iterable.html#spliterator%28%29)
# ◆ OptionKey
[polyglot](index.md) › [org.graalvm.options](org/graalvm/options/index.md) · Every page: [llms.txt](llms.txt)
Sealed class in [`org.graalvm.options`](org/graalvm/options/index.md). Since 19.0.
```java
public sealed class OptionKey permits ConstantOptionKey
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `OptionKey`
Permitted subtypes: [`ConstantOptionKey`](org/graalvm/options/ConstantOptionKey.md)
Represents the option key for an option specification.
## Constructors
### OptionKey(T)
`public OptionKey(T defaultValue)`. Since 19.0. Constructs a new option key given a default value. Throws [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) if no default `OptionType` could be `resolved` for the given type. The default value must not be `null`. Cite: `org/graalvm/options/OptionKey.html#(T)`
### OptionKey(T, OptionType)
`public OptionKey(T defaultValue, OptionType type)`. Since 19.0. Constructs a new option key given a default value and option key. Cite: `org/graalvm/options/OptionKey.html#(T,org.graalvm.options.OptionType)`
## Methods
### mapOf(Class)
`public static OptionKey> mapOf(Class valueClass)`. Since 19.2. Constructs a new option key to group/accumulate options with common prefixes. This type of options allow to collect key=value pairs whose keys are unknown beforehand e.g. user defined properties. See `OptionMap`. Example usage: Properties can be set using the `mylang.Properties` prefix. The option map can be consumed as follows: Throws [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) if no default `OptionType` could be `resolved` for the value type. Cite: `org/graalvm/options/OptionKey.html#mapOf(java.lang.Class)`
```java
@Option.Group("mylang")
public class MiscOptions {
@Option(help = "User-defined properties", category = OptionCategory.USER) //
public static final OptionKey> Properties = OptionKey.mapOf(String.class);
...
}
```
```java
Context context = Context.newBuilder() //
.option("mylang.Properties.key", "value") //
.option("mylang.Properties.user.name", "guest") //
.build();
```
```java
OptionMap properties = getOptions().get(MiscOptions.Properties);
properties.get("key"); // value
properties.get("user.name"); // guest
properties.get("undefined"); // null
```
### getType()
`public OptionType getType()`. Since 19.0. Returns the option type of this key. Cite: `org/graalvm/options/OptionKey.html#getType()`
### getDefaultValue()
`public T getDefaultValue()`. Since 19.0. Returns the default value for this option. Cite: `org/graalvm/options/OptionKey.html#getDefaultValue()`
### getValue(OptionValues)
`public T getValue(OptionValues values)`. Since 19.0. Returns the value of this key given the `values`. Cite: `org/graalvm/options/OptionKey.html#getValue(org.graalvm.options.OptionValues)`
### hasBeenSet(OptionValues)
`public boolean hasBeenSet(OptionValues values)`. Since 19.0. Returns `true` if a value for this key has been set for the given option values or `false` if no value has been set. Cite: `org/graalvm/options/OptionKey.html#hasBeenSet(org.graalvm.options.OptionValues)`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`toString`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ OptionMap
[polyglot](index.md) › [org.graalvm.options](org/graalvm/options/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.options`](org/graalvm/options/index.md). Since 19.2.
```java
public final class OptionMap
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `OptionMap`
Represents a mapping between [`String`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html) keys and values. Allows to create [`options`](org/graalvm/options/OptionKey.md) to group/accumulate `key=value` pairs, with a common prefix; whose keys are not known beforehand e.g. user defined properties.
**Type parameters**
- ``: the class of the map values
## Methods
### empty()
`public static OptionMap empty()`. Since 19.2. Returns an empty option map (immutable). Type parameters: ``: the class of the map values. Returns `OptionMap`: an empty option map. Cite: `org/graalvm/options/OptionMap.html#empty()`
### get(String)
`public T get(String key)`. Since 19.2. Returns the value to which the specified key is mapped, or `null` if this option map contains no mapping for the key. Parameters: `key` `String`: the key whose associated value is to be returned. Returns `T`: the value to which the specified key is mapped, or `null` if this map contains no mapping for the key. Cite: `org/graalvm/options/OptionMap.html#get(java.lang.String)`
### entrySet()
`public Set> entrySet()`. Since 19.2. Returns an unmodifiable [`Set`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Set.html) view of the mappings contained in this map. Returns `Set>`: a set view of the mappings contained in this map. Cite: `org/graalvm/options/OptionMap.html#entrySet()`
### hashCode()
`public int hashCode()`. Since 19.2. Overrides `hashCode()`. Cite: `org/graalvm/options/OptionMap.html#hashCode()`
### equals(Object)
`public boolean equals(Object obj)`. Since 19.2. Overrides `equals(java.lang.Object)`. Cite: `org/graalvm/options/OptionMap.html#equals(java.lang.Object)`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`toString`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ≡ OptionStability
[polyglot](index.md) › [org.graalvm.options](org/graalvm/options/index.md) · Every page: [llms.txt](llms.txt)
Enum class in [`org.graalvm.options`](org/graalvm/options/index.md). Since 19.0.
```java
public enum OptionStability
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > [`Enum`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html) > `OptionStability`
Categorizes options according to their stability.
## Enum constants
### STABLE
`STABLE`. Since 19.0. A stable option is expected to remain available for many releases. End users can rely on such an option being present. A stable option can still be removed but will go through a clear deprecating process before being removed. Cite: `org/graalvm/options/OptionStability.html#STABLE`
### EXPERIMENTAL
`EXPERIMENTAL`. Since 19.0. An experimental option has no guarantees of stability and might be removed at any point. Cite: `org/graalvm/options/OptionStability.html#EXPERIMENTAL`
## Methods
### values()
`public static OptionStability[] values()`. Returns the enum constants in declaration order. Returns `OptionStability[]`: Returns the enum constants in declaration order. Cite: `org/graalvm/options/OptionStability.html#values()`
### valueOf(String)
`public static OptionStability valueOf(String name)`. Returns the enum constant with the given name. Parameters: `name` `String`: The exact name of the enum constant. Returns `OptionStability`: Returns the enum constant with the given name. Cite: `org/graalvm/options/OptionStability.html#valueOf(java.lang.String)`
## Inherited members
- From class [`Enum`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#clone%28%29), [`compareTo`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#compareTo%28E%29), [`describeConstable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#describeConstable%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#finalize%28%29), [`getDeclaringClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#getDeclaringClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#hashCode%28%29), [`name`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#name%28%29), [`ordinal`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#ordinal%28%29), [`toString`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#toString%28%29), [`valueOf`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#valueOf%28java.lang.Class,java.lang.String%29)
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ OptionType
[polyglot](index.md) › [org.graalvm.options](org/graalvm/options/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.options`](org/graalvm/options/index.md). Since 19.0.
```java
public final class OptionType
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `OptionType`
Represents a type of an option that allows to convert string values to Java values.
## Constructors
### OptionType(String, Function, Consumer)
`public OptionType(String name, Function stringConverter, Consumer validator)`. Since 19.0. Constructs a new option type with name and function that allows to convert a string to the option type and validator of the option values. Parameters: `name` `String`: the name of the type. `stringConverter` `Function`: a function that converts a string value to the option value. Can throw [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) to indicate an invalid string. `validator` `Consumer`: used for validating the option value. Throws [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) if the value is invalid. Cite: `org/graalvm/options/OptionType.html#(java.lang.String,java.util.function.Function,java.util.function.Consumer)`
### OptionType(String, Function)
`public OptionType(String name, Function stringConverter)`. Since 19.0. Constructs a new option type with name and function that allows to convert a string to the option type. Parameters: `name` `String`: the name of the type. `stringConverter` `Function`: a function that converts a string value to the option value. Can throw [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) to indicate an invalid string. Cite: `org/graalvm/options/OptionType.html#(java.lang.String,java.util.function.Function)`
### OptionType(String, T, …)
`@Deprecated(since = "19.0") public OptionType(String name, T defaultValue, Function stringConverter, Consumer validator)`. Since 19.0. Deprecated since 19.0. Use `OptionType(String, Function, Consumer)`. Cite: `org/graalvm/options/OptionType.html#(java.lang.String,T,java.util.function.Function,java.util.function.Consumer)`
### OptionType(String, T, Function)
`@Deprecated(since = "19.0") public OptionType(String name, T defaultValue, Function stringConverter)`. Since 19.0. Deprecated since 19.0. Use `OptionType(String, Function)`. Cite: `org/graalvm/options/OptionType.html#(java.lang.String,T,java.util.function.Function)`
## Methods
### getDefaultValue()
`@Deprecated(since = "19.0") public T getDefaultValue()`. Since 19.0. Deprecated since 19.0. Cite: `org/graalvm/options/OptionType.html#getDefaultValue()`
### getName()
`public String getName()`. Since 19.0. Returns the name of this type. Cite: `org/graalvm/options/OptionType.html#getName()`
### convert(String)
`public T convert(String value)`. Since 19.0. Converts a string value, validates it, and converts it to an object of this type. Throws: `IllegalArgumentException` (unchecked): if the value is invalid or cannot be converted. Cite: `org/graalvm/options/OptionType.html#convert(java.lang.String)`
### convert(Object, String, String)
`public T convert(Object previousValue, String nameSuffix, String value)`. Since 19.2. Converts a string value, validates it, and converts it to an object of this type. For option maps includes the previous map stored for the option and the key. Parameters: `previousValue` `Object`: the previous value holded by option. `nameSuffix` `String`: the key for prefix options. Throws: `IllegalArgumentException` (unchecked): if the value is invalid or cannot be converted. Cite: `org/graalvm/options/OptionType.html#convert(java.lang.Object,java.lang.String,java.lang.String)`
### validate(T)
`public void validate(T value)`. Since 19.0. Validates an option value and throws an [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) if the value is invalid. Throws: `IllegalArgumentException` (unchecked): if the value is invalid or cannot be converted. Cite: `org/graalvm/options/OptionType.html#validate(T)`
### toString()
`public String toString()`. Since 19.0. Overrides `toString()`. Cite: `org/graalvm/options/OptionType.html#toString()`
### defaultType(T)
`public static OptionType defaultType(T value)`. Since 19.0. Returns the default option type for a given value. Returns `null` if no default option type is available for the Java type of this value. Cite: `org/graalvm/options/OptionType.html#defaultType(T)`
### defaultType(Class)
`public static OptionType defaultType(Class clazz)`. Since 19.0. Returns the default option type for a class. Returns `null` if no default option type is available for this Java type. Cite: `org/graalvm/options/OptionType.html#defaultType(java.lang.Class)`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◇ OptionValues
[polyglot](index.md) › [org.graalvm.options](org/graalvm/options/index.md) · Every page: [llms.txt](llms.txt)
Interface in [`org.graalvm.options`](org/graalvm/options/index.md). Since 19.0.
```java
public interface OptionValues
```
Represents a set of option values based on an [`OptionDescriptor`](org/graalvm/options/OptionDescriptor.md).
## Methods
### getDescriptors()
`OptionDescriptors getDescriptors()`. Since 19.0. Returns all available options. Cite: `org/graalvm/options/OptionValues.html#getDescriptors()`
### set(OptionKey, T)
`@Deprecated(since = "22.0") default void set(OptionKey optionKey, T value)`. Since 19.0. Deprecated since 22.0. `OptionValues` should be read-only. If the value of an option needs to be altered after options are set, then the new value should be stored in the language's context or instrument fields and read from there. Sets the value of `optionKey` to `value`. Throws: `UnsupportedOperationException` (unchecked): because this operation has been deprecated and is no longer supported, in order for OptionValues to be read-only. Cite: `org/graalvm/options/OptionValues.html#set(org.graalvm.options.OptionKey,T)`
### get(OptionKey)
` T get(OptionKey optionKey)`. Since 19.0. Returns the value of a given option. `hasBeenSet(OptionKey)` can be used to know whether the value was explicitly set, or is the `default value`. Cite: `org/graalvm/options/OptionValues.html#get(org.graalvm.options.OptionKey)`
### hasBeenSet(OptionKey)
`boolean hasBeenSet(OptionKey> optionKey)`. Since 19.0. Determines if a value for `optionKey` has been set explicitly by the `Context` or `Engine`, and therefore `get(OptionKey)` does not call `OptionKey.getDefaultValue()`. Cite: `org/graalvm/options/OptionValues.html#hasBeenSet(org.graalvm.options.OptionKey)`
### hasSetOptions()
`default boolean hasSetOptions()`. Since 19.0. Determines if a value for any of the option keys in `option descriptors` `has been set`. Cite: `org/graalvm/options/OptionValues.html#hasSetOptions()`
# ▣ org.graalvm.polyglot
[polyglot](index.md) · Every page: [llms.txt](llms.txt)
Package in polyglot. Since 19.0.
The GraalVM SDK polyglot API allows to embed Graal languages in Java applications.
To get started quickly create a new [`org.graalvm.polyglot.Context`](org/graalvm/polyglot/Context.md) using [`org.graalvm.polyglot.Context.create(String...)`](org/graalvm/polyglot/Context.md#create%28java.lang.String...%29) and then evaluate guest language code using [`org.graalvm.polyglot.Context.eval(String, CharSequence)`](org/graalvm/polyglot/Context.md#eval%28java.lang.String,java.lang.CharSequence%29).
See [graalvm.org](https://www.graalvm.org/latest/reference-manual/embed-languages/) for more examples on how to use this API.
**See also**
- [`For an overview over the features the polyglot API provides.`](org/graalvm/polyglot/Context.md)
## Classes
- [`Context`](org/graalvm/polyglot/Context.md): A polyglot context for Graal guest languages that allows to evaluate code.
- [`Engine`](org/graalvm/polyglot/Engine.md): An execution engine for Graal guest languages that allows to inspect the the installed guest languages, instruments and their available options.
- [`EnvironmentAccess`](org/graalvm/polyglot/EnvironmentAccess.md): Represents an access policy to the process environment for the guest languages of a context.
- [`HostAccess`](org/graalvm/polyglot/HostAccess.md): Represents the host access policy of a polyglot context.
- [`Instrument`](org/graalvm/polyglot/Instrument.md): A handle for an instrument installed in an engine.
- [`Language`](org/graalvm/polyglot/Language.md): A handle for a Graal language installed in an engine.
- [`PolyglotAccess`](org/graalvm/polyglot/PolyglotAccess.md): Represents an access policy for polyglot builtins in the guest languages.
- [`PreinitializedSources`](org/graalvm/polyglot/PreinitializedSources.md): Registers sources that context pre-initialization parses when a native image is built.
- [`ResourceLimitEvent`](org/graalvm/polyglot/ResourceLimitEvent.md): Event triggered by a resource limit for a context.
- [`ResourceLimits`](org/graalvm/polyglot/ResourceLimits.md): Represents resource limits configuration that is used to configure contexts.
- [`Source`](org/graalvm/polyglot/Source.md): Representation of a source code unit and its contents that can be evaluated in an execution context.
- [`SourceSection`](org/graalvm/polyglot/SourceSection.md): Description of contiguous section of text within a Source of program code.; supports multiple modes of access to the text and its location.
- [`TypeLiteral`](org/graalvm/polyglot/TypeLiteral.md): Represents a generic type T.
- [`Value`](org/graalvm/polyglot/Value.md): Represents a polyglot value that can be accessed using a set of language agnostic operations.
## Enums
- [`SandboxPolicy`](org/graalvm/polyglot/SandboxPolicy.md): The sandbox policy presets and validates configurations of a context or engine to be suitable as a code sandbox.
## Exceptions
- [`PolyglotException`](org/graalvm/polyglot/PolyglotException.md): A polyglot exception represents errors that contain Graal guest languages on the stack trace.
# ◆ Context
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0.
```java
public final class Context implements AutoCloseable
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `Context`
Implements: [`AutoCloseable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AutoCloseable.html)
A polyglot context for Graal guest languages that allows to [`evaluate`](org/graalvm/polyglot/Context.md#eval%28org.graalvm.polyglot.Source%29) code. A polyglot context represents the global runtime state of all [`installed`](org/graalvm/polyglot/Engine.md#getLanguages%28%29) and [`permitted`](org/graalvm/polyglot/Context.md#newBuilder%28java.lang.String...%29) languages. Permitted languages are [`initialized`](org/graalvm/polyglot/Context.md#initialize%28java.lang.String%29) lazily, when they are used for the first time. For many context operations, a *language identifier* needs to be specified. A language identifier is unique for each language.
### Evaluation
A context allows to evaluate a guest language source code using [`eval(Source)`](org/graalvm/polyglot/Context.md#eval%28org.graalvm.polyglot.Source%29). This is possible by evaluating [`Source`](org/graalvm/polyglot/Source.md) objects or a given language identifier and code [`String`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html). The [`evaluation`](org/graalvm/polyglot/Context.md#eval%28org.graalvm.polyglot.Source%29) returns either the result value or throws a [`PolyglotException`](org/graalvm/polyglot/PolyglotException.md) if a guest language error occurs.
**Example** for evaluation of a fragment of JavaScript code with a new context:
```java
Context context = Context.create();
Value result = context.eval("js", "42");
assert result.asInt() == 42;
context.close();
```
In this example:
- First we create a new context with all permitted languages.
- Next, we evaluate the expression "42" with language "js", which is the language identifier for JavaScript. Since this is the first time we access JavaScript, it automatically gets [`initialized`](org/graalvm/polyglot/Context.md#initialize%28java.lang.String%29).
- Then, we assert the result value by converting the result value as primitive `int` .
- Finally, when a context is no longer needed, it is recommended to explicitly close it to ensure timely release of resources. While contexts are automatically closed when no longer strongly reachable, explicit closure is still preferred. Contexts are also [`AutoCloseable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AutoCloseable.html), allowing them to be used with the Java `try-with-resources` statement.
### Configuration
Contexts may be created either with default configuration using the [`create method`](org/graalvm/polyglot/Context.md#create%28java.lang.String...%29) or with custom configuration using the [`builder`](org/graalvm/polyglot/Context.md#newBuilder%28java.lang.String...%29). Both methods allow to specify a subset of the installed languages as permitted languages. If no language is specified then all installed languages are permitted. Using the builder method [`input`](org/graalvm/polyglot/Context.Builder.md#in%28java.io.InputStream%29), [`error`](org/graalvm/polyglot/Context.Builder.md#err%28java.io.OutputStream%29) and [`output`](org/graalvm/polyglot/Context.Builder.md#out%28java.io.OutputStream%29) streams, [`options`](org/graalvm/polyglot/Context.Builder.md#option%28java.lang.String,java.lang.String%29), and [`application arguments`](org/graalvm/polyglot/Context.Builder.md#arguments%28java.lang.String,java.lang.String[]%29) may be configured.
Options may be specified for [`languages`](org/graalvm/polyglot/Engine.md#getLanguages%28%29), [`instruments`](org/graalvm/polyglot/Engine.md#getInstruments%28%29), the [`engine`](org/graalvm/polyglot/Engine.md#getOptions%28%29) and the [`compiler`](org/graalvm/polyglot/Engine.md#getOptions%28%29). For [`language options`](org/graalvm/polyglot/Language.md#getOptions%28%29), the option key consists of the [`language id`](org/graalvm/polyglot/Language.md#getId%28%29) plus a dot followed by the option name (e.g. "js.Strict"). For most languages the option names start with an upper-case letter by convention. A list of available options may be received using [`Language.getOptions()`](org/graalvm/polyglot/Language.md#getOptions%28%29). [`Instrument options`](org/graalvm/polyglot/Instrument.md#getOptions%28%29) are structured in the same way as language options but start with the [`instrument id`](org/graalvm/polyglot/Instrument.md#getId%28%29) instead.
If system properties are [`enabled`](org/graalvm/polyglot/Engine.Builder.md#useSystemProperties%28boolean%29), which they are by default, then all polyglot options maybe specified with the prefix "polyglot." (e.g. "-Dpolyglot.js.Strict=true"). The system properties are read only once when the context or engine instance is created. After that, changes to the system properties have no affect.
Each Graal language performs an initialization step before it can be used to execute code, after which it remains initialized for the lifetime of the context. Initialization is by default lazy and automatic, but initialization can be forced [`manually`](org/graalvm/polyglot/Context.md#initialize%28java.lang.String%29) if needed.
**Example** for custom configuration using the context builder:
```java
OutputStream myOut = new BufferedOutputStream()
Context context = Context.newBuilder("js", "R")
.out(myOut)
.option("js.Strict", "true")
.allowAllAccess(true)
.build();
context.eval("js", "42");
context.eval("R", "42");
context.close();
```
In this example:
- At first, we create a new context and specify permitted languages as parameters.
- Secondly, we set the standard output stream to be used for the context.
- Then, we specify an option for JavaScript language only, by structuring the option key with the language id followed by the option name;
- With [`Builder.allowAllAccess(boolean)`](org/graalvm/polyglot/Context.Builder.md#allowAllAccess%28boolean%29) we grant a new context instance with the same access privileges as the host virtual machine.
- Next, we evaluate the expression "42" with language "js", which is the language identifier for JavaScript. Since this is the first time we access JavaScript, it first gets [`initialized`](org/graalvm/polyglot/Context.md#initialize%28java.lang.String%29) as well.
- Similarly to the previous line, the R language expression gets evaluated.
- Finally, we close the context, since it is no longer needed, to free all allocated resources. Contexts are also [`AutoCloseable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AutoCloseable.html) for use with the Java `try-with-resources` statement.
### Bindings
The symbols of the top-most scope of a language can be accessed using the [`language bindings`](org/graalvm/polyglot/Context.md#getBindings%28java.lang.String%29). Each language provides its own bindings object for a context. The bindings object may be used to read, modify, insert and delete members in the top-most scope of the language. Certain languages may not allow write access to the bindings object. See [`getBindings(String)`](org/graalvm/polyglot/Context.md#getBindings%28java.lang.String%29) for details.
A context instance also provides access to the [`polyglot`](org/graalvm/polyglot/Context.md#getPolyglotBindings%28%29) bindings. The polyglot bindings are shared between languages and may be used to exchange values. See [`getPolyglotBindings()`](org/graalvm/polyglot/Context.md#getPolyglotBindings%28%29) for details.
**Examples** using language bindings from JavaScript:
```java
Context context = Context.create("js");
Value jsBindings = context.getBindings("js")
jsBindings.putMember("foo", 42);
assert context.eval("js", "foo").asInt() == 42;
context.eval("js", "var bar = 42");
assert jsBindings.getMember("bar").asInt() == 42;
assert jsBindings.getMember("Math")
.getMember("abs")
.execute(-42)
.asInt() == 42;
context.close();
```
In this example:
- We create a new context with JavaScript as the only permitted language.
- Next, we load the JavaScript bindings object and assign it to a local variable `jsBindings`.
- Then, we insert a new member `foo` into to the bindings object and verify that the object is accessible within the language by reading from a global symbol with the same name.
- After that, we declare a new global variable in JavaScript and verify that it is accessible as member of the language bindings object.
- Next, we access we access a JavaScript builtin named `Math.abs` symbol and execute it with -42. This result is asserted to be 42.
- Finally, we close the context to free all allocated resources.
### Host Interoperability
It is often necessary to interact with values of the host runtime and Graal guest languages. Such objects are referred to as *host objects*. Every Java value that is passed to a Graal language is interpreted according to the specification described in [`asValue(Object)`](org/graalvm/polyglot/Context.md#asValue%28java.lang.Object%29). Also see [`Value.as(Class)`](org/graalvm/polyglot/Value.md#as%28java.lang.Class%29) for further details.
By default only public classes, methods, and fields that are annotated with [`@HostAccess.Export`](org/graalvm/polyglot/HostAccess.Export.md) are accessible to the guest language. This policy can be customized using [`Builder.allowHostAccess(HostAccess)`](org/graalvm/polyglot/Context.Builder.md#allowHostAccess%28org.graalvm.polyglot.HostAccess%29) when constructing the context.
**Example** using a Java object from JavaScript:
```java
public class JavaRecord {
@HostAccess.Export public int x;
@HostAccess.Export
public String name() {
return "foo";
}
}
Context context = Context.create();
JavaRecord record = new JavaRecord();
context.getBindings("js").putMember("javaRecord", record);
context.eval("js", "javaRecord.x = 42");
assert record.x == 42;
context.eval("js", "javaRecord.name()").asString().equals("foo");
```
### Error Handling
Program execution may fail when executing a guest language code or when accessing guest language object. Almost all methods in the [`Context`](org/graalvm/polyglot/Context.md) and [`Value`](org/graalvm/polyglot/Value.md) API throw a [`PolyglotException`](org/graalvm/polyglot/PolyglotException.md) in case an error occurs. See [`PolyglotException`](org/graalvm/polyglot/PolyglotException.md) for further details on error handling.
### Isolation
Each context is by default isolated from all other instances with respect to both language evaluation semantics and resource consumption. By default, a new context instance has no access to host resources, like threads, files or loading new host classes. To allow access to such resources either the individual access right must be granted or [`all access`](org/graalvm/polyglot/Context.Builder.md#allowAllAccess%28boolean%29) must be set to `true`.
Contexts can be [configured](org/graalvm/polyglot/Context.Builder.md#engine%28org.graalvm.polyglot.Engine%29) to share certain system resources like ASTs or optimized code by specifying a single underlying engine. See [`Engine`](org/graalvm/polyglot/Engine.md) for more details about code sharing.
Context can be configured to allow value sharing between multiple contexts (allowed by default). See [`Builder.allowValueSharing(boolean)`](org/graalvm/polyglot/Context.Builder.md#allowValueSharing%28boolean%29) for details.
### Proxies
The [`proxy interfaces`](org/graalvm/polyglot/proxy/Proxy.md) allow to mimic guest language objects, arrays, executables, primitives and native objects in Graal languages. Every Graal language will treat proxy instances like objects of that particular language. Multiple proxy interfaces can be implemented at the same time. For example, it is useful to provide proxy values that are objects with members and arrays at the same time.
### Thread-Safety
It is safe to use a context instance from a single thread. It is also safe to use it with multiple threads if they do not access the context at the same time. Whether a single context instance may be used from multiple threads at the same time depends on if all initialized languages support it. If initialized languages support multi-threading, then the context instance may be used from multiple threads at the same time. If a context is used from multiple threads and the language does not fit, then an [`IllegalStateException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html) is thrown by the accessing method.
Meta-data from the context's underlying [`engine`](org/graalvm/polyglot/Context.md#getEngine%28%29) can be retrieved safely by any thread at any time.
A context may be [closed](org/graalvm/polyglot/Context.md#close%28%29) from any thread, but only if the context is not currently executing code. If the context is currently executing some code, a different thread may kill the running execution and close the context using [`close(boolean)`](org/graalvm/polyglot/Context.md#close%28boolean%29).
### Context Exit
A context is exited naturally by calling the [`close`](org/graalvm/polyglot/Context.md#close%28boolean%29) method. A context may also be exited at the guest application request. There are two ways a guest language may exit.
- Soft exit. A guest language throws a special exception that causes the embedder thread to eventually throw a [`PolyglotException`](org/graalvm/polyglot/PolyglotException.md) with [`PolyglotException.isExit()`](org/graalvm/polyglot/PolyglotException.md#isExit%28%29) returning `true` and [`PolyglotException.getExitStatus()`](org/graalvm/polyglot/PolyglotException.md#getExitStatus%28%29) returning the exit status code specified by the guest application. The special exception does not influence other threads and does not trigger context close on its own. Closing the context is up to the embedder.
- Hard exit. A guest language uses a builtin command that unwinds all context threads and closes the context by force. Embedder threads also throw a [`PolyglotException`](org/graalvm/polyglot/PolyglotException.md) with [`PolyglotException.isExit()`](org/graalvm/polyglot/PolyglotException.md#isExit%28%29) returning `true` and [`PolyglotException.getExitStatus()`](org/graalvm/polyglot/PolyglotException.md#getExitStatus%28%29) returning the exit status code specified by the guest application. However, the context is closed automatically. The hard exit can be customized using [`Builder.useSystemExit(boolean)`](org/graalvm/polyglot/Context.Builder.md#useSystemExit%28boolean%29). If `true`, the context threads are unwound by calling [`System.exit(int)`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/System.html#exit%28int%29) with the exit status parameter specified by the guest application. This operation terminates the whole host application.
### Pre-Initialization
The context pre-initialization can be used to perform expensive builtin creation in the time of native compilation.
The context pre-initialization is enabled by setting the system property `polyglot.image-build-time.PreinitializeContexts` to a comma separated list of language ids which should be pre-initialized, for example: `-Dpolyglot.image-build-time.PreinitializeContexts=js,python`
See `com.oracle.truffle.api.TruffleLanguage.patchContext(java.lang.Object, com.oracle.truffle.api.TruffleLanguage.Env)` for details about pre-initialization for language implementers.
## Nested types
- [`Context.Builder`](org/graalvm/polyglot/Context.Builder.md) (class): Builder class to construct Context instances.
## Methods
### getEngine()
`public Engine getEngine()`. Since 19.0. Provides access to meta-data about the underlying Graal engine. Returns `Engine`: Graal `Engine` being used by this context. Cite: `org/graalvm/polyglot/Context.html#getEngine()`
### eval(Source)
`public Value eval(Source source)`. Since 19.0. Evaluates a source object by using the language specified in the source. The result is accessible as `value` and never returns `null`. The first time a source is evaluated, it will be parsed. Consecutive invocations of eval with the same source will only execute the already parsed code. **Basic Example:**. Parameters: `source` `Source`: a source object to evaluate. Returns `Value`: the evaluation result. The returned instance is never `null`, but the result might represent a `null` value. Throws: `PolyglotException` (unchecked): in case the guest language code parsing or evaluation failed. `IllegalStateException` (unchecked): if the context is already closed and the current thread is not allowed to access it. `IllegalArgumentException` (unchecked): if the language of the given source is not installed or the `MIME type` is not supported with the language or the validation of a `source option` failed. Cite: `org/graalvm/polyglot/Context.html#eval(org.graalvm.polyglot.Source)`
```java
try (Context context = Context.create()) {
Source source = Source.newBuilder("js", "42", "mysource.js").build();
Value result = context.eval(source);
assert result.asInt() == 42;
}
```
### eval(String, CharSequence)
`public Value eval(String languageId, CharSequence source)`. Since 19.0. Evaluates a guest language code literal, using a provided `language id`. The result is accessible as `value` and never returns `null`. The provided [`CharSequence`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/CharSequence.html) must represent an immutable String. **Basic Example:**. Returns `Value`: the evaluation result. The returned instance is never `null`, but the result might represent a `null` value. Throws: `PolyglotException` (unchecked): in case the guest language code parsing or evaluation failed. `IllegalArgumentException` (unchecked): if the language does not exist or is not accessible. `IllegalStateException` (unchecked): if the context is already closed and the current thread is not allowed to access it, or if the given language is not installed. Cite: `org/graalvm/polyglot/Context.html#eval(java.lang.String,java.lang.CharSequence)`
```java
try (Context context = Context.create()) {
Value result = context.eval("js", "42");
assert result.asInt() == 42;
}
```
### parse(Source)
`public Value parse(Source source) throws PolyglotException`. Since 20.2. Parses but does not evaluate a given source by using the language specified in the source and returns a `value` that can be `executed`. If a parsing fails, e.g. due to a syntax error in the source, then a `PolyglotException` will be thrown. In case of a syntax error the `PolyglotException.isSyntaxError()` will return `true`. There is no guarantee that only syntax errors will be thrown by this method. Any other guest language exception might be thrown. If the validation succeeds then the method completes without throwing an exception. The result value only supports an empty set of arguments to `execute`. If executed repeatedly then the source is evaluated multiple times. `Interactive` sources will print their result for each execution of the parsing result to the `output` stream. If the parsing succeeds and the source is `cached` then the result will automatically be reused for consecutive calls to `parse(Source)` or `eval(Source)`. If the validation should be performed for each invocation or the result should not be remembered then `cached` can be set to `false`. By default sources are cached. **Basic Example:**. Parameters: `source` `Source`: a source object to parse. Throws: `PolyglotException`: in case the guest language code parsing or validation failed. `IllegalArgumentException` (unchecked): if the language of the given source is not installed or the `MIME type` is not supported with the language or the validation of a `source option` failed. `IllegalStateException` (unchecked): if the context is already closed and the current thread is not allowed to access it, or if the given language is not installed. Cite: `org/graalvm/polyglot/Context.html#parse(org.graalvm.polyglot.Source)`
```java
try (Context context = Context.create()) {
Source source = Source.create("js", "42");
Value value;
try {
value = context.parse(source);
// parsing succeeded
} catch (PolyglotException e) {
if (e.isSyntaxError()) {
SourceSection location = e.getSourceLocation();
// syntax error detected at location
} else {
// other guest error detected
}
throw e;
}
// evaluate the parsed script
value.execute();
}
```
### parse(String, CharSequence)
`public Value parse(String languageId, CharSequence source)`. Since 20.2. Parses but does not evaluate a guest language code literal using a provided `language id` and character sequence and returns a `value` that can be `executed`. The provided [`CharSequence`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/CharSequence.html) must represent an immutable String. This method represents a short-hand for `parse(Source)` . The result value only supports an empty set of arguments to `execute`. If executed repeatedly then the source is evaluated multiple times. `Interactive` sources will print their result for each execution of the parsing result to the `output` stream. Throws: `PolyglotException` (unchecked): in case the guest language code parsing or evaluation failed. `IllegalArgumentException` (unchecked): if the language does not exist or is not accessible. `IllegalStateException` (unchecked): if the context is already closed and the current thread is not allowed to access it, or if the given language is not installed. Cite: `org/graalvm/polyglot/Context.html#parse(java.lang.String,java.lang.CharSequence)`
```java
try (Context context = Context.create()) {
Value value;
try {
value = context.parse("js", "42");
// parsing succeeded
} catch (PolyglotException e) {
if (e.isSyntaxError()) {
SourceSection location = e.getSourceLocation();
// syntax error detected at location
} else {
// other guest error detected
}
throw e;
}
// evaluate the parsed script
value.execute();
}
```
### getPolyglotBindings()
`public Value getPolyglotBindings()`. Since 19.0. Returns polyglot bindings that may be used to exchange symbols between the host and guest languages. All languages have unrestricted access to the polyglot bindings. The returned bindings object always has `members` and its members are `readable`, `writable` and `removable`. Guest languages may put and get members through language specific APIs. For example, in JavaScript, symbols of the polyglot bindings can be accessed using `Polyglot.import("name")` and set using `Polyglot.export("name", value)`. Please see the individual language reference on how to access these symbols. Throws: `IllegalStateException` (unchecked): if context is already closed. Cite: `org/graalvm/polyglot/Context.html#getPolyglotBindings()`
### getBindings(String)
`public Value getBindings(String languageId)`. Since 19.0. Returns a value that represents the top-most bindings of a language. The top most bindings of the language returns a `member` for a symbol in the scope. Languages may allow modifications of members of the returned bindings object at the language's discretion. If the language has not been `initialized` yet, it will be initialized when the bindings are requested. Throws: `IllegalArgumentException` (unchecked): if the language does not exist or is not accessible. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): in case the lazy initialization failed due to a guest language error. Cite: `org/graalvm/polyglot/Context.html#getBindings(java.lang.String)`
### initialize(String)
`public boolean initialize(String languageId)`. Since 19.0. Forces the initialization of a language. It is not necessary to explicitly initialize a language, it will be initialized the first time it is used. Parameters: `languageId` `String`: the identifier of the language to initialize. Returns `boolean`: `true` if the language was initialized. Returns `false` if it was already initialized. Throws: `PolyglotException` (unchecked): in case the initialization failed due to a guest language error. `IllegalArgumentException` (unchecked): if the language does not exist or is not accessible. `IllegalStateException` (unchecked): if the context is already closed. Cite: `org/graalvm/polyglot/Context.html#initialize(java.lang.String)`
### resetLimits()
`public void resetLimits()`. Since 19.3. Resets all accumulators of resource limits for the associated context to zero. Cite: `org/graalvm/polyglot/Context.html#resetLimits()`
### asValue(Object)
`public Value asValue(Object hostValue)`. Since 19.0. Converts a host value to a polyglot `value` representation. This conversion is applied implicitly whenever `execution` or `instantiation` arguments are provided, `members` and `array elements` are set or when a value is returned by a `polyglot proxy`. It is not required nor efficient to explicitly convert to polyglot values before performing these operations. This method is useful to convert a `mapped` host value back to a polyglot value while preserving the identity. When a host value is converted to a polyglot value the following rules apply: If the `hostValue` is `null`, then it will be interpreted as polyglot `null`.; If the `hostValue` is already a `polyglot value`, then it will be cast to `Value`.; If the `hostValue` is an instance of [`Byte`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Byte.html), [`Short`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Short.html), [`Integer`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Integer.html), [`Long`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Long.html), [`Float`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Float.html) or [`Double`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Double.html), then it will be interpreted as polyglot `number`. Other subclasses of [`Number`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Number.html) will be interpreted as `host object` (see later).; If the `hostValue` is an instance of [`Character`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Character.html) or [`String`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html), then it will be interpreted as polyglot `string`.; If the `hostValue` is an instance of [`Boolean`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Boolean.html), then it will be interpreted as polyglot `boolean`.; If the `hostValue` is an instance of [`Instant`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Instant.html), [`LocalTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/LocalTime.html), [`LocalDateTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/LocalDateTime.html), [`ZonedDateTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/ZonedDateTime.html), [`OffsetDateTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/OffsetDateTime.html), [`OffsetTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/OffsetTime.html), [`java.sql.Time`](https://docs.oracle.com/en/java/javase/25/docs/api/java.sql/java/sql/Time.html), or [`java.util.Date`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Date.html) but not [`java.sql.Date`](https://docs.oracle.com/en/java/javase/25/docs/api/java.sql/java/sql/Date.html), then it will be interpreted as polyglot `time`.; If the `hostValue` is an instance of [`Instant`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Instant.html), [`LocalDate`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/LocalDate.html), [`LocalDateTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/LocalDateTime.html), [`ZonedDateTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/ZonedDateTime.html), [`OffsetDateTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/OffsetDateTime.html), or [`java.util.Date`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Date.html) but not [`java.sql.Time`](https://docs.oracle.com/en/java/javase/25/docs/api/java.sql/java/sql/Time.html), then it will be interpreted as polyglot `date`.; If the `hostValue` is an instance of [`ZoneId`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/ZoneId.html), [`Instant`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Instant.html), [`ZonedDateTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/ZonedDateTime.html), [`OffsetDateTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/OffsetDateTime.html), [`OffsetTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/OffsetTime.html), or [`java.util.Date`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Date.html) but not [`java.sql.Time`](https://docs.oracle.com/en/java/javase/25/docs/api/java.sql/java/sql/Time.html) or [`java.sql.Date`](https://docs.oracle.com/en/java/javase/25/docs/api/java.sql/java/sql/Date.html), then it will be interpreted as polyglot `time zone`.; If the `hostValue` is an instance of [`ZonedDateTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/ZonedDateTime.html), [`OffsetDateTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/OffsetDateTime.html), [`Instant`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Instant.html), or [`java.util.Date`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Date.html) but not [`java.sql.Time`](https://docs.oracle.com/en/java/javase/25/docs/api/java.sql/java/sql/Time.html) or [`java.sql.Date`](https://docs.oracle.com/en/java/javase/25/docs/api/java.sql/java/sql/Date.html), then it will be interpreted as polyglot `instant`.; If the `hostValue` is an instance of [`Duration`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Duration.html) then it will be interpreted as polyglot `duration`.; If the `hostValue` is a `polyglot proxy`, then it will be interpreted according to the behavior specified by the proxy. See the javadoc of the proxy subclass for further details.; If the `hostValue` is a non-primitive `mapped Java value`, then the original value will be restored. For example, if a guest language object was mapped to [`Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html), then the original object identity will be preserved when converting back to a polyglot value.; Any other `hostValue` will be interpreted as `host object`. Host objects expose all their public java fields and methods as `members`. In addition, Java arrays, subtypes of [`List`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html) and [`Entry`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.Entry.html) will be interpreted as a value with `array elements`. The subtypes of [`Iterable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Iterable.html) will be interpreted as a value with `Value.hasIterator()` iterator}. The subtypes of [`Iterator`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Iterator.html) will be interpreted as an `iterator` value. The subtypes of [`Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html) will be interpreted as a value with `Value.hasHashEntries()` hash entries}. And single method interfaces annotated with [`FunctionalInterface`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/FunctionalInterface.html) are `executable` directly. Java [`Class`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Class.html) instances are interpreted as `instantiable`, but they do not expose Class methods as members. **Basic Examples:** The following assertion statements always hold: Mapping to Java methods and fields When Java host objects are passed to guest languages, their public methods and fields are provided as `members`. Methods and fields are grouped by name, so only one member is exposed for each name. [`Class`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Class.html) objects have a member named `static` referring to the class's companion object containing the static methods of the class. Likewise, the companion object has a member named `class` that points back to the class object. When an argument value needs to be mapped to match a required Java method parameter type, then the semantics of `host value mapping` is used. The result of the mapping is equivalent of calling `Value.as(Class)` with the parameter type. Therefore, a [`ClassCastException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/ClassCastException.html) or [`NullPointerException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/NullPointerException.html) is thrown if a parameter value cannot be cast to the required parameter type. Overloaded java methods are selected based on the provided arguments. In case multiple mapped Java methods with the same name are applicable for `executions` or `instantiations`, then the method with the most concrete method with applicable arguments will be called. The following parameter type hierarchy is used for a method resolution. Left-most parameter types are prioritized over types to their right. `Boolean` values: boolean, Boolean, Object; String values: char, Character, String, CharSequence, Object; Number values: byte, Byte, short, Short, int, Integer, long, Long, float, Float, double, Double, Number, Object; Other values are resolved based on their Java type hierarchy. If there are multiple concrete methods or too many arguments provided, then an illegal argument type error will be raised. **Advanced Example:** This example first creates a new instance of the Java class `Record` and inspects it using the polyglot value API. Later, a host value is converted to a polyglot value using JavaScript guest language. In the following examples all assertions hold. Parameters: `hostValue` `Object`: the host value to convert to a polyglot value. Returns `Value`: the polyglot value. Throws: `IllegalStateException` (unchecked): if the context is already closed. See also: `Value.as(Class)`. Cite: `org/graalvm/polyglot/Context.html#asValue(java.lang.Object)`
```java
Context context = Context.create();
assert context.asValue(null).isNull();
assert context.asValue(42).isNumber();
assert context.asValue("42").isString();
assert context.asValue('c').isString();
assert context.asValue(new String[0]).hasArrayElements();
assert context.asValue(new ArrayList<>()).isHostObject();
assert context.asValue(new ArrayList<>()).hasArrayElements();
assert context.asValue((Supplier) () -> 42).execute().asInt() == 42;
```
```java
class JavaRecord {
public int x = 42;
public double y = 42.0;
public String name() {
return "foo";
}
}
Context context = Context.create();
Value record = context.asValue(new JavaRecord());
assert record.getMember("x").asInt() == 42;
assert record.getMember("y").asDouble() == 42.0d;
assert record.getMember("name").execute().asString().equals("foo");
assert context.eval("js", "(function(record) record.x)")
.execute(record).asInt() == 42;
assert context.eval("js", "(function(record) record.y)")
.execute(record).asDouble() == 42.0d;
assert context.eval("js", "(function(record) record.name())")
.execute(record).asString().equals("foo");
```
### enter()
`public void enter()`. Since 19.0. Explicitly enters the context on the current thread. A context needs to be entered and left for any operation to be performed. For example, before and after invoking the `execute` method. This can be inefficient if a very high number of simple operations needs to be performed. By `entering` and `leaving` once explicitly, the overhead for entering/leaving the context for each operation can be eliminated. Contexts can be entered multiple times on the same thread. Throws: `IllegalStateException` (unchecked): if the context is already `closed`. `PolyglotException` (unchecked): if a language has denied execution on the current thread. See also: `leave a context.`. Cite: `org/graalvm/polyglot/Context.html#enter()`
### equals(Object)
`public boolean equals(Object obj)`. Since 19.0. Overrides `equals(java.lang.Object)`. Cite: `org/graalvm/polyglot/Context.html#equals(java.lang.Object)`
### hashCode()
`public int hashCode()`. Since 19.0. Overrides `hashCode()`. Cite: `org/graalvm/polyglot/Context.html#hashCode()`
### toString()
`public String toString()`. Since 25.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/Context.html#toString()`
### leave()
`public void leave()`. Since 19.0. Explicitly leaves the context on the current thread. The context must be `entered` before calling this method. Throws: `IllegalStateException` (unchecked): if the context is already closed or if the context was not `entered` on the current thread. See also: `enter a context.`. Cite: `org/graalvm/polyglot/Context.html#leave()`
### close(boolean)
`public void close(boolean cancelIfExecuting)`. Since 19.0. Closes the context and frees up potentially allocated native resources. A context cannot free all native resources allocated automatically. For this reason it is necessary to close contexts after use. If a context is cancelled, then the executing thread will throw a `PolyglotException`. The exception indicates that it was `cancelled`. Please note, canceling a single context can negatively affect the performance of other executing contexts constructed with the same engine. If internal errors occur during context closing, then they are printed to the configured `error output stream`. If a context was closed, then its methods will throw an [`IllegalStateException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html) when invoked. If an attempt to close a context was successful, then consecutive calls to close have no effect. For convenience, before the actual closing process begins, the close method leaves the context on the current thread, if it was entered `explicitly`. Parameters: `cancelIfExecuting` `boolean`: if `true` then currently executing contexts will be `cancelled`, else an [`IllegalStateException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html) is thrown. Throws: `PolyglotException` (unchecked): in case the close failed due to a guest language error, or, if cancelIfExecuting is `false`, the exception is also thrown when the context was `cancelled` or the context was `exited` at request of the guest application. `IllegalStateException` (unchecked): if the context is still running and cancelIfExecuting is `false`. See also: `close an engine.`. Cite: `org/graalvm/polyglot/Context.html#close(boolean)`
### close()
`public void close()`. Since 19.0. Closes this context and frees up potentially allocated native resources. A context may not free all native resources allocated automatically. For this reason it is recommended to close contexts after use. If the context is currently being executed on another thread, then an [`IllegalStateException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html) is thrown. To close concurrently executing contexts see `close(boolean)`. If internal errors occur during the context closure, then they are printed to the configured `error output stream`. If a context was closed, then its methods will throw an [`IllegalStateException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html), when invoked. If an attempt to close a context was successful, then consecutive calls to close have no effect. For convenience, before the actual closing process begins, the close method leaves the context on the current thread, if it was entered `explicitly`. Throws: `PolyglotException` (unchecked): in case the close failed due to a guest language error, or the context was `cancelled` or the context was `exited` at request of the guest application. `IllegalStateException` (unchecked): if the context is currently executing on another thread. Overrides `close()`. See also: `close an engine.`. Cite: `org/graalvm/polyglot/Context.html#close()`
### interrupt(Duration)
`public void interrupt(Duration timeout) throws TimeoutException`. Since 20.3. Use this method to interrupt this context. The interruption is non-destructive meaning the context is still usable after this method finishes. Please note that guest finally blocks are executed during interrupt. A context thread may not be interruptiple if it uses non-interruptible waiting or executes non-interruptible host code. This method may be used as a "soft cancel", meaning that it can be used before `close(true)` is executed. Parameters: `timeout` `Duration`: specifies the duration the interrupt method will wait for the active threads of the context to be finished. Setting the duration to [`0`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Duration.html#ZERO) means wait indefinitely. Throws: `IllegalStateException` (unchecked): in case the context is entered in the current thread. `TimeoutException`: in case the interrupt was not successful, i.e., not all threads were finished within the specified time limit. Cite: `org/graalvm/polyglot/Context.html#interrupt(java.time.Duration)`
### safepoint()
`public void safepoint()`. Since 21.1. Polls safepoints events and executes them for the current thread. This allows guest languages to run actions between long-running host method calls. Polyglot embeddings that rely on cancellation should call this method whenever a potentially long-running host operation is executed. For example, iterating an unbounded array. Guest language code and operations automatically poll safepoints regularly. In this example we allow `interruption` and `cancellation` to stop the processing of our event queue. Throws: `PolyglotException` (unchecked): in case the close failed due to a guest language error. `IllegalStateException` (unchecked): if the context is already `closed`. Cite: `org/graalvm/polyglot/Context.html#safepoint()`
```java
class EventProcessor {
List events = new ArrayDeque(); // list of arbitrary size
public void processEvents() {
Context context = Context.getCurrent();
while (Object event = events.pop()) {
// process event
// allow cancellation and interruptions
try {
context.safepoint();
} catch (PolyglotException e) {
if (e.isInterrupted() || e.isCancelled()) {
// break event processing if interrupted or cancelled
throw e;
}
// other handling of guest errors or rethrow
}
}
}
}
```
### getCurrent()
`public static Context getCurrent()`. Since 19.0. Returns the currently entered polyglot context. A context will be entered if the current executing Java method is called by a Graal guest language or if a context is entered explicitly using `Context.enter()` on the current thread. The returned context may be used to: Evaluate guest language code from `string literals` or `file` sources.; `Convert` Java values to `polyglot values`.; Access top-level `bindings` of other languages.; Access `polyglot bindings`.; Access meta-data like available `languages` or `options` of the `engine`. The returned context can **not** be used to `enter` , `leave` or `close` the context or `engine`. Invoking such methods will cause an [`IllegalStateException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html) to be thrown. This ensures that only the `creator` of a context is allowed to enter, leave or close a context. The current entered context may change. It is therefore required to call `getCurrent` every time a context is needed. The current entered context should not be cached in static fields. Throws: `IllegalStateException` (unchecked): if no context is currently entered. Cite: `org/graalvm/polyglot/Context.html#getCurrent()`
### create(String...)
`public static Context create(String... permittedLanguages)`. Since 19.0. Creates a context with default configuration. This method is a shortcut for `newBuilder(permittedLanguages).build()`. See also: `newBuilder(String...)`. Cite: `org/graalvm/polyglot/Context.html#create(java.lang.String...)`
### newBuilder(String...)
`public static Context.Builder newBuilder(String... permittedLanguages)`. Since 19.0. Creates a builder for constructing a context with custom configuration. Parameters: `permittedLanguages` `String...`: names of languages permitted in the context. If no languages are provided, then all installed languages will be permitted. If an explicit `engine` was specified then only those languages may be used that were installed and `permitted` by the specified engine. Languages are validated when the context is `built`. An [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) will be thrown if an unknown or a language denied by the engine was used. Returns `Context.Builder`: a builder that can create a context. Cite: `org/graalvm/polyglot/Context.html#newBuilder(java.lang.String...)`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ Context.Builder
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0. Nested in [`Context`](org/graalvm/polyglot/Context.md).
```java
public final class Context.Builder
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `Builder`
Builder class to construct [`Context`](org/graalvm/polyglot/Context.md) instances. A builder instance is not thread-safe and must not be used from multiple threads at the same time.
**See also**
- [`Context`](org/graalvm/polyglot/Context.md)
## Methods
### apply(Consumer)
`public Context.Builder apply(Consumer action)`. Since 25.0. Applies the provided Consumer to this Builder instance. This method allows encapsulating complex Builder configuration logic into separate methods while maintaining the fluent API of `Context.Builder`. Example. Parameters: `action` `Consumer`: The Consumer that configures this Builder instance; it is not supposed to finalize the Builder using `build()`. Cite: `org/graalvm/polyglot/Context.Builder.html#apply(java.util.function.Consumer)`
```java
private void configureEnv(Builder builder) {
return builder.environment("DEBUG", appConfiguration.isDebugMode())
.environment("APP_NAME", appConfiguration.getApplicationName())
.environment("JAVA_VER", System.getProperty("java.version"))@
}
public Context createContext() {
return Context.newBuilder()
.apply(this::configureEnv)
.allowNativeAccess(true)
.build();
}
```
### engine(Engine)
`public Context.Builder engine(Engine engine)`. Since 19.0. Explicitly sets the underlying engine to use. By default, every context has its own isolated engine. If multiple contexts are created from one engine, then they may share/cache certain system resources like ASTs or optimized code by specifying a single underlying engine. See `Engine` for more details about system resource sharing. Cite: `org/graalvm/polyglot/Context.Builder.html#engine(org.graalvm.polyglot.Engine)`
### out(OutputStream)
`public Context.Builder out(OutputStream out)`. Since 19.0. Sets the standard output stream to be used for the context. If not set, then the standard output stream configured for the `engine` or standard error stream is used. Cite: `org/graalvm/polyglot/Context.Builder.html#out(java.io.OutputStream)`
### err(OutputStream)
`public Context.Builder err(OutputStream err)`. Since 19.0. Sets the error output stream to be used for the context. If not set, then either the error stream configured for the `engine` or standard error stream is used. Cite: `org/graalvm/polyglot/Context.Builder.html#err(java.io.OutputStream)`
### in(InputStream)
`public Context.Builder in(InputStream in)`. Since 19.0. Sets the input stream to be used for the context. If not set, then either the input stream configured for the `engine` or standard in stream is used. Cite: `org/graalvm/polyglot/Context.Builder.html#in(java.io.InputStream)`
### allowHostAccess(boolean)
`@Deprecated(since = "19.0") public Context.Builder allowHostAccess(boolean enabled)`. Since 19.0. Deprecated since 19.0. use `allowHostAccess(HostAccess)` or `allowHostClassLookup(Predicate)` instead. Allows guest languages to access the host language by loading new classes. Default is `false`. If `all access` is set to `true`, then host access is enabled if not disallowed explicitly. Cite: `org/graalvm/polyglot/Context.Builder.html#allowHostAccess(boolean)`
### allowHostAccess(HostAccess)
`public Context.Builder allowHostAccess(HostAccess config)`. Since 19.0. Configures which public constructors, methods or fields of public classes are accessible by guest applications. By default if `allowAllAccess(boolean)` is `false` the `HostAccess.EXPLICIT` policy will be used, otherwise `HostAccess.ALL`. Repeated calls of this method on the same `Context.Builder` instance override the previously set `HostAccess` configuration. Use `extendHostAccess(HostAccess, Consumer)` for composable `HostAccess` configuration. See also: `EXPLICIT - to allow explicitly annotated constructors, methods or fields.`, `ALL - to allow unrestricted access (use only for trusted guest applications).`, `NONE - to not allow any access.`, `newBuilder() - to create a custom configuration.`, `- for composable HostAccess configuration.`. Cite: `org/graalvm/polyglot/Context.Builder.html#allowHostAccess(org.graalvm.polyglot.HostAccess)`
### extendHostAccess(HostAccess, Consumer)
`public Context.Builder extendHostAccess(HostAccess defaultInitialValue, Consumer setup)`. Since 25.0. Extends the existing host access configuration that determines, which public constructors, methods or fields of public classes are accessible by guest applications. This method allows composing code that configures `HostAccess`. The provided `setup` is applied to a `HostAccess.Builder` instance, which is initialized with the current `HostAccess` configuration. If no `HostAccess` configuration exists, the `defaultInitialValue` is used to initialize the builder. Example usage In this example the call to `extendHostAccess` in `MyArrayWrapper::addMapping` does not override the `HostAccess.ALL` configured before. Using `allowHostAccess(HostAccess)` in this situation would override the previous configuration. Parameters: `defaultInitialValue` `HostAccess`: - the initial value to use if no `HostAccess` is configured. `setup` `Consumer`: - Consumer that receives a `HostAccess.Builder` preconfigured with the current `HostAccess` configuration. Returns `Context.Builder`: the `Builder`. See also: `- to set or override existing HostAccess configuration.`, `- to extend existing IOAccess configuration.`. Cite: `org/graalvm/polyglot/Context.Builder.html#extendHostAccess(org.graalvm.polyglot.HostAccess,java.util.function.Consumer)`
```java
public static final class MyArrayWrapper {
private final Value v;
private MyArrayWrapper(Value v) {
this.v = v;
}
// ...
public static void addMapping(Context.Builder builder) {
builder.extendHostAccess(HostAccess.NONE,
b -> b.targetTypeMapping(Value.class, MyArrayWrapper.class,
Value::hasArrayElements,
MyArrayWrapper::new));
}
}
// ...
public Context createContext() {
return Context.newBuilder().
.allowHostAccess(HostAccess.ALL)
.apply(MyArrayWrapper::addMapping)
// ...
.build();
}
```
### allowNativeAccess(boolean)
`public Context.Builder allowNativeAccess(boolean enabled)`. Since 19.0. Allows guest languages to access the native interface. Cite: `org/graalvm/polyglot/Context.Builder.html#allowNativeAccess(boolean)`
### allowCreateThread(boolean)
`public Context.Builder allowCreateThread(boolean enabled)`. Since 19.0. If `true`, allows guest languages to create new threads. Default is `false`. If `all access` is set to `true`, then the creation of threads is enabled if not allowed explicitly. Threads created by guest languages are closed, when the context is `closed`. Cite: `org/graalvm/polyglot/Context.Builder.html#allowCreateThread(boolean)`
### allowAllAccess(boolean)
`public Context.Builder allowAllAccess(boolean enabled)`. Since 19.0. Sets the default value for all privileges. If not explicitly specified, then all access is `false`. If all access is enabled then certain privileges may still be disabled by configuring it explicitly using the builder (either before or after the call to `allowAllAccess()`). Allowing all access should only be set if the guest application is fully trusted. If `true`, grants the context the same access privileges as the host virtual machine. If the host VM runs without a [`security manager`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/SecurityManager.html) enabled, then enabling all access gives the guest languages full control over the host process. Otherwise, Java [`security manager`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/SecurityManager.html) is in control of restricting the privileges of the polyglot context. If new privilege restrictions are added to the polyglot API, then they will default to full access. Grants full access to the following privileges by default: The `creation` and use of new threads.; The access to public `host classes`.; The loading of new `host classes` by adding entries to the class path.; Exporting new members into the polyglot `bindings`.; Unrestricted `IO operations` on host system.; Passing `experimental options`.; The `creation` and use of new sub-processes.; The `access` to process environment variables.; The `changing` of options for of inner contexts spawned by the language. Parameters: `enabled` `boolean`: `true` for all access by default. Cite: `org/graalvm/polyglot/Context.Builder.html#allowAllAccess(boolean)`
### allowHostClassLoading(boolean)
`public Context.Builder allowHostClassLoading(boolean enabled)`. Since 19.0. If host class loading is enabled, then the guest language is allowed to load new host classes via jar or class files. If `all access` is set to `true`, then the host class loading is enabled if it is not disallowed explicitly. For host class loading to be useful, `IO` operations `host class lookup`, and the `host access policy` needs to be configured as well. See also: `allowHostAccess(HostAccess)`, `allowHostClassLookup(Predicate)`. Cite: `org/graalvm/polyglot/Context.Builder.html#allowHostClassLoading(boolean)`
### allowHostClassLookup(Predicate)
`public Context.Builder allowHostClassLookup(Predicate classFilter)`. Since 19.0. Sets a filter that specifies the Java host classes that can be looked up by the guest application. If set to `null` then no class lookup is allowed and relevant language builtins are not available (e.g. `Java.type` in JavaScript). If the `classFilter` parameter is set to a filter predicate, then language builtins are available and classes can be looked up if the filter predicate returns `true` for the fully qualified class name. If the filter returns `false`, then the class cannot be looked up and as a result throws a guest language error when accessed. By default and if `all access` is `false`, host class lookup is disabled. By default and if `all access` is `true`, then all classes may be looked up by the guest application. In order to access class members looked up by the guest application a `host access policy` needs to be set or `all access` needs to be set to `true`. To load new classes the context uses the `hostClassLoader` if specified or the [`context class loader`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Thread.html#getContextClassLoader%28%29) that will be captured when the context is `built`. If an explicit `engine` was specified, then the context class loader at engine `build-time` will be used instead. When the Java module system is available (\>= JDK 9) then only classes are accessible that are exported to the unnamed module of the captured class loader. Example usage with JavaScript: In this example: We create a new context with the `permission` to look up the class `myPackage.MyClass` in the guest language application.; We evaluate a JavaScript code snippet that accesses the Java class `myPackage.MyClass` using the `Java.type` builtin provided by the JavaScript language implementation. Other classes can only be looked up if the provided class filter returns `true` for their name.; We create a new instance of the Java class `MyClass` by using the JavaScript `new` keyword.; We call the method `accessibleMethod` which returns `42`. The method is accessible to the guest language because because the enclosing class and the declared method are public, as well as annotated with the `@HostAccess.Export` annotation. Which Java members of classes are accessible can be configured using the `host access policy`. Parameters: `classFilter` `Predicate`: a predicate that returns `true` or `false` for a qualified Java class name or `null` to disable host class lookup. See also: `allowHostClassLoading - to allow loading of classes.`, `allowHostAccess - to configure the access policy of host values for guest languages.`. Cite: `org/graalvm/polyglot/Context.Builder.html#allowHostClassLookup(java.util.function.Predicate)`
```java
public class MyClass {
@HostAccess.Export
public int accessibleMethod() {
return 42;
}
public static void main(String[] args) {
try (Context context = Context.newBuilder() //
.allowHostClassLookup(c -> c.equals("myPackage.MyClass")) //
.build()) {
int result = context.eval("js", "" +
"var MyClass = Java.type('myPackage.MyClass');" +
"new MyClass().accessibleMethod()").asInt();
assert result == 42;
}
}
}
```
### allowExperimentalOptions(boolean)
`public Context.Builder allowExperimentalOptions(boolean enabled)`. Since 19.0. Allow experimental options to be used for language options. Do not use experimental options in production environments. If set to `false` (the default), then passing an experimental option results in an [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) when the context is built. Alternatively `Engine.Builder.allowExperimentalOptions(boolean)` may be used when constructing the context using an `explicit engine`. Cite: `org/graalvm/polyglot/Context.Builder.html#allowExperimentalOptions(boolean)`
### allowPolyglotAccess(PolyglotAccess)
`public Context.Builder allowPolyglotAccess(PolyglotAccess accessPolicy)`. Since 19.0. Allow polyglot access using the provided policy. If `all access` is `true` then the default polyglot access policy is `PolyglotAccess.ALL`, otherwise `PolyglotAccess.NONE`. The provided access policy must not be `null`. Cite: `org/graalvm/polyglot/Context.Builder.html#allowPolyglotAccess(org.graalvm.polyglot.PolyglotAccess)`
### allowValueSharing(boolean)
`public Context.Builder allowValueSharing(boolean enabled)`. Since 21.3. Enables or disables sharing of any `value` between contexts. Value sharing is enabled by default and is not affected by `allowAllAccess(boolean)`. If this option is set to `true` (default) then any value that is associated with one context will be automatically migrated when passed to another context. Primitive, `host` and `proxy` values can be migrated without limitation. When guest language values are migrated, they capture and remember their original context. Guest language objects need to be accessed when their respective context is `entered`, therefore before any access their original context is entered and subsequently left. Entering the original context may fail, for example when the context of a original context value only allows single threaded access to values or if it was `closed` in the mean time. If this option is set to `false` then any value passed from one context to another will fail with an error indicating that sharing is disallowed. Turning sharing off can be useful when strict safety is required and it would be considered an error if a value of one context is passed to another. Values of a guest language that are passed from one context to another are restricted to using the interoperability protocol only. In practice this often leads to slight changes and incompatibilities in behavior. For example, the prototype of a JavaScript object passed from one context to another is not writable, as the interoperability protocol does not allow such an operation (yet). A typical use-case is passing big immutable data structures that are infrequently accessed from one context to another, without copying them. In practice, passing values from one context to another should be avoided if possible, as their access is slower and their language compatibility reduced. This feature was introduced in 21.3. Older versions fail when guest values are passed from one context to another. Cite: `org/graalvm/polyglot/Context.Builder.html#allowValueSharing(boolean)`
### allowInnerContextOptions(boolean)
`public Context.Builder allowInnerContextOptions(boolean enabled)`. Since 22.3. Allows this context to spawn inner contexts that may change option values set for the outer context. If this privilege is set to `false` then inner contexts are only allowed to use the same option values as its outer context. If this privilege is set to `true` then the context may modify option values for inner contexts it creates. This privilege should not be enabled for security sensitive use-cases. The default value for this privilege is inherited from `allowAllAccess(boolean)`. Inner contexts are spawned by language implementations to implement language embeddings of their own. For example, some languages provide dedicated APIs to spawn language virtual machines. Such APIs are often implemented using the inner context mechanism. See also: `allowAllAccess(boolean)`. Cite: `org/graalvm/polyglot/Context.Builder.html#allowInnerContextOptions(boolean)`
### hostClassFilter(Predicate)
`@Deprecated(since = "19.0") public Context.Builder hostClassFilter(Predicate classFilter)`. Since 19.0. Deprecated since 19.0. use `allowHostClassLookup(Predicate)` instead. Sets a class filter that allows to limit the classes that are allowed to be loaded by guest languages. If the filter returns `true`, then the class is accessible, otherwise it is not accessible and throws a guest language error when accessed. In order to have an effect, `allowHostAccess(org.graalvm.polyglot.HostAccess)` or `allowAllAccess(boolean)` needs to be set to `true`. Parameters: `classFilter` `Predicate`: a predicate that returns `true` or `false` for a java qualified class name. Cite: `org/graalvm/polyglot/Context.Builder.html#hostClassFilter(java.util.function.Predicate)`
### option(String, String)
`public Context.Builder option(String key, String value)`. Since 19.0. Sets an option for this `context`. By default, any options for the `engine`, `language` or `instrument` can be set for a context. If an `explicit engine` is set for the context, then only language options can be set. Instrument and engine options can be set exclusively on the explicit engine instance. If a language option is set for the context and the engine, then the option of the context is going to take precedence. If one of the set option keys or values is invalid, then an [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) is thrown when the context is `built`. The given key and value must not be `null`. See also: `To specify an option for the engine.`. Cite: `org/graalvm/polyglot/Context.Builder.html#option(java.lang.String,java.lang.String)`
### options(Map)
`public Context.Builder options(Map options)`. Since 19.0. Shortcut for setting multiple `options` using a map. All values of the provided map must be non-null. Parameters: `options` `Map`: a map options. See also: `To set a single option.`. Cite: `org/graalvm/polyglot/Context.Builder.html#options(java.util.Map)`
### arguments(String, String[])
`public Context.Builder arguments(String language, String[] args)`. Since 19.0. Sets the guest language application arguments for a language `context`. Application arguments are typically made available to guest language implementations. It depends on the language if and how they are accessible within the `evaluated` guest language scripts. Passing no arguments to a language is equivalent to providing an empty arguments array. Parameters: `language` `String`: the language id of the primary language. `args` `String[]`: an array of arguments passed to the guest language program. Throws: `IllegalArgumentException` (unchecked): if an invalid language id was specified. Cite: `org/graalvm/polyglot/Context.Builder.html#arguments(java.lang.String,java.lang.String[])`
### allowIO(IOAccess)
`public Context.Builder allowIO(IOAccess ioAccess)`. Since 23.0. Configures guest language access to host IO. Default is `IOAccess.NONE`. If `all access` is set to `true`, then `IOAccess.ALL` is used unless explicitly set. This method can be used to virtualize file system access in the guest language by using an `IOAccess` with a custom filesystem. Repeated calls of this method on the same `Context.Builder` instance override the previously set `IOAccess` configuration. Use `extendIO(IOAccess, Consumer)` for composable `IOAccess` configuration. Parameters: `ioAccess` `IOAccess`: the IO configuration. Returns `Context.Builder`: the `Builder`. See also: `- to allow full host IO access.`, `- to disable host IO access.`, `- to create a custom configuration.`, `- for composable IOAccess configuration.`. Cite: `org/graalvm/polyglot/Context.Builder.html#allowIO(org.graalvm.polyglot.io.IOAccess)`
### allowIO(boolean)
`@Deprecated(since = "23.0") public Context.Builder allowIO(boolean enabled)`. Since 19.0. Deprecated since 23.0. If the value was previously `true` pass `IOAccess.ALL`, otherwise pass `IOAccess.NONE`. If `true`, allows guest language to perform unrestricted IO operations on host system. Default is `false`. If `all access` is set to `true`, then IO is enabled if not allowed explicitly. Parameters: `enabled` `boolean`: `true` to enable Input/Output. Returns `Context.Builder`: the `Builder`. Cite: `org/graalvm/polyglot/Context.Builder.html#allowIO(boolean)`
### extendIO(IOAccess, Consumer)
`public Context.Builder extendIO(IOAccess defaultInitialValue, Consumer setup)`. Since 25.0. Extends the existing guest language access to host IO configuration. This method allows composing code that configures `IOAccess`. The provided `setup` is applied to a `IOAccess.Builder` instance, which is initialized with the current `IOAccess` configuration. If no `IOAccess` configuration exists, the `defaultInitialValue` is used to initialize the builder. Example usage In this example the call to `extendIOAccess` does not override the `FileSystem` configured in `addFileSystem`. Using `allowIO(IOAccess)` in this situation would override the configured `FileSystem`. Parameters: `defaultInitialValue` `IOAccess`: - the initial value to use if no `IOAccess` is configured. `setup` `Consumer`: - Consumer that receives a `IOAccess.Builder` preconfigured with the current `IOAccess` configuration. Returns `Context.Builder`: the `Builder`. See also: `- to set or override existing IOAccess.`, `- to extend existing HostAccess configuration.`. Cite: `org/graalvm/polyglot/Context.Builder.html#extendIO(org.graalvm.polyglot.io.IOAccess,java.util.function.Consumer)`
```java
private void addFileSystem(IOAccess.Builder builder) {
builder.fileSystem(new MyCustomFileSystem());
}
public Context createContext() {
return Context.newBuilder().extendIOAccess(IOAccess.NONE, this::addFileSystem)
// ...
.extendIOAccess(IOAccess.NONE, b -> b.allowHostSocketAccess(true))
// ...
.build();
}
```
### fileSystem(FileSystem)
`@Deprecated(since = "23.0") public Context.Builder fileSystem(FileSystem fileSystem)`. Since 19.0. Deprecated since 23.0. If a file system was previously set use `allowIO(IOAccess.newBuilder().fileSystem(fileSystem).build())`. Installs a new `FileSystem`. Parameters: `fileSystem` `FileSystem`: the file system to be installed. Returns `Context.Builder`: the `Builder`. Cite: `org/graalvm/polyglot/Context.Builder.html#fileSystem(org.graalvm.polyglot.io.FileSystem)`
### serverTransport(MessageTransport)
`public Context.Builder serverTransport(MessageTransport serverTransport)`. Since 19.0. Take over the transport of messages communication with a server peer. Provide an implementation of `MessageTransport` to virtualize a transport of messages to a server endpoint. `MessageTransport.open(java.net.URI, org.graalvm.polyglot.io.MessageEndpoint)` corresponds to accept of a server socket. Parameters: `serverTransport` `MessageTransport`: an implementation of message transport interceptor. See also: `MessageTransport`. Cite: `org/graalvm/polyglot/Context.Builder.html#serverTransport(org.graalvm.polyglot.io.MessageTransport)`
### logHandler(Handler)
`public Context.Builder logHandler(Handler logHandler)`. Since 19.0. Installs a new logging [`Handler`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Handler.html). The logger's [`Level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html) configuration is done using the `Context's options`. The level option key has the following format: `log.languageId.loggerName.level` or `log.instrumentId.loggerName.level`. The value is either the name of a pre-defined [`Level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html) constant or a numeric [`Level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html) value. If not explicitly set in options, the level is inherited from the parent logger. **Examples** of setting log level options: `builder.option("log.level","FINE");` sets the [`FINE level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html#FINE) to all `TruffleLogger`s. `builder.option("log.js.level","FINE");` sets the [`FINE level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html#FINE) to JavaScript `TruffleLogger`s. `builder.option("log.js.com.oracle.truffle.js.parser.JavaScriptLanguage.level","FINE");` sets the [`FINE level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html#FINE) to `TruffleLogger` for the `JavaScriptLanguage` class. If the `logHandler` is not set on `Engine` nor on `Context`, the log messages are printed to `Context's error output stream`. Parameters: `logHandler` `Handler`: the [`Handler`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Handler.html) to use for logging in built `Context`. The passed `logHandler` is closed when the context is `closed`. Returns `Context.Builder`: the `Builder`. Cite: `org/graalvm/polyglot/Context.Builder.html#logHandler(java.util.logging.Handler)`
### logHandler(OutputStream)
`public Context.Builder logHandler(OutputStream logOut)`. Since 19.0. Installs a new logging [`Handler`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Handler.html) using given [`OutputStream`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/OutputStream.html). The logger's [`Level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html) configuration is done using the `Context's options`. The level option key has the following format: `log.languageId.loggerName.level` or `log.instrumentId.loggerName.level`. The value is either the name of pre-defined [`Level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html) constant or a numeric [`Level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html) value. If not explicitly set in options the level is inherited from the parent logger. **Examples** of setting log level options: `builder.option("log.level","FINE");` sets the [`FINE level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html#FINE) to all `TruffleLogger`s. `builder.option("log.js.level","FINE");` sets the [`FINE level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html#FINE) to JavaScript `TruffleLogger`s. `builder.option("log.js.com.oracle.truffle.js.parser.JavaScriptLanguage.level","FINE");` sets the [`FINE level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html#FINE) to `TruffleLogger` for the `JavaScriptLanguage` class. If the `logHandler` is not set on `Engine` nor on `Context` the log messages are printed to `Context's standard output stream`. Parameters: `logOut` `OutputStream`: the [`OutputStream`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/OutputStream.html) to use for logging in built `Context`. The passed `logOut` stream is closed when the context is `closed`. Returns `Context.Builder`: the `Builder`. Cite: `org/graalvm/polyglot/Context.Builder.html#logHandler(java.io.OutputStream)`
### timeZone(ZoneId)
`public Context.Builder timeZone(ZoneId zone)`. Since 19.2.0. Sets the default time zone to be used for this context. If not set, or explicitly set to `null`, then UTC is used with `SandboxPolicy.CONSTRAINED` or stricter sandbox policies, and the [`system default`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/ZoneId.html#systemDefault%28%29) zone is used otherwise. Returns `Context.Builder`: the `Builder`. See also: [`ZoneId.systemDefault()`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/ZoneId.html#systemDefault%28%29). Cite: `org/graalvm/polyglot/Context.Builder.html#timeZone(java.time.ZoneId)`
### allowCreateProcess(boolean)
`public Context.Builder allowCreateProcess(boolean enabled)`. Since 19.1.0. If `true`, allows guest language to execute external processes. Default is `false`. If `all access` is set to `true`, then process creation is enabled if not denied explicitly. Parameters: `enabled` `boolean`: `true` to enable external process creation. Cite: `org/graalvm/polyglot/Context.Builder.html#allowCreateProcess(boolean)`
### processHandler(ProcessHandler)
`public Context.Builder processHandler(ProcessHandler handler)`. Since 19.1.0. Installs a `ProcessHandler` responsible for external process creation. Parameters: `handler` `ProcessHandler`: the handler to be installed. Cite: `org/graalvm/polyglot/Context.Builder.html#processHandler(org.graalvm.polyglot.io.ProcessHandler)`
### resourceLimits(ResourceLimits)
`public Context.Builder resourceLimits(ResourceLimits limits)`. Since 19.3.0. Assigns resource limit configuration to a context. By default no resource limits are assigned. The limits will be enabled for all contexts created using this builder. Assigning a limit may have performance impact of all contexts that run with the same engine. See also: `for usage examples`. Cite: `org/graalvm/polyglot/Context.Builder.html#resourceLimits(org.graalvm.polyglot.ResourceLimits)`
### exceptionHandler(Consumer)
`public Context.Builder exceptionHandler(Consumer handler)`. Since 25.1. Sets an exception handler that is invoked whenever a `PolyglotException` is about to be thrown from a context bound value back to the host. The handler is called on the host thread that performs the polyglot operation, for example when invoking `Value` methods, executing guest code, or initializing a language. It receives the `PolyglotException` that would normally be thrown to the caller. The handler can inspect the exception, perform additional logging or metrics, or translate the `PolyglotException` into a different exception type. If the handler throws an exception, that exception is propagated to the caller instead of the original `PolyglotException`. If the handler returns normally, the original `PolyglotException` is thrown as usual. A common use case is to unwrap and rethrow host runtime exceptions so that calling code can handle them directly: In this example, `Value.throwException()` would normally throw a `PolyglotException`. Because the handler rethrows the underlying host [`RuntimeException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/RuntimeException.html), the caller observes `IllegalStateException` directly instead of `PolyglotException`. Handlers should be written carefully, because any host call into the context can then appear to throw additional exception types. In particular, translating guest exceptions into unrelated runtime exceptions can make APIs harder to reason about and should only be done with care. When this builder is used together with an explicit `Engine`, and that engine has an exception handler configured, the context must either use the same handler instance or `null`. Using a different handler instance and an explicit engine at the same time causes `build()` to fail with an [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html). Passing `null` lets the context inherit the handler configured on the engine. Parameters: `handler` `Consumer`: the handler to invoke before a `PolyglotException` is thrown to the host, or `null` to disable custom handling and, when an explicit engine is used, inherit the handler from that engine. See also: `Engine.Builder.exceptionHandler(Consumer)`. Cite: `org/graalvm/polyglot/Context.Builder.html#exceptionHandler(java.util.function.Consumer)`
```java
static void rethrowHostRuntimeException(PolyglotException e) {
if (e.isHostException()) {
Throwable t = e.asHostException();
if (t instanceof RuntimeException rt) {
// rethrow the original host runtime exception
throw rt;
}
}
// fall through, the PolyglotException will be thrown
}
try (Context c = Context.newBuilder()
.exceptionHandler(MyHost::rethrowHostRuntimeException)
.build()) {
try {
// Without an exception handler, this would throw a PolyglotException
// wrapping the IllegalStateException as a host exception.
c.asValue(new IllegalStateException("test")).throwException();
} catch (IllegalStateException e) {
// The handler rethrew the original host exception.
assert "test".equals(e.getMessage());
}
}
```
### sandbox(SandboxPolicy)
`public Context.Builder sandbox(SandboxPolicy policy)`. Since 23.0. Sets a code sandbox policy to a context. By default, the context's sandbox policy is `SandboxPolicy.TRUSTED`, there are no restrictions to the context configuration. See also: `SandboxPolicy`. Cite: `org/graalvm/polyglot/Context.Builder.html#sandbox(org.graalvm.polyglot.SandboxPolicy)`
### allowEnvironmentAccess(EnvironmentAccess)
`public Context.Builder allowEnvironmentAccess(EnvironmentAccess accessPolicy)`. Since 19.1.0. Allow environment access using the provided policy. If `all access` is `true` then the default environment access policy is `EnvironmentAccess.INHERIT`, otherwise `EnvironmentAccess.NONE`. The provided access policy must not be `null`. Parameters: `accessPolicy` `EnvironmentAccess`: the `environment access policy`. Cite: `org/graalvm/polyglot/Context.Builder.html#allowEnvironmentAccess(org.graalvm.polyglot.EnvironmentAccess)`
### environment(String, String)
`public Context.Builder environment(String name, String value)`. Since 19.1.0. Sets an environment variable. Parameters: `name` `String`: the environment variable name. `value` `String`: the environment variable value. Cite: `org/graalvm/polyglot/Context.Builder.html#environment(java.lang.String,java.lang.String)`
### environment(Map)
`public Context.Builder environment(Map env)`. Since 19.1.0. Shortcut for setting multiple `environment variables` using a map. All values of the provided map must be non-null. Parameters: `env` `Map`: environment variables. See also: `To set a single environment variable.`. Cite: `org/graalvm/polyglot/Context.Builder.html#environment(java.util.Map)`
### currentWorkingDirectory(Path)
`public Context.Builder currentWorkingDirectory(Path workingDirectory)`. Since 20.0.0. Sets the current working directory used by the guest application to resolve relative paths. When the Context is built, the given directory is set as the current working directory on the Context's file system using the `FileSystem.setCurrentWorkingDirectory` method. Parameters: `workingDirectory` `Path`: the new current working directory. Throws: `NullPointerException` (unchecked): when `workingDirectory` is `null`. `IllegalArgumentException` (unchecked): when `workingDirectory` is a relative path. Cite: `org/graalvm/polyglot/Context.Builder.html#currentWorkingDirectory(java.nio.file.Path)`
### hostClassLoader(ClassLoader)
`public Context.Builder hostClassLoader(ClassLoader classLoader)`. Since 20.1.0. Sets a host class loader. If set the given `classLoader` is used to load host classes and it's also set as a [`context ClassLoader`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Thread.html#setContextClassLoader%28java.lang.ClassLoader%29) during code execution. Otherwise the ClassLoader that was captured when the context was `built` is used to load host classes and the [`context ClassLoader`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Thread.html#setContextClassLoader%28java.lang.ClassLoader%29) is not set during code execution. Setting the hostClassLoader has a negative effect on enter and leave performance. Parameters: `classLoader` `ClassLoader`: the host class loader. Cite: `org/graalvm/polyglot/Context.Builder.html#hostClassLoader(java.lang.ClassLoader)`
### useSystemExit(boolean)
`public Context.Builder useSystemExit(boolean enabled)`. Since 22.0. Specifies whether [`System.exit(int)`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/System.html#exit%28int%29) may be used to improve efficiency of stack unwinding for context exit requested by the guest application. See also: `Context`. Cite: `org/graalvm/polyglot/Context.Builder.html#useSystemExit(boolean)`
### spawnIsolate(boolean)
`public Context.Builder spawnIsolate(boolean value)`. Since 25.1. Specifies whether the implicitly created engine should run guest languages in a polyglot isolate. A polyglot isolate executes guest languages with an isolated heap. This can be useful for sandboxing and for running guest languages as native images when the current runtime does not support optimizing guest language execution. If enabled, all languages permitted by this context are run in the isolate. If `value` is `true`, this builder must have been created with an explicit permitted languages list, for example using `Context.newBuilder("js")`. This setting is equivalent to setting the `engine.SpawnIsolate` engine option to `true` or `false`. If both are set to conflicting values, `build()` fails with [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html). For contexts that use an explicit engine, configure isolate spawning on the engine builder rather than on the context builder. Parameters: `value` `boolean`: `true` to spawn a polyglot isolate. See also: `Engine.Builder.spawnIsolate(boolean)`, `Engine.supportsCompilation()`, [ Polyglot Isolates documentation](https://www.graalvm.org/latest/reference-manual/embed-languages/#polyglot-isolates). Cite: `org/graalvm/polyglot/Context.Builder.html#spawnIsolate(boolean)`
### build()
`public Context build()`. Since 19.0. Creates a new context instance from the configuration provided in the builder. The same context builder can be used to create multiple context instances. Cite: `org/graalvm/polyglot/Context.Builder.html#build()`
### toString()
`public String toString()`. Since 25.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/Context.Builder.html#toString()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ Engine
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0.
```java
public final class Engine implements AutoCloseable
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `Engine`
Implements: [`AutoCloseable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AutoCloseable.html)
An execution engine for Graal [guest languages](org/graalvm/polyglot/Language.md) that allows to inspect the the installed [`guest languages`](org/graalvm/polyglot/Engine.md#getLanguages%28%29), [`instruments`](org/graalvm/polyglot/Engine.md#getInstruments%28%29) and their available options.
By default every context creates its own [`engine`](org/graalvm/polyglot/Engine.md) instance implicitly when [`instantiated`](org/graalvm/polyglot/Context.Builder.md#build%28%29). Multiple contexts can use an [`explicit engine`](org/graalvm/polyglot/Context.Builder.md#engine%28org.graalvm.polyglot.Engine%29) when using a context builder. If contexts share the same engine instance then they share instruments and their configuration.
It can be useful to [`create`](org/graalvm/polyglot/Engine.md#create%28%29) an engine instance without a context to only access meta-data for installed languages, instruments and their available options.
## Nested types
- [`Engine.Builder`](org/graalvm/polyglot/Engine.Builder.md) (class): No description.
- [`Engine.CancellationCallback`](org/graalvm/polyglot/Engine.CancellationCallback.md) (interface): A callback that is invoked repeatedly while persisting the auxiliary engine cache.
- [`Engine.Preinitialized`](org/graalvm/polyglot/Engine.Preinitialized.md) (class): Prepared engine state that can be consumed by one engine build.
## Methods
### getLanguages()
`public Map getLanguages()`. Since 19.0. Gets a map of all installed languages with the language id as key and the language object as value. The returned map is unmodifiable and might be used from multiple threads. Cite: `org/graalvm/polyglot/Engine.html#getLanguages()`
### getInstruments()
`public Map getInstruments()`. Since 19.0. Gets all installed instruments of this engine. An instrument alters and/or monitors the execution of guest language source code. Common examples for instruments are debuggers, profilers, or monitoring tools. Instruments are enabled via `options` passed to the `engine` when the engine or context is constructed. Cite: `org/graalvm/polyglot/Engine.html#getInstruments()`
### getOptions()
`public OptionDescriptors getOptions()`. Since 19.0. Returns all options available for the engine. The engine offers options with the following `groups`: **engine**: options to configure the behavior of this engine.; **compiler**: options to configure the behavior of the compiler. The language and instrument specific options need to be retrieved using `Instrument.getOptions()` or `Language.getOptions()`. See also: `To get a list of options for a language.`, `To get a list of options for an instrument.`, `To set an option for an engine, language, or instrument.`, `To set an option for a context.`. Cite: `org/graalvm/polyglot/Engine.html#getOptions()`
### getVersion()
`public String getVersion()`. Since 19.0. Gets the version string of the engine in an unspecified format. Cite: `org/graalvm/polyglot/Engine.html#getVersion()`
### close(boolean)
`public void close(boolean cancelIfExecuting)`. Since 19.0. Closes this engine and frees up allocated native resources. If there are still open context instances that were created using this engine and they are currently not being executed then they will be closed automatically. If an attempt to close an engine was successful then consecutive calls to close have no effect. If a context is cancelled then the currently executing thread will throw a `PolyglotException`. The exception indicates that it was `cancelled`. Parameters: `cancelIfExecuting` `boolean`: if `true` then currently executing contexts will be cancelled, else an [`IllegalStateException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html) is thrown. Cite: `org/graalvm/polyglot/Engine.html#close(boolean)`
### close()
`public void close()`. Since 19.0. Closes this engine and frees up allocated native resources. If there are still open context instances that were created using this engine and they are currently not being executed then they will be closed automatically. If an attempt to close the engine was successful then consecutive calls to close have no effect. Throws: `IllegalStateException` (unchecked): if there currently executing open context instances. Overrides `close()`. See also: `close(boolean)`, `Engine.close()`. Cite: `org/graalvm/polyglot/Engine.html#close()`
### storeCache(Path)
`public boolean storeCache(Path targetFile) throws UnsupportedOperationException`. Since 25.0. Stores the auxiliary engine cache to the targetFile without cancellation. Throws: `UnsupportedOperationException`: if this engine or the host virtual machine does not support storing the cache. See also: `storeCache(Path, WordPointer)`, `persistCache(CancellationCallback)`. Cite: `org/graalvm/polyglot/Engine.html#storeCache(java.nio.file.Path)`
### storeCache(Path, WordPointer)
`public boolean storeCache(Path targetFile, WordPointer cancelledWord) throws CancellationException, UnsupportedOperationException`. Since 25.0. Stores the auxiliary engine cache to the `targetFile`. If it already exists, the file will be overwritten. The option `engine.CacheStoreEnabled` must be set to `true` to use this feature. Stored caches may be loaded by specifying the path using the `engine.CacheLoad` option. Note that this feature is experimental and only supported on native-image hosts built with auxiliary engine caching enabled. Basic Usage: See the [ documentation](https://github.com/oracle/graal/blob/master/truffle/docs/AuxiliaryEngineCaching.md) on auxiliary engine caching for further details. Parameters: `targetFile` `Path`: the file to which the cache is stored. `cancelledWord` `WordPointer`: a native pointer; if set to a non-zero value, the operation is cancelled. Allows cancellation of the cache store operation through a `cancelled` control word. The memory `address` pointing to the control word is polled periodically during storage without guaranteed frequency and may be delayed by safepoints such as garbage collection. A control word value of zero must be maintained for the duration of the operation. If a non-zero value is detected, the operation will be cancelled. A non-null provided pointer must remain accessible during the entire operation. Providing an invalid or inaccessible pointer may result in a VM crash. Returns `boolean`: `true` if the file was written; otherwise, `false`. Throws: `CancellationException`: if the storeCache operation was cancelled via the `cancelled` pointer. `UnsupportedOperationException`: if this engine or host virtual machine does not support cache storage. Cite: `org/graalvm/polyglot/Engine.html#storeCache(java.nio.file.Path,org.graalvm.nativeimage.c.type.WordPointer)`
```java
// Store the engine cache into a file
Path store = Files.createTempFile("cache", "engine");
try (Engine e = Engine.newBuilder().allowExperimentalOptions(true).option("engine.CacheStoreEnabled", "true").build()) {
try (Context c = Context.newBuilder().engine(e).build()) {
// Evaluate sources, run application
}
e.storeCache(store);
}
// Load the engine cache from a file
try (Engine e = Engine.newBuilder().allowExperimentalOptions(true).option("engine.CacheLoad", store.toAbsolutePath().toString()).build()) {
try (Context c = Context.newBuilder().engine(e).build()) {
// The context should be able to use
// the existing code cache.
}
}
```
### persistCache(Engine.CancellationCallback)
`public ByteBuffer persistCache(Engine.CancellationCallback callback)`. Since 25.1. Persists the auxiliary engine cache into an in-memory buffer. The option `engine.CacheStoreEnabled` must be set to `true` to use this feature. The returned buffer contains the cache image bytes and can be written to a file by the caller. Note that this feature is experimental and only supported on native-image hosts built with auxiliary engine caching enabled. If `callback` is non-null, it is polled periodically to request cancellation. Cancellation support during the low-level auxiliary image persistence phase is only available on hosts that support it; otherwise callback cancellation is limited to the compilation-preparation phase. Implementations that cannot support the callback semantics may throw [`UnsupportedOperationException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/UnsupportedOperationException.html). Parameters: `callback` `Engine.CancellationCallback`: callback used to request cancellation, or `null` for no cancellation. Returns `ByteBuffer`: a buffer containing the persisted cache image, or `null` if no image was produced, for example because the configured maximum image size was exceeded. Throws: `CancellationException` (unchecked): if the persist operation was cancelled via the callback. `UnsupportedOperationException` (unchecked): if this engine or host virtual machine does not support in-memory cache persistence. Cite: `org/graalvm/polyglot/Engine.html#persistCache(org.graalvm.polyglot.Engine.CancellationCallback)`
### getImplementationName()
`public String getImplementationName()`. Since 19.0. Gets a human-readable name of the polyglot implementation (for example, "Default Truffle Engine" or "Graal Truffle Engine"). The returned value may change without notice. The value is never `null`. Cite: `org/graalvm/polyglot/Engine.html#getImplementationName()`
### toString()
`public String toString()`. Since 25.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/Engine.html#toString()`
### create()
`public static Engine create()`. Since 19.0. Creates a new engine instance with default configuration. This method is a shortcut for `newBuilder().build()`. See also: `to create a new execution context.`. Cite: `org/graalvm/polyglot/Engine.html#create()`
### create(String...)
`public static Engine create(String... permittedLanguages)`. Since 21.3. Creates a new engine instance with default configuration with a set of permitted languages. This method is a shortcut for `newBuilder(permittedLanguages).build()`. See also: `to create a new execution context.`. Cite: `org/graalvm/polyglot/Engine.html#create(java.lang.String...)`
### newBuilder()
`public static Engine.Builder newBuilder()`. Since 21.3. Creates a new engine builder that allows to configure an engine instance. This method is equivalent to calling `newBuilder(String...)` with an empty set of permitted languages. Cite: `org/graalvm/polyglot/Engine.html#newBuilder()`
### newBuilder(String...)
`public static Engine.Builder newBuilder(String... permittedLanguages)`. Since 21.3. Creates a new engine builder that allows to configure an engine instance. Parameters: `permittedLanguages` `String...`: names of languages permitted in the engine. If no languages are provided, then all installed languages will be permitted. All contexts created with this engine will inherit the set of permitted languages. Returns `Engine.Builder`: a builder that can create a context. Cite: `org/graalvm/polyglot/Engine.html#newBuilder(java.lang.String...)`
### newBuilder(Engine.Preinitialized)
`public static Engine.Builder newBuilder(Engine.Preinitialized state)`. Since 25.5. Creates a new engine builder that consumes the given prepared state when `Builder.build()` is called. The builder inherits the permitted languages and sandbox policy used to prepare the state. A prepared state can create only one engine. Calling `build()` consumes the state even if building the engine fails. Runtime options must be compatible with the prepared state. The options `engine.SpecializationStatistics` and `engine.AssertProbes`, and the options of retained instruments, must match the preparation configuration. For retained instruments, this includes which options were explicitly set. The experimental-option policy uses the consuming builder's `configuration`. Parameters: `state` `Engine.Preinitialized`: the prepared state to consume. Returns `Engine.Builder`: a builder that can create an engine. Throws: `NullPointerException` (unchecked): if `state` is `null`. Cite: `org/graalvm/polyglot/Engine.html#newBuilder(org.graalvm.polyglot.Engine.Preinitialized)`
### findHome()
`public static Path findHome()`. Since 19.0. Finds the GraalVM home folder. This is equivalent to `HomeFinder.getHomeFolder()` which should be preferred. Returns `Path`: the path to a folder containing the GraalVM or `null` if it cannot be found. Cite: `org/graalvm/polyglot/Engine.html#findHome()`
### getCachedSources()
`public Set getCachedSources()`. Since 20.3. Returns the sources previously cached by this engine. Only sources may be returned that allow `caching` (default on). The source cache of the engine is using weak references to refer to the source objects. Calling this method will result in a strong reference to all cached sources of this engine until the returned set is no longer referenced. This method is useful to find out which sources very already evaluated by this engine. This method only returns sources that were evaluated using `Context.eval(Source)`. Sources evaluated by the guest application will not be returned. The return set is never `null` and not modifiable. Cite: `org/graalvm/polyglot/Engine.html#getCachedSources()`
### copyResources(Path, String...)
`public static boolean copyResources(Path targetFolder, String... components) throws IOException`. Since 23.1. Unpacks the language or instrument internal resources specified by the `components` into the `targetFolder` directory. During execution, the internal resource cache location can be overridden by the following system properties: `polyglot.engine.resourcePath`: Sets the cache location to the given path. The expected folder structure is the structure generated by this method.; `polyglot.engine.resourcePath.`: Retains the default cache folder but overrides caches for the specified component with the given path. The expected folder structure is `targetFolder/`.; `polyglot.engine.resourcePath..` : Retains the default cache folder but overrides caches for the specified resource within the component with the given path. The expected folder structure is `targetFolder//`. Parameters: `targetFolder` `Path`: the folder to unpack resources into. `components` `String...`: names of languages or instruments whose resources should be unpacked. If no languages or instruments are provided, then all installed languages and instruments are used. Returns `boolean`: `true` if at least one of the `components` has associated resources that were unpacked into `targetFolder`. Throws: `IllegalArgumentException` (unchecked): if the `components` list contains an id of a language or instrument that is not installed. `IOException`: in case of an IO error. Cite: `org/graalvm/polyglot/Engine.html#copyResources(java.nio.file.Path,java.lang.String...)`
### supportsCompilation()
`public static boolean supportsCompilation()`. Since 25.1. Returns whether the current runtime supports optimizing guest language execution. When this method returns `false`, guest code runs on the fallback runtime unless a polyglot isolate is used. Embedders can use this method to decide whether to enable isolate execution, for example with `Context.newBuilder().spawnIsolate(!Engine.supportsCompilation())`. Returns `boolean`: `true` if guest language execution can be optimized at run time; `false` if only the fallback runtime is available. Cite: `org/graalvm/polyglot/Engine.html#supportsCompilation()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ Engine.Builder
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0. Nested in [`Engine`](org/graalvm/polyglot/Engine.md).
```java
public final class Engine.Builder
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `Builder`
## Methods
### out(OutputStream)
`public Engine.Builder out(OutputStream out)`. Since 19.0. Sets the standard output stream to be used for this engine. Every context that uses this engine will inherit the configured output stream if it is not specified in the context. If not set then the system output stream will be used. Cite: `org/graalvm/polyglot/Engine.Builder.html#out(java.io.OutputStream)`
### err(OutputStream)
`public Engine.Builder err(OutputStream err)`. Since 19.0. Sets the standard error stream to be used for this engine. Every context that uses this engine will inherit the configured error stream if it is not specified in the context. If not set then the system error stream will be used. Cite: `org/graalvm/polyglot/Engine.Builder.html#err(java.io.OutputStream)`
### in(InputStream)
`public Engine.Builder in(InputStream in)`. Since 19.0. Sets the standard input stream to be used for this engine. Every context that uses this engine will inherit the configured input stream if it is not specified in the context. If not set then the system input stream will be used. Cite: `org/graalvm/polyglot/Engine.Builder.html#in(java.io.InputStream)`
### allowExperimentalOptions(boolean)
`public Engine.Builder allowExperimentalOptions(boolean enabled)`. Since 19.0. Allow experimental options to be used for instruments and engine options. Do not use experimental options in production environments. If set to `false` (the default), then passing an experimental option results in an [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) when the context is built. Cite: `org/graalvm/polyglot/Engine.Builder.html#allowExperimentalOptions(boolean)`
### useSystemProperties(boolean)
`public Engine.Builder useSystemProperties(boolean enabled)`. Since 19.0. Specifies whether the engine should use [`system properties`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/System.html#getProperty%28java.lang.String%29) if no explicit option is `set`. The default value is `true` indicating that the system properties should be used. System properties are looked up with the prefix *"polyglot"* in order to disambiguate existing system properties. For example, for the option with the key `"js.ECMACompatibility"`, the system property `"polyglot.js.ECMACompatibility"` is read. Invalid options specified using system properties will cause the `build` method to fail using an [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html). System properties are read once when the engine is built and are never updated after that. Parameters: `enabled` `boolean`: if `true` system properties will be used as options. See also: `To specify option values directly.`, `To build the engine instance.`. Cite: `org/graalvm/polyglot/Engine.Builder.html#useSystemProperties(boolean)`
### option(String, String)
`public Engine.Builder option(String key, String value)`. Since 19.0. Sets an option for an `engine`, `language` or `instrument`. If one of the set option keys or values is invalid then an [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) is thrown when the engine is `built`. The given key and value must not be `null`. See `Engine.getOptions()` to list all available options for engines. See `Language.getOptions()` to list all available options for a `language`. See `Instrument.getOptions()` to list all available options for an `instrument`. Cite: `org/graalvm/polyglot/Engine.Builder.html#option(java.lang.String,java.lang.String)`
### sandbox(SandboxPolicy)
`public Engine.Builder sandbox(SandboxPolicy policy)`. Since 23.0. Sets a code sandbox policy to an engine. By default, the engine's sandbox policy is `SandboxPolicy.TRUSTED`, there are no restrictions to the engine configuration. See also: `SandboxPolicy`. Cite: `org/graalvm/polyglot/Engine.Builder.html#sandbox(org.graalvm.polyglot.SandboxPolicy)`
### options(Map)
`public Engine.Builder options(Map options)`. Since 19.0. Shortcut for setting multiple `options` using a map. All values of the provided map must be non-null. Parameters: `options` `Map`: a map options. See also: `To set a single option.`. Cite: `org/graalvm/polyglot/Engine.Builder.html#options(java.util.Map)`
### serverTransport(MessageTransport)
`public Engine.Builder serverTransport(MessageTransport serverTransport)`. Since 19.0. Take over transport of message communication with a server peer. Provide an implementation of `MessageTransport` to virtualize a transport of messages to a server endpoint. `MessageTransport.open(java.net.URI, org.graalvm.polyglot.io.MessageEndpoint)` corresponds to accept of a server socket. Parameters: `serverTransport` `MessageTransport`: an implementation of message transport interceptor. See also: `MessageTransport`. Cite: `org/graalvm/polyglot/Engine.Builder.html#serverTransport(org.graalvm.polyglot.io.MessageTransport)`
### exceptionHandler(Consumer)
`public Engine.Builder exceptionHandler(Consumer handler)`. Since 25.1. Sets an exception handler that is invoked whenever a `PolyglotException` is about to be thrown from a engine bound value back to the host. The configured custom exception handler gets inherited by all contexts created with this engine. The handler is called on the host thread that performs the polyglot operation, for example when invoking `Value` methods, executing guest code, or initializing a language. It receives the `PolyglotException` that would normally be thrown to the caller. The handler can inspect the exception, perform additional logging or metrics, or translate the `PolyglotException` into a different exception type. If the handler throws an exception, that exception is propagated to the caller instead of the original `PolyglotException`. If the handler returns normally, the original `PolyglotException` is thrown as usual. A common use case is to unwrap and rethrow host runtime exceptions so that calling code can handle them directly: In this example, `Value.throwException()` would normally throw a `PolyglotException`. Because the handler rethrows the underlying host [`RuntimeException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/RuntimeException.html), the caller observes `IllegalStateException` directly instead of `PolyglotException`. Handlers should be written carefully, because any host call into the context can then appear to throw additional exception types. In particular, translating guest exceptions into unrelated runtime exceptions can make APIs harder to reason about and should only be done with care. Parameters: `handler` `Consumer`: the handler to invoke before a `PolyglotException` is thrown to the host, or `null` to disable custom handling. See also: `Context.Builder.exceptionHandler(Consumer)`. Cite: `org/graalvm/polyglot/Engine.Builder.html#exceptionHandler(java.util.function.Consumer)`
```java
static void rethrowHostRuntimeException(PolyglotException e) {
if (e.isHostException()) {
Throwable t = e.asHostException();
if (t instanceof RuntimeException rt) {
// rethrow the original host runtime exception
throw rt;
}
}
// fall through, the PolyglotException will be thrown
}
try (Context c = Context.newBuilder()
.exceptionHandler(MyHost::rethrowHostRuntimeException)
.build()) {
try {
// Without an exception handler, this would throw a PolyglotException
// wrapping the IllegalStateException as a host exception.
c.asValue(new IllegalStateException("test")).throwException();
} catch (IllegalStateException e) {
// The handler rethrew the original host exception.
assert "test".equals(e.getMessage());
}
}
```
### logHandler(Handler)
`public Engine.Builder logHandler(Handler logHandler)`. Since 19.0. Installs a new logging [`Handler`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Handler.html). The logger's [`Level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html) configuration is done using the `Engine's options`. The level option key has the following format: `log.languageId.loggerName.level` or `log.instrumentId.loggerName.level`. The value is either the name of pre-defined [`Level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html) constant or a numeric [`Level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html) value. If not explicitly set in options the level is inherited from the parent logger. **Examples** of setting log level options: `builder.option("log.level","FINE");` sets the [`FINE level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html#FINE) to all `TruffleLogger`s. `builder.option("log.js.level","FINE");` sets the [`FINE level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html#FINE) to JavaScript `TruffleLogger`s. `builder.option("log.js.com.oracle.truffle.js.parser.JavaScriptLanguage.level","FINE");` sets the [`FINE level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html#FINE) to `TruffleLogger` for the `JavaScriptLanguage` class. Parameters: `logHandler` `Handler`: the [`Handler`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Handler.html) to use for logging in engine's `Context`s. The passed `logHandler` is closed when the engine is `closed`. Returns `Engine.Builder`: the `Builder`. Cite: `org/graalvm/polyglot/Engine.Builder.html#logHandler(java.util.logging.Handler)`
### logHandler(OutputStream)
`public Engine.Builder logHandler(OutputStream logOut)`. Since 19.0. Installs a new logging [`Handler`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Handler.html) using given [`OutputStream`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/OutputStream.html). The logger's [`Level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html) configuration is done using the `Engine's options`. The level option key has the following format: `log.languageId.loggerName.level` or `log.instrumentId.loggerName.level`. The value is either the name of pre-defined [`Level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html) constant or a numeric [`Level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html) value. If not explicitly set in options the level is inherited from the parent logger. **Examples** of setting log level options: `builder.option("log.level","FINE");` sets the [`FINE level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html#FINE) to all `TruffleLogger`s. `builder.option("log.js.level","FINE");` sets the [`FINE level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html#FINE) to JavaScript `TruffleLogger`s. `builder.option("log.js.com.oracle.truffle.js.parser.JavaScriptLanguage.level","FINE");` sets the [`FINE level`](https://docs.oracle.com/en/java/javase/25/docs/api/java.logging/java/util/logging/Level.html#FINE) to `TruffleLogger` for the `JavaScriptLanguage` class. Parameters: `logOut` `OutputStream`: the [`OutputStream`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/OutputStream.html) to use for logging in engine's `Context`s. The passed `logOut` stream is closed when the engine is `closed`. Returns `Engine.Builder`: the `Builder`. Cite: `org/graalvm/polyglot/Engine.Builder.html#logHandler(java.io.OutputStream)`
### spawnIsolate(boolean)
`public Engine.Builder spawnIsolate(boolean value)`. Since 25.1. Specifies whether this engine should run guest languages in a polyglot isolate. A polyglot isolate executes guest languages with an isolated heap. This can be useful for sandboxing and for running guest languages as native images when the current runtime does not support optimizing guest language execution. If enabled, all languages permitted by this engine are run in the isolate. If `value` is `true`, this builder must have been created with an explicit permitted languages list, for example using `Engine.newBuilder("js")`. This setting is equivalent to setting the `engine.SpawnIsolate` engine option to `true` or `false`. If both are set to conflicting values, `build()` fails with [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html). Parameters: `value` `boolean`: `true` to spawn a polyglot isolate. See also: `Context.Builder.spawnIsolate(boolean)`, `Engine.supportsCompilation()`, [ Polyglot Isolates documentation](https://www.graalvm.org/latest/reference-manual/embed-languages/#polyglot-isolates). Cite: `org/graalvm/polyglot/Engine.Builder.html#spawnIsolate(boolean)`
### preinitialize(int, Consumer)
`public Engine.Preinitialized preinitialize(int contextCount, Consumer initializer)`. Since 25.5. Prepares engine state using this builder's configuration. This is a terminal operation, like `build()`. The `initializer` is invoked once with a temporary explicit engine. It may create ordinary contexts using that engine to initialize languages and cache parsed or evaluated sources. All such contexts must be closed before the callback returns. The temporary engine must not be closed and must only be used during the callback. After the callback, context-specific state is discarded and `contextCount` clean contexts are preinitialized for later use by an engine built with `Engine.newBuilder(Preinitialized)`. Preparation requires exactly one sharing layer containing only languages that support context-independent code with `ContextPolicy.SHARED`. All callback contexts must therefore use compatible language options. Custom file systems are not supported by callback contexts or contexts using the resulting engine. Files retained from callback contexts preserve their preparation-time IO permissions. Paths within language homes or internal resources are relocated when the prepared engine is consumed in a native image. Initialized instruments must explicitly support retaining their state in a preinitialized engine. Instruments that do not support preinitialization cause this operation to fail. This method is intended primarily for preparing state while building a native image. It can also be used on HotSpot to test the lifecycle and compatibility of prepared state, without providing native-image startup benefits. During a native-image build, unrelated Truffle execution must not run concurrently with this operation. To persist prepared state in a native image, store it in a static field of a class initialized at image build time. For example: The holder class must be configured using `--initialize-at-build-time=`. Preparing state at native-image run time is not supported. Parameters: `contextCount` `int`: the number of clean contexts to preinitialize; zero prepares only engine state and cached code. `initializer` `Consumer`: callback that prepares the temporary engine. Returns `Engine.Preinitialized`: one-shot prepared engine state. Throws: `IllegalArgumentException` (unchecked): if `contextCount` is negative or the configuration cannot be prepared. `IllegalStateException` (unchecked): if callback contexts remain open, do not form exactly one compatible sharing layer, or retain unsupported instrument state. `NullPointerException` (unchecked): if `initializer` is `null`. Cite: `org/graalvm/polyglot/Engine.Builder.html#preinitialize(int,java.util.function.Consumer)`
```java
static final Engine.Preinitialized PREINITIALIZED =
Engine.newBuilder("js").preinitialize(1, engine -> {
try (Context context = Context.newBuilder("js").engine(engine).build()) {
context.eval("js", "42");
}
});
Engine engine = Engine.newBuilder(PREINITIALIZED).build();
```
### toString()
`public String toString()`. Since 25.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/Engine.Builder.html#toString()`
### build()
`public Engine build()`. Since 19.0. Creates a new engine instance from the configuration provided in the builder. The same engine builder can be used to create multiple engine instances unless it was created with `prepared state`, which can be consumed only once. Throws: `IllegalStateException` (unchecked): if configured prepared state is unavailable. Cite: `org/graalvm/polyglot/Engine.Builder.html#build()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◇ Engine.CancellationCallback
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Interface in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 25.1. Nested in [`Engine`](org/graalvm/polyglot/Engine.md).
```java
@FunctionalInterface
public interface Engine.CancellationCallback
```
A callback that is invoked repeatedly while persisting the auxiliary engine cache.
The callback may be polled during compilation preparation. Some hosts may also support low-level auxiliary image persistence cancellation for host-specific callback implementations with additional runtime constraints.
## Methods
### shouldCancel()
`boolean shouldCancel()`. Since 25.1. Returns `boolean`: whether auxiliary engine cache persistence should be cancelled. Cite: `org/graalvm/polyglot/Engine.CancellationCallback.html#shouldCancel()`
# ◆ Engine.Preinitialized
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 25.5. Nested in [`Engine`](org/graalvm/polyglot/Engine.md).
```java
public static final class Engine.Preinitialized implements AutoCloseable
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `Preinitialized`
Implements: [`AutoCloseable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AutoCloseable.html)
Prepared engine state that can be consumed by one [`engine build`](org/graalvm/polyglot/Engine.Builder.md#build%28%29). Prepared state is useful for retaining initialized languages and cached code in a native image. It may also be used on HotSpot to test preparation and consumption behavior, but does not provide an image-startup benefit there.
A prepared state is thread-safe and one-shot. A call to [`Builder.build()`](org/graalvm/polyglot/Engine.Builder.md#build%28%29) consumes the state even if building the engine fails. An unused state should be [closed](org/graalvm/polyglot/Engine.Preinitialized.md#close%28%29) to release its resources.
To persist prepared state in a native image, store it in a static field of a class initialized at image build time. For example:
```java
static final Engine.Preinitialized PREINITIALIZED =
Engine.newBuilder("js").preinitialize(1, engine -> {
try (Context context = Context.newBuilder("js").engine(engine).build()) {
context.eval("js", "42");
}
});
Engine engine = Engine.newBuilder(PREINITIALIZED).build();
```
The holder class must be configured using `--initialize-at-build-time=`. Preparing state at native-image run time is not supported.
## Methods
### getCachedSources()
`public Set getCachedSources()`. Since 25.5. Returns an immutable snapshot of the sources cached in this prepared state. Returns `Set`: an immutable set of cached sources. Throws: `IllegalStateException` (unchecked): if this state has been consumed or closed. Cite: `org/graalvm/polyglot/Engine.Preinitialized.html#getCachedSources()`
### close()
`public void close()`. Since 25.5. Releases this prepared state if it has not been consumed. This method is idempotent and has no effect if the state is already closed or consumed. Overrides `close()`. Cite: `org/graalvm/polyglot/Engine.Preinitialized.html#close()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`toString`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ EnvironmentAccess
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.1.0.
```java
public final class EnvironmentAccess
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `EnvironmentAccess`
Represents an access policy to the process environment for the guest languages of a context.
## Fields
### NONE
`public static final EnvironmentAccess NONE`. Since 19.1.0. Provides guest languages no access to process environment. No environment variables are visible for reading. The `NONE` is a default value for `Context`s created without `all access`. Cite: `org/graalvm/polyglot/EnvironmentAccess.html#NONE`
### INHERIT
`public static final EnvironmentAccess INHERIT`. Since 19.1.0. Provides guest languages read access to process environment. The `INHERIT` is a default value for `Context`s created with `all access` set to `true`. Cite: `org/graalvm/polyglot/EnvironmentAccess.html#INHERIT`
## Methods
### toString()
`public String toString()`. Since 22.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/EnvironmentAccess.html#toString()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ HostAccess
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0.
```java
public final class HostAccess
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `HostAccess`
Represents the host access policy of a polyglot context. The host access policy specifies which methods and fields are accessible to the guest application, whenever Java host objects are accessed.
There are three predefined instances of host access policies:
- [`EXPLICIT`](org/graalvm/polyglot/HostAccess.md#EXPLICIT) - Java host methods or fields, must be public and be annotated with [`@Export`](org/graalvm/polyglot/HostAccess.Export.md) to make them accessible to the guest language.
- [`SCOPED`](org/graalvm/polyglot/HostAccess.md#SCOPED) - Java host methods or fields, must be public and be annotated with [`@Export`](org/graalvm/polyglot/HostAccess.Export.md) to make them accessible to the guest language. Guest-to-host callback parameter validity is scoped to the duration of the callback by default.
- [`NONE`](org/graalvm/polyglot/HostAccess.md#NONE) - Does not allow any access to methods or fields of host objects. Java host objects may still be passed into a context, but they cannot be accessed.
- [`ALL`](org/graalvm/polyglot/HostAccess.md#ALL) - Does allow full unrestricted access to public methods or fields of host objects. Note that this policy allows unrestricted access to reflection. It is highly discouraged from using this policy in environments where the guest application is not fully trusted.
- [`CONSTRAINED`](org/graalvm/polyglot/HostAccess.md#CONSTRAINED) host access policy suitable for a context with [`CONSTRAINED`](org/graalvm/polyglot/SandboxPolicy.md#CONSTRAINED) sandbox policy.
- [`ISOLATED`](org/graalvm/polyglot/HostAccess.md#ISOLATED) host access policy suitable for a context with [`ISOLATED`](org/graalvm/polyglot/SandboxPolicy.md#ISOLATED) sandbox policy.
- [`UNTRUSTED`](org/graalvm/polyglot/HostAccess.md#UNTRUSTED) host access policy suitable for a context with [`UNTRUSTED`](org/graalvm/polyglot/SandboxPolicy.md#UNTRUSTED) sandbox policy.
Custom host access policies can be created using [`newBuilder()`](org/graalvm/polyglot/HostAccess.md#newBuilder%28%29). The builder allows to specify a custom export annotation and allowed and denied methods or fields.
## Nested types
- [`HostAccess.Builder`](org/graalvm/polyglot/HostAccess.Builder.md) (class): Builder to create a custom host access policy.
- [`HostAccess.DisableMethodScoping`](org/graalvm/polyglot/HostAccess.DisableMethodScoping.md) (annotation interface): If HostAccess.SCOPED is used, placing this annotation on an exported host function excludes it from parameter scoping, i.e.
- [`HostAccess.Export`](org/graalvm/polyglot/HostAccess.Export.md) (annotation interface): Annotation used by the predefined EXPLICIT access policy to mark public constructors, methods and fields in public classes that should be accessible by the guest application.
- [`HostAccess.Implementable`](org/graalvm/polyglot/HostAccess.Implementable.md) (annotation interface): Allows guest language to implement a Java type.
- [`HostAccess.MutableTargetMapping`](org/graalvm/polyglot/HostAccess.MutableTargetMapping.md) (enum class): List of default host object mappings of mutable target types available in Value.as(Class).
- [`HostAccess.Optimized`](org/graalvm/polyglot/HostAccess.Optimized.md) (annotation interface): Requests an implementation optimized for invocation speed when converting a guest value to this interface with Value.as(Class).
- [`HostAccess.TargetMappingPrecedence`](org/graalvm/polyglot/HostAccess.TargetMappingPrecedence.md) (enum class): Represents the precedence of a target type mapping.
## Fields
### EXPLICIT
`public static final HostAccess EXPLICIT`. Since 19.0. Predefined host access policy that allows access to public host methods or fields that were annotated with @Export and were declared in public class. This is the default configuration if `Context.Builder.allowAllAccess(boolean)` is `false`. Equivalent of using the following builder configuration: Cite: `org/graalvm/polyglot/HostAccess.html#EXPLICIT`
```java
HostAccess.newBuilder().allowAccessAnnotatedBy(HostAccess.Export.class).
allowImplementationsAnnotatedBy(HostAccess.Implementable.class).
allowImplementationsAnnotatedBy(FunctionalInterface.class).
.build();
```
### SCOPED
`public static final HostAccess SCOPED`. Since 21.3. Predefined host access policy that is the same as EXPLICIT and enables method scoping of callback parameter values on top. Methods that are annotated with `HostAccess.DisableMethodScoping` are exempt from scoping. Equivalent of using the following builder configuration: Cite: `org/graalvm/polyglot/HostAccess.html#SCOPED`
```java
HostAccess.newBuilder().allowAccessAnnotatedBy(HostAccess.Export.class).
allowImplementationsAnnotatedBy(HostAccess.Implementable.class).
allowImplementationsAnnotatedBy(FunctionalInterface.class).
methodScoping(true).
disableMethodScopingAnnotatedBy(HostAccess.DisableMethodScoping.class)
.build();
```
### ALL
`public static final HostAccess ALL`. Since 19.0. Predefined host access policy that allows full unrestricted access to public methods or fields of public host classes. Note that this policy allows unrestricted access to reflection. It is highly discouraged from using this policy in environments where the guest application is not fully trusted. This is the default configuration if `Context.Builder.allowAllAccess(boolean)` is `true`. Equivalent of using the following builder configuration: Cite: `org/graalvm/polyglot/HostAccess.html#ALL`
```java
HostAccess.newBuilder()
allowPublicAccess(true).
allowAllImplementations(true).
allowAllClassImplementations(true).
allowArrayAccess(true).
allowListAccess(true).
allowBufferAccess(true).
allowIterableAccess(true).
allowIteratorAccess(true).
allowMapAccess(true).
allowAccessInheritance(true).
.build();
```
### NONE
`public static final HostAccess NONE`. Since 19.0. Predefined host access policy that disallows any access to public host methods or fields. Equivalent of using the following builder configuration: Cite: `org/graalvm/polyglot/HostAccess.html#NONE`
```java
HostAccess.newBuilder().build();
```
### CONSTRAINED
`public static final HostAccess CONSTRAINED`. Since 23.0. Predefined host access policy used by Context with a `SandboxPolicy.CONSTRAINED` sandbox policy when the host access policy is not explicitly specified by the embedder. Equivalent of using the following builder configuration: Cite: `org/graalvm/polyglot/HostAccess.html#CONSTRAINED`
```java
HostAccess.newBuilder().
allowAccessAnnotatedBy(Export.class).
allowImplementationsAnnotatedBy(Implementable.class).
allowMutableTargetMappings().build();
```
### ISOLATED
`public static final HostAccess ISOLATED`. Since 23.0. Predefined host access policy used by Context with an `SandboxPolicy.ISOLATED` sandbox policy when the host access policy is not explicitly specified by the embedder. Equivalent of using the following builder configuration: Cite: `org/graalvm/polyglot/HostAccess.html#ISOLATED`
```java
HostAccess.newBuilder(CONSTRAINED).
methodScoping(true).build();
```
### UNTRUSTED
`public static final HostAccess UNTRUSTED`. Since 23.0. Predefined host access policy used by Context with an `SandboxPolicy.UNTRUSTED` sandbox policy when the host access policy is not explicitly specified by the embedder. Equivalent of using the following builder configuration: Cite: `org/graalvm/polyglot/HostAccess.html#UNTRUSTED`
```java
HostAccess.newBuilder().
allowAccessAnnotatedBy(Export.class).
allowMutableTargetMappings().
methodScoping(true).build();
```
## Methods
### equals(Object)
`public boolean equals(Object obj)`. Since 20.3. Overrides `equals(java.lang.Object)`. Cite: `org/graalvm/polyglot/HostAccess.html#equals(java.lang.Object)`
### hashCode()
`public int hashCode()`. Since 20.3. Overrides `hashCode()`. Cite: `org/graalvm/polyglot/HostAccess.html#hashCode()`
### newBuilder()
`public static HostAccess.Builder newBuilder()`. Since 19.0. Creates a new builder that allows to create a custom host access policy. The builder configuration needs to be completed using the `method`. Cite: `org/graalvm/polyglot/HostAccess.html#newBuilder()`
### newBuilder(HostAccess)
`public static HostAccess.Builder newBuilder(HostAccess conf)`. Since 19.0. Creates a new builder that allows to create a custom host access policy based of a preset configuration. The preset configuration is copied and used as a template for the returned buidler. The builder configuration needs to be completed using the `method`. Cite: `org/graalvm/polyglot/HostAccess.html#newBuilder(org.graalvm.polyglot.HostAccess)`
### toString()
`public String toString()`. Since 19.0. Overrides `toString()`. Cite: `org/graalvm/polyglot/HostAccess.html#toString()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ HostAccess.Builder
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0. Nested in [`HostAccess`](org/graalvm/polyglot/HostAccess.md).
```java
public final class HostAccess.Builder
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `Builder`
Builder to create a custom [`host access policy`](org/graalvm/polyglot/HostAccess.md).
## Methods
### allowAccessAnnotatedBy(Class)
`public HostAccess.Builder allowAccessAnnotatedBy(Class extends Annotation> annotation)`. Since 19.0. Allows access to public constructors, methods or fields of public classes that were annotated by the given annotation class. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowAccessAnnotatedBy(java.lang.Class)`
### allowPublicAccess(boolean)
`public HostAccess.Builder allowPublicAccess(boolean allow)`. Since 19.0. Allows unrestricted access to all public constructors, methods or fields of public classes. Note that this policy allows unrestricted access to reflection. It is highly discouraged from using this option in environments where the guest application is not fully trusted. This setting replaces selected public access configured using `allowPublicAccess(Predicate)`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowPublicAccess(boolean)`
### allowPublicAccess(Predicate)
`public HostAccess.Builder allowPublicAccess(Predicate predicate)`. Since 25.4. Allows access to public constructors, methods or fields of public classes for which the given predicate returns `true`. Only public members are passed to the predicate. A predicate that returns `true` for every member exposes the same host members as `allowPublicAccess(true)`. This setting replaces previously configured public access. The predicate does not restrict access granted by `allowAccess(Executable)`, `allowAccess(Field)`, or `allowAccessAnnotatedBy(Class)`. For example, a method annotated with an annotation configured using `allowAccessAnnotatedBy(Class)` remains accessible even if the predicate returns `false` for that method. Access denied with `denyAccess(Class)` or `denyAccess(Class, boolean)` takes precedence. Predicate-selected public access is only supported with `SandboxPolicy.TRUSTED` and cannot be used with `SandboxPolicy.CONSTRAINED` or stricter sandbox policies. For a sandboxed context, each required member should instead be granted explicitly using `allowAccess(Executable)` or `allowAccess(Field)` after reviewing it for security implications. Member visibility is determined when host class metadata is initialized and retained for the lifetime of this policy. The predicate may be invoked multiple times and concurrently, and therefore must be stable, thread-safe, and free of side effects. Errors thrown by the predicate are propagated as host exceptions. Parameters: `predicate` `Predicate`: the predicate that selects public host members to expose. Returns `HostAccess.Builder`: this builder. Throws: `NullPointerException` (unchecked): if `predicate` is `null`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowPublicAccess(java.util.function.Predicate)`
### allowAccess(Executable)
`public HostAccess.Builder allowAccess(Executable element)`. Since 19.0. Allows access to a given constructor or method. Note that the method or constructor must be public in order to have any effect. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowAccess(java.lang.reflect.Executable)`
### allowAccess(Field)
`public HostAccess.Builder allowAccess(Field element)`. Since 19.0. Allows access to a given field. Note that the field must be public in order to have any effect. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowAccess(java.lang.reflect.Field)`
### denyAccess(Class)
`public HostAccess.Builder denyAccess(Class> clazz)`. Since 19.0. Prevents access to members of given class and its subclasses. Parameters: `clazz` `Class>`: the class to deny access to. Returns `HostAccess.Builder`: this builder. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#denyAccess(java.lang.Class)`
### denyAccess(Class, boolean)
`public HostAccess.Builder denyAccess(Class> clazz, boolean includeSubclasses)`. Since 19.0. Prevents access to members of given class. Parameters: `clazz` `Class>`: the class to deny access to. `includeSubclasses` `boolean`: should subclasses be excuded as well? Returns `HostAccess.Builder`: this builder. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#denyAccess(java.lang.Class,boolean)`
### allowAllImplementations(boolean)
`public HostAccess.Builder allowAllImplementations(boolean allow)`. Since 19.0. Allow guest languages to implement any Java interface. Note that implementations implicitly export all their methods, i.e., allowing implementations of a type implies allowing access its methods via its implementations, regardless of whether the methods have been explicitly exported. See also: `HostAccess.ALL`, `allowImplementations(Class)`, `allowImplementationsAnnotatedBy(Class)`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowAllImplementations(boolean)`
### allowAllClassImplementations(boolean)
`public HostAccess.Builder allowAllClassImplementations(boolean allow)`. Since 20.3.0. Allow guest languages to implement (extend) any Java class. Note that the default host type mappings and `Value.as(Class)` only implement abstract classes. Note that implementations implicitly export all their methods, i.e., allowing implementations of a type implies allowing access its methods via its implementations, regardless of whether the methods have been explicitly exported. See also: `HostAccess.ALL`, `allowImplementations(Class)`, `allowImplementationsAnnotatedBy(Class)`, `allowAllImplementations(boolean)`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowAllClassImplementations(boolean)`
### allowImplementationsAnnotatedBy(Class)
`public HostAccess.Builder allowImplementationsAnnotatedBy(Class extends Annotation> annotation)`. Since 19.0. Allow implementations of types annotated with the given annotation. For the `explicit` host access present the `Implementable` annotation is configured for this purpose. Applies to interfaces and classes. Note that implementations implicitly export all their methods, i.e., allowing implementations of a type implies allowing access its methods via its implementations, regardless of whether the methods have been explicitly exported. See also: `HostAccess.Implementable`, `allowImplementations(Class)`, `Value.as(Class)`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowImplementationsAnnotatedBy(java.lang.Class)`
### allowImplementations(Class)
`public HostAccess.Builder allowImplementations(Class> type)`. Since 19.0. Allow implementations of this type by the guest language. Note that implementations implicitly export all their methods, i.e., allowing implementations of a type implies allowing access its methods via its implementations, regardless of whether the methods have been explicitly exported. Parameters: `type` `Class>`: an interface that may be implemented or a class that may be extended. See also: `allowImplementationsAnnotatedBy(Class)`, `Value.as(Class)`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowImplementations(java.lang.Class)`
### allowArrayAccess(boolean)
`public HostAccess.Builder allowArrayAccess(boolean arrayAccess)`. Since 19.0. Allows the guest application to access arrays as values with `array elements`. By default no array access is allowed. See also: `Value.hasArrayElements()`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowArrayAccess(boolean)`
### allowListAccess(boolean)
`public HostAccess.Builder allowListAccess(boolean listAccess)`. Since 19.0. Allows the guest application to access lists as values with `array elements` and `iterators`. By default no array access is allowed. Allowing list access implies also allowing of `iterables` and `iterators`. See also: `Value.hasArrayElements()`, `Value.hasIterator()`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowListAccess(boolean)`
### allowIterableAccess(boolean)
`public HostAccess.Builder allowIterableAccess(boolean iterableAccess)`. Since 21.1. Allows the guest application to access [`iterables`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Iterable.html) as values with `iterators`. By default no iterable access is allowed. Allowing iterable access implies also allowing of `iterators`. See also: `Value.hasIterator()`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowIterableAccess(boolean)`
### allowIteratorAccess(boolean)
`public HostAccess.Builder allowIteratorAccess(boolean iteratorAccess)`. Since 21.1. Allows the guest application to access [`iterators`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Iterator.html) as `iterator` values. By default no iterator access is allowed. See also: `Value.isIterator()`, `Value.hasIteratorNextElement()`, `Value.getIteratorNextElement()`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowIteratorAccess(boolean)`
### allowMapAccess(boolean)
`public HostAccess.Builder allowMapAccess(boolean mapAccess)`. Since 21.1. Allows the guest application to access [`map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html) as `hash` values. By default no map access is allowed. Allowing map access implies also allowing of `iterators`. See also: `Value.hasHashEntries()`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowMapAccess(boolean)`
### allowBigIntegerNumberAccess(boolean)
`public HostAccess.Builder allowBigIntegerNumberAccess(boolean bigIntegerNumberAccess)`. Since 23.0. Allows the guest application to access [`BigInteger`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/math/BigInteger.html) as a `number`. By default BigInteger number access is allowed. See also: `Value.isNumber()`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowBigIntegerNumberAccess(boolean)`
### allowBufferAccess(boolean)
`public HostAccess.Builder allowBufferAccess(boolean bufferAccess)`. Since 21.1. Allows the guest application to access [`java.nio.ByteBuffer`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/ByteBuffer.html)s as values with `buffer elements`. By default no buffer access is allowed. See also: `Value.hasBufferElements()`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowBufferAccess(boolean)`
### allowAccessInheritance(boolean)
`public HostAccess.Builder allowAccessInheritance(boolean inheritAccess)`. Since 22.2. Allows the guest application to inherit access to allowed methods, i.e. implementations of allowed abstract and interface methods and overrides of allowed concrete methods. If access inheritance is disabled, all method implementations need to be explicitly allowed (either by an annotation or using reflection) to be available. Consequently, attempting to allow abstract methods has no effect in this access mode. Rationale: Requiring explicit vetting of all method implementations prevents unintentional exporting of newly added or overridden methods. When a user annotates an abstract (or concrete) method as exported, they might still know what that means when they write the code and know of all its implementations; but they might forget it later and other contributors to the codebase might not be aware of what is exported through an interface or superclass. So when someone introduces a new implementation or overrides the method in a subclass, perhaps a few levels down, they could be accidentally exporting it to the guest application. See also: `allowAccessAnnotatedBy(Class)`, `allowAccess(Executable)`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowAccessInheritance(boolean)`
### allowMutableTargetMappings(HostAccess.MutableTargetMapping...)
`public HostAccess.Builder allowMutableTargetMappings(HostAccess.MutableTargetMapping... mapping)`. Since 23.0. Allows host object mappings of mutable target types, such as [`java.util.List`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html), [`java.util.Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html), [`java.util.Iterator`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Iterator.html) and [`java.lang.Iterable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Iterable.html) based on the `MutableTargetMapping`. Mapping guest objects to well-known host object types such as [`java.util.Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html) is convenient on one hand. On the other hand it can lead to bugs as the guest code is free to provide an arbitrary backing implementation of such objects, which may not behave as expected of a [`java.util.Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html). Cite: `org/graalvm/polyglot/HostAccess.Builder.html#allowMutableTargetMappings(org.graalvm.polyglot.HostAccess.MutableTargetMapping...)`
### targetTypeMapping(Class, Class, …)
`public HostAccess.Builder targetTypeMapping(Class sourceType, Class targetType, Predicate accepts, Function converter)`. Since 19.0. Adds a custom source to target type mapping for Java host calls, host field assignments and `explicit value conversions`. Method is equivalent to calling the targetTypeMapping method with precedence `TargetMappingPrecedence.HIGH`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#targetTypeMapping(java.lang.Class,java.lang.Class,java.util.function.Predicate,java.util.function.Function)`
### targetTypeMapping(Class, Class, …)
`public HostAccess.Builder targetTypeMapping(Class sourceType, Class targetType, Predicate accepts, Function converter, HostAccess.TargetMappingPrecedence precedence)`. Since 20.3. Adds a custom source to target type mapping for Java host calls, host field assignments and `explicit value conversions`. The source type specifies the static source type for the conversion. The target type specifies the exact and static target type of the mapping. Sub or base target types won't trigger the mapping. Custom target type mappings always have precedence over default mappings specified in `Value.as(Class)`, therefore allow to customize their behavior. The provided converter takes a value of the source type and converts it to the target type. If the mapping is only conditionally applicable then an accepts predicate may be specified. If the mapping is applicable for all source values with the specified source type then a `null` accepts predicate should be specified. The converter may throw a [`ClassCastException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/ClassCastException.html) if the mapping is not applicable. It is recommended to return `false` in the accepts predicate if the mapping is not applicable instead of throwing an exception. Implementing the accepts predicate instead of throwing an exception also allows the implementation to perform better overload selection when a method with multiple overloads is invoked. All type mappings are applied recursively to generic types. A type mapping with the target type `String.class` will also be applied to the elements of a `List` mapping. This works for lists, maps, arrays and varargs parameters. The source type uses the semantics of `Value.as(Class)` to convert to the source value. Custom type mappings are not applied there. If the source type is not applicable to a value then the mapping will not be applied. For conversions that may accept any value the `Value` should be used as source type. Multiple mappings may be added for a source or target class. Multiple mappings are applied in the order they were added, grouped by the `priority` where the highest priority group is applied first. See `Value.as(Class)` for a detailed ordered list of the conversion order used. The first mapping that accepts the source value will be used. If the `default priority` is used then all custom target type mappings use the same precedence when an overloaded method is selected. This means that if two methods with a custom target type mapping are applicable for a set of arguments, an [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) is thrown at runtime. Using a non-default priority for the mapping allows to configure whether the method will be prioritized or deprioritized depending on the precedence. For example take a configured target mapping from `String` to `int` and two overloaded methods that takes an int or a [`String`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html) parameter. If this method is invoked with a `String` value then there are three possible outcomes depending on the precedence that was used for the custom mapping: `TargetMappingPrecedence.HIGHEST`: The int method overload will be selected and invoked as the target mapping has a higher precedence than default.; `TargetMappingPrecedence.HIGH`: The execution fails with an error as all overloads have equivalent precedence.; `TargetMappingPrecedence.LOW` or `TargetMappingPrecedence.LOWEST`: The String method overload will be selected and invoked as the target mapping has a lower precedence than default.; In this example the outcome of low and lowest are equivalent. There are differences between low and lowest. See `TargetMappingPrecedence` for details. Primitive boxed target types will be applied to the primitive and boxed values. It is therefore enough to specify a target mapping to [`Integer`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Integer.html) to also map to the target type `int.class`. If the converter returns `null` when converting to a primitive type, the conversion throws a [`NullPointerException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/NullPointerException.html). Primitive target types can not be used as target types. They throw an [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) if used. If the converter function or the accepts predicate calls `Value.as(Class)` recursively then custom target mappings are applied. Special care must be taken in order to not trigger stack overflow errors. It is recommended to use a restricted source type instead of `Value.as(Class)` where possible. It is strongly discouraged that accept predicates or converter cause any side-effects or escape values for permanent storage. Usage example: Parameters: `sourceType` `Class`: the static source type to convert from with this mapping. The source type must be applicable for a mapping to be accepted. `targetType` `Class`: the exact and static target type to convert to with this mapping. `accepts` `Predicate`: the predicate to check whether a mapping is applicable. Returns `true` if the mapping is applicable else false. If set to `null` then all values of a given source type are applicable. `converter` `Function`: a function that produces the converted value of the mapping. May return `null` for reference target types. Returning `null` for a primitive conversion causes a [`NullPointerException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/NullPointerException.html). May throw [`ClassCastException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/ClassCastException.html) if the source value is not convertible. `precedence` `HostAccess.TargetMappingPrecedence`: the precedence of the defined mapping which influences conversion order and precedence with default mappings and other target type mappings. Throws: `IllegalArgumentException` (unchecked): for primitive target types. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#targetTypeMapping(java.lang.Class,java.lang.Class,java.util.function.Predicate,java.util.function.Function,org.graalvm.polyglot.HostAccess.TargetMappingPrecedence)`
```java
public static class MyClass {
@HostAccess.Export
public void json(JsonObject c) {
}
@HostAccess.Export
public String intToString(String c) {
return c;
}
}
public static class JsonObject {
JsonObject(Value v) {
}
}
public static void main(String[] args) {
HostAccess.Builder builder = HostAccess.newBuilder();
builder.allowAccessAnnotatedBy(HostAccess.Export.class);
builder.targetTypeMapping(Value.class, JsonObject.class,
(v) -> v.hasMembers() || v.hasArrayElements(),
(v) -> new JsonObject(v)).build();
builder.targetTypeMapping(Integer.class, String.class, null,
(v) -> v.toString());
HostAccess access = builder.build();
try (Context c = Context.newBuilder().allowHostAccess(access).build()) {
c.getBindings("js").putMember("javaObject", new MyClass());
c.eval("js", "javaObject.json({})"); // works!
c.eval("js", "javaObject.json([])"); // works!
try {
c.eval("js", "javaObject.json(42)"); // fails!
} catch (PolyglotException e) {
}
c.eval("js", "javaObject.intToString(42)"); // returns "42"
}
}
```
### methodScoping(boolean)
`public HostAccess.Builder methodScoping(boolean scopingDefault)`. Since 21.3. Sets the default scoping of callback function parameters. Parameters escape from the scope of a function, if a reference to them is kept after the function returns. To use a value beyond the method scope `Value.pin()` may be used. See also: `Value.pin()`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#methodScoping(boolean)`
### disableMethodScopingAnnotatedBy(Class)
`public HostAccess.Builder disableMethodScopingAnnotatedBy(Class extends Annotation> annotation)`. Since 21.3. Function parameters of a method annotated with the specified annotation are not scoped. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#disableMethodScopingAnnotatedBy(java.lang.Class)`
### disableMethodScoping(Executable)
`public HostAccess.Builder disableMethodScoping(Executable e)`. Since 21.3. Function parameters of the specified executable escape the executable's scope. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#disableMethodScoping(java.lang.reflect.Executable)`
### useModuleLookup(MethodHandles.Lookup)
`public HostAccess.Builder useModuleLookup(MethodHandles.Lookup lookup)`. Since 23.1. Sets the [`lookup`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/invoke/MethodHandles.Lookup.html) the guest application should use to find and access classes on the host side in [`modularized`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Module.html) host applications. This allows guest applications to find and access public classes that are not directly exported by the lookup module, or public classes that are exported to the module only through qualified exports. Access to classes in the unnamed module is not affected by the use of this method. Pass `MethodHandles.lookup()` from a named module to export its access privileges to the guest application. It is requited that the lookup module is a named module, i.e., `lookup.lookupClass().getModule().isNamed()` must be `true`. Note that even though the provided lookup may provide access to non-public classes or members, the access will be restricted to classes or members with public visibility. By default, [`MethodHandles.publicLookup()`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/invoke/MethodHandles.html#publicLookup%28%29) is used to access host classes which can only access classes from the unnamed module and classes exported to the unnamed module. [`MethodHandles.publicLookup()`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/invoke/MethodHandles.html#publicLookup%28%29) is also used for classes from the unnamed module even if another lookup is specified by this method. Therefore, the guest application can still add classes to the classpath and access them even though a custom lookup from a named module is specified. Parameters: `lookup` `MethodHandles.Lookup`: lookup from a named module to be used for host access. Throws: `IllegalArgumentException` (unchecked): if the passed lookup is not from a named module. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#useModuleLookup(java.lang.invoke.MethodHandles.Lookup)`
### toString()
`public String toString()`. Since 25.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#toString()`
### build()
`public HostAccess build()`. Since 19.0. Creates an instance of the custom host access configuration. Cite: `org/graalvm/polyglot/HostAccess.Builder.html#build()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# @ HostAccess.DisableMethodScoping
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Annotation interface in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 21.3. Nested in [`HostAccess`](org/graalvm/polyglot/HostAccess.md).
```java
@Retention(RUNTIME)
@Target({CONSTRUCTOR, METHOD})
public @interface HostAccess.DisableMethodScoping
```
If [`HostAccess.SCOPED`](org/graalvm/polyglot/HostAccess.md#SCOPED) is used, placing this annotation on an exported host function excludes it from parameter scoping, i.e. parameters will not be released after invocation of a callback.
**See also**
- [`HostAccess.SCOPED`](org/graalvm/polyglot/HostAccess.md#SCOPED)
# @ HostAccess.Export
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Annotation interface in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0. Nested in [`HostAccess`](org/graalvm/polyglot/HostAccess.md).
```java
@Target({CONSTRUCTOR, FIELD, METHOD})
@Retention(RUNTIME)
public @interface HostAccess.Export
```
Annotation used by the predefined [`EXPLICIT`](org/graalvm/polyglot/HostAccess.md#EXPLICIT) access policy to mark public constructors, methods and fields in public classes that should be accessible by the guest application.
**Example** using a Java object from JavaScript:
```java
public class JavaRecord {
@HostAccess.Export public int x;
@HostAccess.Export
public String name() {
return "foo";
}
}
try (Context context = Context.create()) {
JavaRecord record = new JavaRecord();
context.getBindings("js").putMember("javaRecord", record);
context.eval("js", "javaRecord.x = 42");
context.eval("js", "javaRecord.name()").asString().equals("foo");
}
```
**See also**
- [`Context.Builder.allowHostAccess(HostAccess)`](org/graalvm/polyglot/Context.Builder.md#allowHostAccess%28org.graalvm.polyglot.HostAccess%29)
- [`HostAccess.EXPLICIT`](org/graalvm/polyglot/HostAccess.md#EXPLICIT)
# @ HostAccess.Implementable
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Annotation interface in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0. Nested in [`HostAccess`](org/graalvm/polyglot/HostAccess.md).
```java
@Retention(RUNTIME)
@Target({TYPE})
public @interface HostAccess.Implementable
```
Allows guest language to implement a Java type. Implementable is required if the [`explicit`](org/graalvm/polyglot/HostAccess.md#EXPLICIT) host access policy is set. The annotation to use for this purpose can be customized with [`Builder.allowImplementationsAnnotatedBy(Class)`](org/graalvm/polyglot/HostAccess.Builder.md#allowImplementationsAnnotatedBy%28java.lang.Class%29). Allowing implementations for all Java interfaces can be enabled with [`Builder.allowAllImplementations(boolean)`](org/graalvm/polyglot/HostAccess.Builder.md#allowAllImplementations%28boolean%29).
**See also**
- [`Context.Builder.allowHostAccess(HostAccess)`](org/graalvm/polyglot/Context.Builder.md#allowHostAccess%28org.graalvm.polyglot.HostAccess%29)
- [`Value.as(Class)`](org/graalvm/polyglot/Value.md#as%28java.lang.Class%29)
- [`HostAccess.EXPLICIT`](org/graalvm/polyglot/HostAccess.md#EXPLICIT)
# ≡ HostAccess.MutableTargetMapping
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Enum class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 23.0. Nested in [`HostAccess`](org/graalvm/polyglot/HostAccess.md).
```java
public enum HostAccess.MutableTargetMapping
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > [`Enum`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html) > `MutableTargetMapping`
List of default host object mappings of mutable target types available in [`Value.as(Class)`](org/graalvm/polyglot/Value.md#as%28java.lang.Class%29). The mappings map guest object traits to host object types.
## Enum constants
### ARRAY_TO_JAVA_LIST
`ARRAY_TO_JAVA_LIST`. Enables default mapping of guest object arrays to host object [`java.util.List`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html). This mapping is also applied when the target host object is [`java.util.Collection`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Collection.html). Cite: `org/graalvm/polyglot/HostAccess.MutableTargetMapping.html#ARRAY_TO_JAVA_LIST`
### ITERATOR_TO_JAVA_ITERATOR
`ITERATOR_TO_JAVA_ITERATOR`. Enables default mapping of guest object iterators to host object [`java.util.Iterator`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Iterator.html). Cite: `org/graalvm/polyglot/HostAccess.MutableTargetMapping.html#ITERATOR_TO_JAVA_ITERATOR`
### ITERABLE_TO_JAVA_ITERABLE
`ITERABLE_TO_JAVA_ITERABLE`. Enables default mapping of guest object iterables to host object [`java.lang.Iterable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Iterable.html). Cite: `org/graalvm/polyglot/HostAccess.MutableTargetMapping.html#ITERABLE_TO_JAVA_ITERABLE`
### HASH_TO_JAVA_MAP
`HASH_TO_JAVA_MAP`. Enables default mapping of guest object hashes to host object [`java.util.Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html). Cite: `org/graalvm/polyglot/HostAccess.MutableTargetMapping.html#HASH_TO_JAVA_MAP`
### MEMBERS_TO_JAVA_MAP
`MEMBERS_TO_JAVA_MAP`. Enables default mapping of guest objects with members to [`java.util.Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html). Cite: `org/graalvm/polyglot/HostAccess.MutableTargetMapping.html#MEMBERS_TO_JAVA_MAP`
### MEMBERS_TO_JAVA_INTERFACE
`MEMBERS_TO_JAVA_INTERFACE`. Enables default mapping of guest objects with members to a Java interface. Cite: `org/graalvm/polyglot/HostAccess.MutableTargetMapping.html#MEMBERS_TO_JAVA_INTERFACE`
### EXECUTABLE_TO_JAVA_INTERFACE
`EXECUTABLE_TO_JAVA_INTERFACE`. Enables default mapping of executable guest objects to a [`java.lang.FunctionalInterface`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/FunctionalInterface.html). Cite: `org/graalvm/polyglot/HostAccess.MutableTargetMapping.html#EXECUTABLE_TO_JAVA_INTERFACE`
## Methods
### values()
`public static HostAccess.MutableTargetMapping[] values()`. Returns the enum constants in declaration order. Returns `HostAccess.MutableTargetMapping[]`: Returns the enum constants in declaration order. Cite: `org/graalvm/polyglot/HostAccess.MutableTargetMapping.html#values()`
### valueOf(String)
`public static HostAccess.MutableTargetMapping valueOf(String name)`. Returns the enum constant with the given name. Parameters: `name` `String`: The exact name of the enum constant. Returns `HostAccess.MutableTargetMapping`: Returns the enum constant with the given name. Cite: `org/graalvm/polyglot/HostAccess.MutableTargetMapping.html#valueOf(java.lang.String)`
## Inherited members
- From class [`Enum`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#clone%28%29), [`compareTo`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#compareTo%28E%29), [`describeConstable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#describeConstable%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#finalize%28%29), [`getDeclaringClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#getDeclaringClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#hashCode%28%29), [`name`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#name%28%29), [`ordinal`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#ordinal%28%29), [`toString`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#toString%28%29), [`valueOf`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#valueOf%28java.lang.Class,java.lang.String%29)
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# @ HostAccess.Optimized
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Annotation interface in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 25.7. Nested in [`HostAccess`](org/graalvm/polyglot/HostAccess.md).
```java
@Documented
@Retention(RUNTIME)
@Target({TYPE})
public @interface HostAccess.Optimized
```
Requests an implementation optimized for invocation speed when converting a guest value to this interface with [`Value.as(Class)`](org/graalvm/polyglot/Value.md#as%28java.lang.Class%29). Use this annotation for interfaces whose methods are called frequently from Java.
Interfaces may declare multiple methods. In Native Image, annotated interfaces included in the image are available for conversion without additional proxy configuration.
```java
@HostAccess.Optimized
@FunctionalInterface
public interface Adder {
int add(int left, int right);
}
try (Context context = Context.newBuilder("js")
.allowHostAccess(HostAccess.EXPLICIT)
.build()) {
Adder adder = context.eval("js", "(x, y) => x + y").as(Adder.class);
assert adder.add(40, 2) == 42;
}
```
This annotation does not authorize host access. Conversion remains subject to the configured [`HostAccess`](org/graalvm/polyglot/HostAccess.md) policy. It also does not guarantee allocation-free conversion or invocation. Only non-sealed interfaces are currently supported. The interface and reference types in its method signatures must be public and their packages must be exported to unnamed modules.
# ≡ HostAccess.TargetMappingPrecedence
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Enum class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 20.3. Nested in [`HostAccess`](org/graalvm/polyglot/HostAccess.md).
```java
public enum HostAccess.TargetMappingPrecedence
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > [`Enum`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html) > `TargetMappingPrecedence`
Represents the precedence of a target type mapping. The precedence influences target type mappings in two ways:
- The conversion order in which target mappings are performed. [`Highest`](org/graalvm/polyglot/HostAccess.TargetMappingPrecedence.md#HIGHEST) and [`high`](org/graalvm/polyglot/HostAccess.TargetMappingPrecedence.md#HIGH) precedences are invoked before all [`default mappings`](org/graalvm/polyglot/Value.md#as%28java.lang.Class%29). [`Low`](org/graalvm/polyglot/HostAccess.TargetMappingPrecedence.md#LOW) after all loss less conversions and [`lowest`](org/graalvm/polyglot/HostAccess.TargetMappingPrecedence.md#LOWEST) after all other default mappings.
- To disambiguate multiple selected overloads on method invocation. The overload precedence defines which method has precedence over other applicable methods. [`Highest`](org/graalvm/polyglot/HostAccess.TargetMappingPrecedence.md#HIGHEST) have higher and [`high`](org/graalvm/polyglot/HostAccess.TargetMappingPrecedence.md#HIGH) have the same precedence as the default loss-less mapping. The precedence [`low`](org/graalvm/polyglot/HostAccess.TargetMappingPrecedence.md#LOW) declares equal precedence than all lossy coercions and [`lowest`](org/graalvm/polyglot/HostAccess.TargetMappingPrecedence.md#LOWEST) defines precedence lower than all default mappings.
**See also**
- [`for detailed information on conversion order.`](org/graalvm/polyglot/Value.md#as%28java.lang.Class%29)
## Enum constants
### HIGHEST
`HIGHEST`. Since 20.3. Defines higher precedence and conversion order as all default mappings and target type mappings with lower precedence. Cite: `org/graalvm/polyglot/HostAccess.TargetMappingPrecedence.html#HIGHEST`
### HIGH
`HIGH`. Since 20.3. Defines high or default precedence and conversion order for a target type mapping. This precedence makes mappings be used before all other default mappings and treated with equal overload precedence as default loss less mappings like primitive coercions. Cite: `org/graalvm/polyglot/HostAccess.TargetMappingPrecedence.html#HIGH`
### LOW
`LOW`. Since 20.3. Defines low precedence and conversion order for a target type mapping. This precedence makes mappings be used before all other default lossy mappings and treated with equal overload precedence as default lossy mappings, like mappings to Map. Cite: `org/graalvm/polyglot/HostAccess.TargetMappingPrecedence.html#LOW`
### LOWEST
`LOWEST`. Since 20.3. Defines lowest precedence and conversion order for a target type mapping. This precedence makes mappings be used after all other default mappings and treated with lower overload precedence as all default mappings or other target type mappings. Cite: `org/graalvm/polyglot/HostAccess.TargetMappingPrecedence.html#LOWEST`
## Methods
### values()
`public static HostAccess.TargetMappingPrecedence[] values()`. Returns the enum constants in declaration order. Returns `HostAccess.TargetMappingPrecedence[]`: Returns the enum constants in declaration order. Cite: `org/graalvm/polyglot/HostAccess.TargetMappingPrecedence.html#values()`
### valueOf(String)
`public static HostAccess.TargetMappingPrecedence valueOf(String name)`. Returns the enum constant with the given name. Parameters: `name` `String`: The exact name of the enum constant. Returns `HostAccess.TargetMappingPrecedence`: Returns the enum constant with the given name. Cite: `org/graalvm/polyglot/HostAccess.TargetMappingPrecedence.html#valueOf(java.lang.String)`
## Inherited members
- From class [`Enum`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#clone%28%29), [`compareTo`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#compareTo%28E%29), [`describeConstable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#describeConstable%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#finalize%28%29), [`getDeclaringClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#getDeclaringClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#hashCode%28%29), [`name`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#name%28%29), [`ordinal`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#ordinal%28%29), [`toString`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#toString%28%29), [`valueOf`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#valueOf%28java.lang.Class,java.lang.String%29)
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ Instrument
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0.
```java
public final class Instrument
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `Instrument`
A handle for an *instrument* installed in an [`engine`](org/graalvm/polyglot/Engine.md). The instrument is usable from other threads. The handle provides access to the metadata of the instrument and allows to [`lookup`](org/graalvm/polyglot/Instrument.md#lookup%28java.lang.Class%29) instrument specific services.
All methods here, as well as instrumentation services in general, can be used safely from any thread.
**See also**
- [`Engine.getInstruments()`](org/graalvm/polyglot/Engine.md#getInstruments%28%29)
## Methods
### getId()
`public String getId()`. Since 19.0. Gets the ID clients can use to acquire this instrument. Returns `String`: the unique ID for this instrument. Cite: `org/graalvm/polyglot/Instrument.html#getId()`
### getName()
`public String getName()`. Since 19.0. Gets a human-readable name for this instrument. Returns `String`: the user-friendly name for this instrument. Cite: `org/graalvm/polyglot/Instrument.html#getName()`
### getOptions()
`public OptionDescriptors getOptions()`. Since 19.0. Gets the options available for this instrument. Returns `OptionDescriptors`: the options as `OptionDescriptors`. Cite: `org/graalvm/polyglot/Instrument.html#getOptions()`
### getSourceOptions()
`public OptionDescriptors getSourceOptions()`. Since 25.0. Returns the source options descriptors available for sources of this instrument. See also: `getOptions()`, `Source.Builder.option(String, String)`. Cite: `org/graalvm/polyglot/Instrument.html#getSourceOptions()`
### getVersion()
`public String getVersion()`. Since 19.0. Gets the version of this instrument. Returns `String`: the version of this instrument. Cite: `org/graalvm/polyglot/Instrument.html#getVersion()`
### lookup(Class)
`public T lookup(Class type)`. Since 19.0. Looks up an additional internal service that is provided by this instrument using a Java type. Note that the services returned by this method are implementation specific and subject to change without notice. Type parameters: ``: the type of the internal service. Parameters: `type` `Class`: class of the service that is being requested. Returns `T`: instance of requested type, `null` if no such service is available. Cite: `org/graalvm/polyglot/Instrument.html#lookup(java.lang.Class)`
### getWebsite()
`public String getWebsite()`. Since 22.1.0. Gets the website of this instrument. Returns `String`: the website of this instrument. Cite: `org/graalvm/polyglot/Instrument.html#getWebsite()`
### toString()
`public String toString()`. Since 25.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/Instrument.html#toString()`
### hashCode()
`public int hashCode()`. Since 24.2. Overrides `hashCode()`. Cite: `org/graalvm/polyglot/Instrument.html#hashCode()`
### equals(Object)
`public boolean equals(Object obj)`. Since 24.2. Overrides `equals(java.lang.Object)`. Cite: `org/graalvm/polyglot/Instrument.html#equals(java.lang.Object)`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ Language
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0.
```java
public final class Language
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `Language`
A handle for a Graal language installed in an [`engine`](org/graalvm/polyglot/Engine.md). The handle provides access to the language's meta-data, including the language's [`id`](org/graalvm/polyglot/Language.md#getId%28%29), [`name`](org/graalvm/polyglot/Language.md#getName%28%29), [`version`](org/graalvm/polyglot/Language.md#getVersion%28%29) and [`options`](org/graalvm/polyglot/Language.md#getOptions%28%29).
**See also**
- [`Engine.getLanguages()`](org/graalvm/polyglot/Engine.md#getLanguages%28%29)
## Methods
### getId()
`public String getId()`. Since 19.0. Gets the primary identification string of this language. The language id is used as the primary way of identifying languages in the polyglot API. (eg. `js`). Returns `String`: a language ID string. Cite: `org/graalvm/polyglot/Language.html#getId()`
### getName()
`public String getName()`. Since 19.0. Gets a human-readable name for the language (for example, "JavaScript"). Returns `String`: the user-friendly name for this language. Cite: `org/graalvm/polyglot/Language.html#getName()`
### getImplementationName()
`public String getImplementationName()`. Since 19.0. Gets a human-readable name of the language implementation (for example, "Graal.JS"). Returns `null` if no implementation name was specified. Cite: `org/graalvm/polyglot/Language.html#getImplementationName()`
### getVersion()
`public String getVersion()`. Since 19.0. Gets the version information of the language in an arbitrary language-specific format. Cite: `org/graalvm/polyglot/Language.html#getVersion()`
### isInteractive()
`public boolean isInteractive()`. Since 19.0. Returns `true` if a the language is suitable for interactive evaluation of `sources`. `Interactive` languages should be displayed in interactive environments and presented to the user. Cite: `org/graalvm/polyglot/Language.html#isInteractive()`
### getOptions()
`public OptionDescriptors getOptions()`. Since 19.0. Returns the set of options provided by this language. Option values for languages can either be provided while building an `engine` or a `context`. The option descriptor `name` must be used as the option name. Cite: `org/graalvm/polyglot/Language.html#getOptions()`
### getSourceOptions()
`public OptionDescriptors getSourceOptions()`. Since 25.0. Returns the source options descriptors available for sources of this language. See also: `getOptions()`, `Source.Builder.option(String, String)`. Cite: `org/graalvm/polyglot/Language.html#getSourceOptions()`
### getDefaultMimeType()
`public String getDefaultMimeType()`. Since 19.0. Returns the default MIME type that is in use by a language. The default MIME type specifies whether a source is loaded as character or binary based source by default. Returns `null` if the language does not specify a default MIME type. See also: `Source.hasBytes()`, `Source.getMimeType()`. Cite: `org/graalvm/polyglot/Language.html#getDefaultMimeType()`
### getMimeTypes()
`public Set getMimeTypes()`. Since 19.0. Returns the MIME types supported by this language. See also: `Source.getMimeType()`. Cite: `org/graalvm/polyglot/Language.html#getMimeTypes()`
### getWebsite()
`public String getWebsite()`. Since 21.1.0. Get the URL for the language website. Cite: `org/graalvm/polyglot/Language.html#getWebsite()`
### toString()
`public String toString()`. Since 25.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/Language.html#toString()`
### hashCode()
`public int hashCode()`. Since 24.2. Overrides `hashCode()`. Cite: `org/graalvm/polyglot/Language.html#hashCode()`
### equals(Object)
`public boolean equals(Object obj)`. Since 24.2. Overrides `equals(java.lang.Object)`. Cite: `org/graalvm/polyglot/Language.html#equals(java.lang.Object)`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ PolyglotAccess
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0.
```java
public final class PolyglotAccess
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `PolyglotAccess`
Represents an access policy for polyglot builtins in the guest languages.
If the two predefined access policies [`NONE`](org/graalvm/polyglot/PolyglotAccess.md#NONE) and [`ALL`](org/graalvm/polyglot/PolyglotAccess.md#ALL) are not sufficient then a custom access configuration may be created using [`newBuilder()`](org/graalvm/polyglot/PolyglotAccess.md#newBuilder%28%29). This allows to grant individual access rights between the language.
The following access rights may be granted:
- The ability to evaluate code [`between`](org/graalvm/polyglot/PolyglotAccess.Builder.md#allowEvalBetween%28java.lang.String...%29) two or just for [`one`](org/graalvm/polyglot/PolyglotAccess.Builder.md#allowEval%28java.lang.String,java.lang.String%29) language. If a language has access to at least one other language then the polyglot eval builtin will be available, otherwise access to that builtin might be restricted. The concrete name of the polyglot eval builtin is language specific. In JavaScript it is called `Polyglot.eval`.
- The ability to access members in the [`polyglot bindings`](org/graalvm/polyglot/PolyglotAccess.Builder.md#allowBindingsAccess%28java.lang.String%29). The names of the guest language builtins to access polyglot bindings are language specific. In JavaScript they are called `Polyglot.import` and `Polyglot.export`.
Access to polyglot evaluation and bindings builtins are always enabled when access policy [`ALL`](org/graalvm/polyglot/PolyglotAccess.md#ALL) is used. In this mode polyglot evaluation builtins are available even if there is just one [`installed`](org/graalvm/polyglot/Engine.md#getLanguages%28%29) language available.
## Nested types
- [`PolyglotAccess.Builder`](org/graalvm/polyglot/PolyglotAccess.Builder.md) (class): A builder for a polyglot access configuration.
## Fields
### NONE
`public static final PolyglotAccess NONE`. Since 19.0. Provides guest languages no access to other languages using polyglot builtins evaluation and binding builtins. Cite: `org/graalvm/polyglot/PolyglotAccess.html#NONE`
### ALL
`public static final PolyglotAccess ALL`. Since 19.0. Provides guest languages full access to other languages using polyglot evaluation and binding builtins. Cite: `org/graalvm/polyglot/PolyglotAccess.html#ALL`
## Methods
### toString()
`public String toString()`. Since 25.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/PolyglotAccess.html#toString()`
### newBuilder()
`public static PolyglotAccess.Builder newBuilder()`. Since 19.2. Creates a new custom polyglot access configuration builder. A polyglot access builder starts with no access rights. Cite: `org/graalvm/polyglot/PolyglotAccess.html#newBuilder()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ PolyglotAccess.Builder
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.2. Nested in [`PolyglotAccess`](org/graalvm/polyglot/PolyglotAccess.md).
```java
public final class PolyglotAccess.Builder
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `Builder`
A builder for a polyglot access configuration. Builder instances are not thread-safe.
## Methods
### allowEvalBetween(String...)
`public PolyglotAccess.Builder allowEvalBetween(String... languages)`. Since 19.2. Allows bidirectional evaluation of code between the given languages. When called with language `"A"` and language `"B"`, this is equivalent to calling `allowEval``("A", "B")` and `allowEval``("B", "A")`. If called with more than two then all language evaluation combinations will be allowed. This method potentially overrides already configured access rights with `allowEval(String, String)` or `denyEval(String, String)`. The given language array must be non `null` and individual languages must not be `null`. See also: `allowEval(String, String)`. Cite: `org/graalvm/polyglot/PolyglotAccess.Builder.html#allowEvalBetween(java.lang.String...)`
### denyEvalBetween(String...)
`public PolyglotAccess.Builder denyEvalBetween(String... languages)`. Since 19.2. Denies bidirectional evaluation of code between the given languages. When called with language `"A"` and language `"B"`, this is equivalent to calling `denyEval``("A", "B")` and `denyEval``("B", "A")`. If called with more than two then all language access combinations will be denied. This method potentially overrides already configured access rights with `allowEval(String, String)` or `denyEval(String, String)`. The given language array must be non `null` and individual languages must not be `null`. See also: `denyEval(String, String)`. Cite: `org/graalvm/polyglot/PolyglotAccess.Builder.html#denyEvalBetween(java.lang.String...)`
### allowEval(String, String)
`public PolyglotAccess.Builder allowEval(String from, String to)`. Since 19.2. Allows evaluation of code by one language of another. This method only allows one-way evaluation access. Every language always has implicitly access to itself. If a language has access to one ore more different languages then the guest application will have access to polyglot evaluation builtins. If a language has no access granted to another language then access to polyglot evaluation builtins is denied. See also: `allowEvalBetween(String...)`. Cite: `org/graalvm/polyglot/PolyglotAccess.Builder.html#allowEval(java.lang.String,java.lang.String)`
### denyEval(String, String)
`public PolyglotAccess.Builder denyEval(String from, String to)`. Since 19.2. Denies evaluation of code by one language of another. This method only denies one-way evaluation. Every language has always evaluation access to itself. This access cannot be denied. See also: `denyEvalBetween(String...)`. Cite: `org/graalvm/polyglot/PolyglotAccess.Builder.html#denyEval(java.lang.String,java.lang.String)`
### allowBindingsAccess(String)
`public PolyglotAccess.Builder allowBindingsAccess(String language)`. Since 19.2. Allows access to polyglot bindings for a language. The names of the guest language builtins to access polyglot bindings are language specific. In JavaScript they are called `Polyglot.import` and `Polyglot.export`. See also: `denyBindingsAccess(String)`. Cite: `org/graalvm/polyglot/PolyglotAccess.Builder.html#allowBindingsAccess(java.lang.String)`
### denyBindingsAccess(String)
`public PolyglotAccess.Builder denyBindingsAccess(String language)`. Since 19.2. Denies access to polyglot bindings for a language. The provided language must not be `null`. See also: `allowBindingsAccess(String)`. Cite: `org/graalvm/polyglot/PolyglotAccess.Builder.html#denyBindingsAccess(java.lang.String)`
### toString()
`public String toString()`. Since 25.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/PolyglotAccess.Builder.html#toString()`
### build()
`public PolyglotAccess build()`. Since 19.2. Creates an instance of the custom polyglot access configuration. This method may be called multiple times to create more than one independent instances. Cite: `org/graalvm/polyglot/PolyglotAccess.Builder.html#build()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ⚡︎ PolyglotException
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Exception in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0.
```java
public final class PolyglotException extends RuntimeException
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > [`Throwable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html) > [`Exception`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Exception.html) > [`RuntimeException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/RuntimeException.html) > `PolyglotException`
A polyglot exception represents errors that contain Graal guest languages on the stack trace. In addition to the Java stack trace it also returns a [`polyglot stack trace`](org/graalvm/polyglot/PolyglotException.md#getPolyglotStackTrace%28%29). Methods like [`printStackTrace()`](org/graalvm/polyglot/PolyglotException.md#printStackTrace%28%29) are implemented such that host and guest language stack traces are printed nicely.
A polyglot exception may have the following properties:
- [`Guest Exception`](org/graalvm/polyglot/PolyglotException.md#isGuestException%28%29): Is `true` if the exception was raised in guest language code.
- [`Host Exception`](org/graalvm/polyglot/PolyglotException.md#isHostException%28%29): Is `true` if this exception was raised in host runtime code. This may happen if the polyglot runtime host runtime methods that throw an exception. The original host exception can be accessed using [`asHostException()`](org/graalvm/polyglot/PolyglotException.md#asHostException%28%29).
- [`Cancelled`](org/graalvm/polyglot/PolyglotException.md#isCancelled%28%29): Is `true` if the execution got cancelled. The execution may be cancelled when [`closing`](org/graalvm/polyglot/Context.md#close%28%29) a context, by a guest language intrinsic or by a tool, like the debugger.
- [`Exit`](org/graalvm/polyglot/PolyglotException.md#isExit%28%29): Is `true` if the execution exited. The guest language triggers exit events if the guest language code request to exit the VM. The exit status can be accessed using [`getExitStatus()`](org/graalvm/polyglot/PolyglotException.md#getExitStatus%28%29).
- [`Syntax Error`](org/graalvm/polyglot/PolyglotException.md#isSyntaxError%28%29): Is `true` if the error represents a syntax error. For syntax errors a [`location`](org/graalvm/polyglot/PolyglotException.md#getSourceLocation%28%29) may be available.
- [`Incomplete Source`](org/graalvm/polyglot/PolyglotException.md#isIncompleteSource%28%29): Is `true` if this returns a [`syntax error`](org/graalvm/polyglot/PolyglotException.md#isSyntaxError%28%29) that indicates that the source is incomplete.
- [`Resource exhausted`](org/graalvm/polyglot/PolyglotException.md#isResourceExhausted%28%29): Is `true` if a resource limit e.g. the maximum memory was exhausted.
- [`Internal Error`](org/graalvm/polyglot/PolyglotException.md#isInternalError%28%29): Is `true` if an internal implementation error occurred in the polyglot runtime, the guest language or an instrument. It is not recommended to show such errors to the user in production. Please consider filing issues for internal implementation errors.
**See also**
- [`Context`](org/graalvm/polyglot/Context.md)
- [`Value`](org/graalvm/polyglot/Value.md)
## Nested types
- [`PolyglotException.StackFrame`](org/graalvm/polyglot/PolyglotException.StackFrame.md) (class): Represents a polyglot stack frame originating from a guest language or the host language Java.
## Methods
### toString()
`public String toString()`. Since 25.0. Returns a short description of this exception. The result is the concatenation of: the qualified name of the metaobject of the guest exception, if this object represents one, and it has a metaobject. Otherwise, the [name](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Class.html#getName%28%29) of the `PolyglotException` class.; ": " (a colon and a space); the result of invoking this object's `getMessage` method If `getMessage` returns `null`, then just the class name is returned. Returns `String`: a string representation of this exception. Overrides `toString()`. Cite: `org/graalvm/polyglot/PolyglotException.html#toString()`
### printStackTrace()
`public void printStackTrace()`. Since 19.0. Prints host and guest language stack frames to the standard [`error output`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/System.html#err). Overrides `printStackTrace()`. Cite: `org/graalvm/polyglot/PolyglotException.html#printStackTrace()`
### printStackTrace(PrintStream)
`public void printStackTrace(PrintStream s)`. Since 19.0. Prints host and guest language stack frames to specified print stream. Overrides `printStackTrace(java.io.PrintStream)`. Cite: `org/graalvm/polyglot/PolyglotException.html#printStackTrace(java.io.PrintStream)`
### printStackTrace(PrintWriter)
`public void printStackTrace(PrintWriter s)`. Since 19.0. Prints host and guest language stack frames to specified print writer. Overrides `printStackTrace(java.io.PrintWriter)`. Cite: `org/graalvm/polyglot/PolyglotException.html#printStackTrace(java.io.PrintWriter)`
### fillInStackTrace()
`public Throwable fillInStackTrace()`. Since 19.0. Unsupported, `PolyglotException` instances are not writable therefore filling the stack trace has no effect for them. Overrides `fillInStackTrace()`. Cite: `org/graalvm/polyglot/PolyglotException.html#fillInStackTrace()`
### getStackTrace()
`public StackTraceElement[] getStackTrace()`. Since 19.0. Gets stack trace elements for Java and guest languages. For polyglot exceptions it recommended to use `getPolyglotStackTrace()` as the guest language stack elements do not always fit the Java format for stack trace elements. Overrides `getStackTrace()`. Cite: `org/graalvm/polyglot/PolyglotException.html#getStackTrace()`
### getMessage()
`public String getMessage()`. Since 19.0. Gets a user readable message for the polyglot exception. In case the exception is `internal` then the original java class name is included in the message. The message may return `null` if no message is available. Overrides `getMessage()`. Cite: `org/graalvm/polyglot/PolyglotException.html#getMessage()`
### getSourceLocation()
`public SourceSection getSourceLocation()`. Since 19.0. Gets a guest language source location of this error or `null` if no source location is available for this exception. Cite: `org/graalvm/polyglot/PolyglotException.html#getSourceLocation()`
### equals(Object)
`public boolean equals(Object obj)`. Since 19.0. Overrides `equals(java.lang.Object)`. Cite: `org/graalvm/polyglot/PolyglotException.html#equals(java.lang.Object)`
### hashCode()
`public int hashCode()`. Since 19.0. Overrides `hashCode()`. Cite: `org/graalvm/polyglot/PolyglotException.html#hashCode()`
### setStackTrace(StackTraceElement[])
`public void setStackTrace(StackTraceElement[] stackTrace)`. Since 19.0. Unsupported, `PolyglotException` instances are not writable therefore setting the stack trace has no effect for them. Overrides `setStackTrace(java.lang.StackTraceElement[])`. Cite: `org/graalvm/polyglot/PolyglotException.html#setStackTrace(java.lang.StackTraceElement[])`
### getPolyglotStackTrace()
`public Iterable getPolyglotStackTrace()`. Since 19.0. Provides programmatic access to the polyglot stack trace information printed by `printStackTrace()`. Returns an array of stack trace elements, each representing one stack frame. The zeroth element of the array (assuming the array's length is non-zero) represents the top of the stack, which is the last invocation in the sequence. Typically, this is the point at which this throwable was created and thrown. The last element of the array (assuming the array's length is non-zero) represents the bottom of the stack, which is the first method invocation in the sequence. See also: `StackFrame`. Cite: `org/graalvm/polyglot/PolyglotException.html#getPolyglotStackTrace()`
### isHostException()
`public boolean isHostException()`. Since 19.0. Returns `true` if this exception originates from the Java host language. In such a case the first `stack frame` returns a `host frame` as zeroth element. Cite: `org/graalvm/polyglot/PolyglotException.html#isHostException()`
### isGuestException()
`public boolean isGuestException()`. Since 19.0. Returns `true` if this exception originates from a Graal guest language. In such a case the first `stack frame` returns a `guest frame` as zeroth element. Cite: `org/graalvm/polyglot/PolyglotException.html#isGuestException()`
### asHostException()
`public Throwable asHostException()`. Since 19.0. Returns the original Java host exception that caused this exception. The original host exception contains a stack trace that is hardly interpretable by users as it contains details of the language implementation. The polyglot exception provides information for user-friendly error reporting with the `polyglot stack trace`. Throws: `UnsupportedOperationException` (unchecked): if this exception is not a host exception. Call `isHostException()` to ensure its originating from the host language. Cite: `org/graalvm/polyglot/PolyglotException.html#asHostException()`
### isInternalError()
`public boolean isInternalError()`. Since 19.0. Returns `true` if this exception was caused by an internal implementation error. These errors should be reported as bugs if observed. Internal error messages are typically hard to understand for guest language programmers and might contain implementation specific details that allows guest language implementers to debug the problem. Cite: `org/graalvm/polyglot/PolyglotException.html#isInternalError()`
### isResourceExhausted()
`public boolean isResourceExhausted()`. Since 20.2. Returns `true` if this exception indicates that a resource limit was exceeded, else `false`. Resource limit exceeded errors may be raised for the following reasons: The host runtime run out of memory or stack space. For example if host runtime throws [`OutOfMemoryError`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/OutOfMemoryError.html) or [`StackOverflowError`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/StackOverflowError.html), then they will be translated to a `PolyglotException` that return `true` for `isResourceExhausted()`.; A configured `resource limit` was exceeded.; A runtime specific per context resource limit was exceeded. Depending on the host runtime implementation additional options to restrict the resource usage of a context may be specified using options. Resource limit exceptions may be originating from the `host` or `guest`. Resource limit exceeded errors are never `internal`, but may have caused the context to be `cancelled` such that it is no longer usable. Cite: `org/graalvm/polyglot/PolyglotException.html#isResourceExhausted()`
### isCancelled()
`public boolean isCancelled()`. Since 19.0. Returns `true` if the execution was cancelled. The execution can be cancelled by `closing` a context, if an instrument such as a debugger decides to cancel the current execution or if a `resource limit` was exceeded. The context that caused a cancel event becomes unusable, i.e. closed. Cite: `org/graalvm/polyglot/PolyglotException.html#isCancelled()`
### isInterrupted()
`public boolean isInterrupted()`. Since 20.3. Returns `true` if the current application thread was interrupted by an [`InterruptedException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/InterruptedException.html), or by calling `Context.interrupt(Duration)` from the host. Cite: `org/graalvm/polyglot/PolyglotException.html#isInterrupted()`
### isExit()
`public boolean isExit()`. Since 19.0. Returns `true` if this exception is caused by an attempt of a guest language program to exit the application. The provided exit code can be accessed using `getExitStatus()`. This can be the result of either the soft or the hard exit. See also: `Context`. Cite: `org/graalvm/polyglot/PolyglotException.html#isExit()`
### isSyntaxError()
`public boolean isSyntaxError()`. Since 19.0. Returns `true` if this exception indicates a parser or syntax error. In such a case #get. Cite: `org/graalvm/polyglot/PolyglotException.html#isSyntaxError()`
### isIncompleteSource()
`public boolean isIncompleteSource()`. Since 19.0. Returns `true` if this exception indicates a syntax error that is indicating that the syntax is incomplete. This allows guest language programmers to find out if more code is expected from a given source. For example, an incomplete JavaScript program could look like this: A shell might react to this exception and prompt for additional source code, if this method returns `true`. Cite: `org/graalvm/polyglot/PolyglotException.html#isIncompleteSource()`
```java
function incompleteFunction(arg) {
```
### getGuestObject()
`public Value getGuestObject()`. Since 19.0. Returns an additional guest language object. Returns `null` if no exception object is available. Cite: `org/graalvm/polyglot/PolyglotException.html#getGuestObject()`
### getExitStatus()
`public int getExitStatus()`. Since 19.0. Returns the exit status if this exception indicates that the application was `exited`. The exit status is intended to be passed to [`System.exit(int)`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/System.html#exit%28int%29). In case of hard exit the application can be configured to call [`System.exit(int)`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/System.html#exit%28int%29) directly using `Context.Builder.useSystemExit(boolean)`. See also: `Context`. Cite: `org/graalvm/polyglot/PolyglotException.html#getExitStatus()`
## Inherited members
- From class [`Throwable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html): [`addSuppressed`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#addSuppressed%28java.lang.Throwable%29), [`getCause`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#getCause%28%29), [`getLocalizedMessage`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#getLocalizedMessage%28%29), [`getSuppressed`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#getSuppressed%28%29), [`initCause`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#initCause%28java.lang.Throwable%29)
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ PolyglotException.StackFrame
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0. Nested in [`PolyglotException`](org/graalvm/polyglot/PolyglotException.md).
```java
public final class PolyglotException.StackFrame
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `StackFrame`
Represents a polyglot stack frame originating from a guest language or the host language Java.
## Methods
### isHostFrame()
`public boolean isHostFrame()`. Since 19.0. Returns true if the stack frame originates from the host language. Host frames do not provide a `source location`. Instead the Java stack frame can be accessed using `toHostFrame()`. Cite: `org/graalvm/polyglot/PolyglotException.StackFrame.html#isHostFrame()`
### isGuestFrame()
`public boolean isGuestFrame()`. Since 19.0. Returns true if the stack frame originates from the guest language. Cite: `org/graalvm/polyglot/PolyglotException.StackFrame.html#isGuestFrame()`
### toHostFrame()
`public StackTraceElement toHostFrame()`. Since 19.0. Returns a Java stack trace element representation of the polyglot stack trace element. This is supported for host stack frames as well as guest language stack frames. A conversion to the host frame format can be useful for interoperability. Cite: `org/graalvm/polyglot/PolyglotException.StackFrame.html#toHostFrame()`
### getSourceLocation()
`public SourceSection getSourceLocation()`. Since 19.0. Returns the source location of the stack frame or `null` if no source location is available. Host frames do never provide a source location. Cite: `org/graalvm/polyglot/PolyglotException.StackFrame.html#getSourceLocation()`
### getBytecodeIndex()
`public int getBytecodeIndex()`. Since 24.1. Returns the bytecode index of this frame if available, or a negative number if no bytecode index is available. The bytecode index is an internal identifier of the current execution location. The bytecode index is typically only provided by languages that are internally implemented as bytecode interpreter. This information is exposed for debugging or testing purposes and should not be relied upon for anything else. Cite: `org/graalvm/polyglot/PolyglotException.StackFrame.html#getBytecodeIndex()`
### getRootName()
`public String getRootName()`. Since 19.0. Returns the root name of this stack frame. In case of the host language the Java method name is returned. In guest languages it returns a useful identifier for code. For example, in JavaScript this can be the function name. Cite: `org/graalvm/polyglot/PolyglotException.StackFrame.html#getRootName()`
### getLanguage()
`public Language getLanguage()`. Since 19.0. Returns the language of this stack frame. In case of the host language a synthetic Java language object is returned. Cite: `org/graalvm/polyglot/PolyglotException.StackFrame.html#getLanguage()`
### toString()
`public String toString()`. Since 19.0. Returns a string representation of this stack frame. The format is inspired by the Java stack frame format. Overrides `toString()`. Cite: `org/graalvm/polyglot/PolyglotException.StackFrame.html#toString()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ PreinitializedSources
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 25.4.
```java
public final class PreinitializedSources
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `PreinitializedSources`
Registers sources that context pre-initialization parses when a native image is built. Context pre-initialization is enabled with the image build time system property `polyglot.image-build-time.PreinitializeContexts`, see [`Context`](org/graalvm/polyglot/Context.md).
Pre-initialization parses each registered source with its language in the pre-initialized context, and never executes it. A source that a context of the image parses later and that is [equal](org/graalvm/polyglot/Source.md#equals%28java.lang.Object%29) to a registered source then uses the call target parsed at build time, provided that the context uses the pre-initialized context. Two sources are equal only if everything the source builder can set is equal, e.g., the characters, name, MIME type, path and URI, so a source registered here should be built exactly as the image will build it at run time.
Sources are registered while the image is built, before the contexts are pre-initialized, e.g., from `Feature.duringSetup` of a `org.graalvm.nativeimage.hosted.Feature`. The system property `polyglot.image-build-time.PreinitializeSources` is a shorthand for registering sources read from files, with a name and no MIME type.
Registering is a hint: a registered source is parsed only if the image pre-initializes its language, i.e., the language is listed in `polyglot.image-build-time.PreinitializeContexts`. Otherwise the source is skipped, so a library can register its sources from its own feature without failing the builds of images that do not pre-initialize its language. If the language is pre-initialized but does not support context patching, the image build fails.
Only sources that the embedder parses, e.g., with [`Context.eval(Source)`](org/graalvm/polyglot/Context.md#eval%28org.graalvm.polyglot.Source%29) or [`Context.parse(Source)`](org/graalvm/polyglot/Context.md#parse%28org.graalvm.polyglot.Source%29), can use a registered source. A source that a language creates itself, e.g., a module that its module loader loads for an `import`, is never equal to a registered source. A source built from a [`java.io.File`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/File.html) or [`java.net.URL`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/net/URL.html) has the path or URI of the build machine, so it is equal to a source of the image only if the image builds it from the same path or URI; prefer a [literal source](org/graalvm/polyglot/Source.md#newBuilder%28java.lang.String,java.lang.CharSequence,java.lang.String%29) with a name and a MIME type.
On a JVM, context pre-initialization can be debugged by setting the system property `polyglot.image-build-time.PreinitializeContexts`: the contexts are then pre-initialized when the polyglot implementation is loaded, before any source can be registered, so sources cannot be registered in this mode.
```java
public final class MyFeature implements Feature {
@Override
public void duringSetup(DuringSetupAccess access) {
PreinitializedSources.register(Source.newBuilder("js", moduleCode, "main.mjs").mimeType("application/javascript+module").buildLiteral());
}
}
```
## Methods
### register(Source...)
`public static void register(Source... sources)`. Since 25.4. Registers `sources` to be parsed by context pre-initialization: all of them, or none if this method throws. Throws: `IllegalStateException` (unchecked): if the contexts were already pre-initialized, or if called in a native image at run time. `UnsupportedOperationException` (unchecked): if no polyglot implementation that supports context pre-initialization is installed. Cite: `org/graalvm/polyglot/PreinitializedSources.html#register(org.graalvm.polyglot.Source...)`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`toString`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#toString%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ ResourceLimitEvent
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.3.
```java
public final class ResourceLimitEvent
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `ResourceLimitEvent`
Event triggered by a resource limit for a context. Event objects are short-lived and should not be stored. Their use should be limited to the duration of the event.
**See also**
- [`ResourceLimits`](org/graalvm/polyglot/ResourceLimits.md)
## Methods
### getContext()
`public Context getContext()`. Since 19.3. The context for which the limit was exceeded. Never `null`. Cite: `org/graalvm/polyglot/ResourceLimitEvent.html#getContext()`
### toString()
`public String toString()`. Since 19.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/ResourceLimitEvent.html#toString()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ ResourceLimits
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.3.
```java
public final class ResourceLimits
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `ResourceLimits`
Represents resource limits configuration that is used to configure contexts. Resource limit instances are created using the [`builder`](org/graalvm/polyglot/ResourceLimits.md#newBuilder%28%29) and activated by [`enabling`](org/graalvm/polyglot/Context.Builder.md#resourceLimits%28org.graalvm.polyglot.ResourceLimits%29) them for a [`context`](org/graalvm/polyglot/Context.md). All configured limits are applied per context instance. Resource limits may be [`reset`](org/graalvm/polyglot/Context.md#resetLimits%28%29). If a resource limit is triggered the context that triggered the limit will automatically be [`closed`](org/graalvm/polyglot/Context.md#close%28boolean%29) and can no longer be used to evaluate code.
The following resource limits are supported:
- [`Statement count`](org/graalvm/polyglot/ResourceLimits.Builder.md#statementLimit%28long,java.util.function.Predicate%29) limit per context. Allows to limit the amount of statements executed per context.
### Statement Limit Example
`
``
ResourceLimits limits = ResourceLimits.newBuilder()
.statementLimit(500, null)
.build();
try (Context context = Context.newBuilder("js")
.resourceLimits(limits)
.build();) {
try {
context.eval("js", "while(true);");
assert false;
} catch (PolyglotException e) {
// triggered after 500 iterations of while(true);
// context is closed and can no longer be used
assert e.isCancelled();
}
}
``
`
**See also**
- [`newBuilder()`](org/graalvm/polyglot/ResourceLimits.md#newBuilder%28%29)
## Nested types
- [`ResourceLimits.Builder`](org/graalvm/polyglot/ResourceLimits.Builder.md) (class): A builder used to construct resource limits.
## Methods
### newBuilder()
`public static ResourceLimits.Builder newBuilder()`. Since 19.3. Creates a new builder to construct `ResourceLimits` instances. Cite: `org/graalvm/polyglot/ResourceLimits.html#newBuilder()`
### toString()
`public String toString()`. Since 25.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/ResourceLimits.html#toString()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ ResourceLimits.Builder
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.3. Nested in [`ResourceLimits`](org/graalvm/polyglot/ResourceLimits.md).
```java
public final class ResourceLimits.Builder
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `Builder`
A builder used to construct resource limits. Builder instances are not thread-safe and may not be used from multiple threads at the same time.
## Methods
### statementLimit(long, Predicate)
`public ResourceLimits.Builder statementLimit(long limit, Predicate sourceFilter)`. Since 19.3. Specifies the maximum number of statements a context may execute until the onLimit event is notified and the context will be `closed`. After the statement limit was triggered for a context, it is no longer usable and every use of the context will throw a `PolyglotException` that returns `true` for `PolyglotException.isCancelled()`. The statement limit is independent of the number of threads executing and is applied per context. Invoking this method multiple times overwrites previous statement limit configurations. If the statement limit is exceeded then the `onLimit` listener is notified. By default there is no statement limit applied. The limit may be set to 0 to disable it. In addition to the limit a source filter may be set to indicate for which sources the limit should be applied. If the source filter is `null` then it will be applied to all `internal` and public sources. The provided limit must not be negative otherwise an [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) is thrown. If a `shared engine` is used then the same source filter instance must be used for all contexts of an engine. Otherwise an [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) is thrown when the context is `built`. The limit itself may vary between contexts. The statement limit is applied to the context and all inner contexts it spawns. Therefore, new inner contexts cannot be used to exceed the statement limit. Note that attaching a statement limit to a context reduces the throughput of all guest applications with the same engine. The statement counter needs to be updated with every statement that is executed. It is recommended to benchmark the use of the statement limit before it is used in production. Note that the complexity of a single statement may not be constant time depending on the guest language. For example, statements that execute JavaScript builtins, like `Array.sort`, may account for a single statement, but its execution time is dependent on the size of the array. The statement count limit is therefore not suitable to perform time boxing and must be combined with other more reliable measures. See also: `Example Usage`. Cite: `org/graalvm/polyglot/ResourceLimits.Builder.html#statementLimit(long,java.util.function.Predicate)`
### onLimit(Consumer)
`public ResourceLimits.Builder onLimit(Consumer onLimit)`. Since 19.3. Notified when a resource limit is reached. Default is `null`. May be set to `null` to disable events. Cite: `org/graalvm/polyglot/ResourceLimits.Builder.html#onLimit(java.util.function.Consumer)`
### toString()
`public String toString()`. Since 25.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/ResourceLimits.Builder.html#toString()`
### build()
`public ResourceLimits build()`. Since 19.3. Builds the limit configuration object. See also: `Example Usage`. Cite: `org/graalvm/polyglot/ResourceLimits.Builder.html#build()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ≡ SandboxPolicy
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Enum class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 23.0.
```java
public enum SandboxPolicy
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > [`Enum`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html) > `SandboxPolicy`
The sandbox policy presets and validates configurations of a [`context`](org/graalvm/polyglot/Context.md) or [`engine`](org/graalvm/polyglot/Engine.md) to be suitable as a code sandbox. The policy is set by passing it to the [`engine`](org/graalvm/polyglot/Engine.Builder.md#sandbox%28org.graalvm.polyglot.SandboxPolicy%29) or [`context`](org/graalvm/polyglot/Context.Builder.md#sandbox%28org.graalvm.polyglot.SandboxPolicy%29) builder method.
There are four policies to choose from that become strictly more strict:
- [`TRUSTED`](org/graalvm/polyglot/SandboxPolicy.md#TRUSTED) policy intended for fully trusted applications. In this mode, access to any resource of the host might be accessible to the guest application. This is the default mode, there are no restrictions to the context or engine configuration.
- [`CONSTRAINED`](org/graalvm/polyglot/SandboxPolicy.md#CONSTRAINED) policy intended for trusted, but potentially buggy applications. In this mode, any access to host resources is required to be as restrictive as possible. In this mode, the guest and host application share a heap and execute on the same underlying virtual machine.
- [`ISOLATED`](org/graalvm/polyglot/SandboxPolicy.md#ISOLATED) policy intended for trusted applications, but which might have security vulnerabilities and optionally that can be mitigated using this policy. For example, a script that processes untrusted input. Security vulnerabilities would allow an attacker to compromise the guest application by providing malicious input. In this mode, guest and host application execute on separate virtual machine instances.
- [`UNTRUSTED`](org/graalvm/polyglot/SandboxPolicy.md#UNTRUSTED) policy intended for fully untrusted applications. This assumes that a potentially malicious actor is supplying the guest code itself that is being run. A strong adversarial scenario is the execution of client-side Javascript in the browser that is supplied by an untrusted website. In this mode, the sandbox employs additional hardening mechanisms at the compiler and runtime level to mitigate e.g. JIT spraying or speculative execution attacks.
It is unsupported to run untrusted code with any other policy than [`UNTRUSTED`](org/graalvm/polyglot/SandboxPolicy.md#UNTRUSTED).
** Compatibility Notice:** The behavior of sandbox policies is subject to incompatible changes for new GraalVM major releases. New presets and validations may be added in new GraalVM releases that may let configurations valid in older versions fail for newer versions. Therefore, adopting a new GraalVM version with a set sandbox policy might require changes for the embedder. This applies to all policies other than [`TRUSTED`](org/graalvm/polyglot/SandboxPolicy.md#TRUSTED). Changes to the policy are announced in the SDK [release changelog](https://github.com/oracle/graal/blob/master/sdk/CHANGELOG.md).
For further information on Polyglot Sandboxing, please refer to the [security guide](https://www.graalvm.org/latest/security-guide/polyglot-sandbox/).
**See also**
- [`Context.Builder.sandbox(SandboxPolicy)`](org/graalvm/polyglot/Context.Builder.md#sandbox%28org.graalvm.polyglot.SandboxPolicy%29)
- [`Engine.Builder.sandbox(SandboxPolicy)`](org/graalvm/polyglot/Engine.Builder.md#sandbox%28org.graalvm.polyglot.SandboxPolicy%29)
## Enum constants
### TRUSTED
`TRUSTED`. Since 23.0. Policy intended for fully trusted applications. In this mode, access to any resource of the host might be accessible to the guest application. This is the default mode, there are no restrictions to the context or engine configuration. Cite: `org/graalvm/polyglot/SandboxPolicy.html#TRUSTED`
### CONSTRAINED
`CONSTRAINED`. Since 23.0. Policy intended for trusted, but potentially buggy applications. In this mode, any access to host resources is required to be as restrictive as possible. In this mode, the guest and host application share a heap and execute on the same underlying virtual machine. The `CONSTRAINED` sandbox policy enforces the following context restriction: The list of `permitted languages` must be explicitly set.; If `in` is not specified, the [`InputStream.nullInputStream()`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/InputStream.html#nullInputStream%28%29) is used. Otherwise, it must be redirected elsewhere than to [`System.in`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/System.html#in).; Standard `out` and `Context.Builder.err(OutputStream)` err} streams must be redirected.; The `all access` must not be enabled.; The `native access` must not be enabled.; The `Context.Builder.allowHostClassLoading(boolean)` host class loading} must not be enabled.; The `external process execution` must not be enabled.; The `environment access` must be `EnvironmentAccess.NONE`.; If the `time zone` is not specified, UTC is used instead of the host default time zone.; The `host System.exit` must not be used.; The `access to the host file system` must be disabled. IO can be `disabled` or it can use a `custom file system`.; GraalVM trusts custom file systems supplied by the embedder. The embedder must ensure that a custom file system does not expose the host file system or other host resources prohibited by the selected sandbox policy to guest code. Sandbox validation rejects the `default file system` and GraalVM-provided file system decorators known to expose it, but it cannot determine the behavior of arbitrary custom `FileSystem` implementations.; Only languages with a sandbox policy of at least `CONSTRAINED` can be used.; Only instruments with a sandbox policy of at least `CONSTRAINED` can be used.; Only a subset of options that are safe with the sandbox policy can be used.; If `HostAccess` is not specified, the `HostAccess.CONSTRAINED` is used.; Otherwise, the specified; `HostAccess`; must not allow; `unrestricted public access`; ,; `predicate-selected public access`; ,; `access inheritance`; ,; `all class implementations`; ,; `all interface implementations`; and; `mutable target type mappings`; .; The `execution listeners` must not be attached.; The `message transport` must not be set. Constrained Context building example: Cite: `org/graalvm/polyglot/SandboxPolicy.html#CONSTRAINED`
```java
ByteArrayOutputStream output = new ByteArrayOutputStream();
ByteArrayOutputStream errorOutput = new ByteArrayOutputStream();
try (Context context = Context.newBuilder("js") //
.sandbox(SandboxPolicy.CONSTRAINED) //
.out(output) //
.err(errorOutput) //
.build()) {
context.eval(source);
}
```
### ISOLATED
`ISOLATED`. Since 23.0. Policy intended for trusted applications, but which might have security vulnerabilities and optionally that can be mitigated using this policy. For example, a script that processes untrusted input. Security vulnerabilities may allow an attacker to compromise the guest application by providing malicious input. In this mode, guest and host application execute on separate virtual machine instances. In addition to the `CONSTRAINED` restrictions, the `ISOLATED` sandbox policy adds the following constraints: The `engine.SpawnIsolate` option is preset to `true` if it has not been explicitly set.; The `engine.MaxIsolateMemory` option must be set.; The `sandbox.MaxCPUTime` limits option must be set. Use `sandbox.TraceLimits` to estimate an application's optimal sandbox parameters.; If `HostAccess` is not specified, the `HostAccess.ISOLATED` is used.; Otherwise, the specified; `HostAccess`; must meet all the constraints of the; `CONSTRAINED`; sandbox policy and must in addition use; `scoped references`; . Isolated Context building example: Cite: `org/graalvm/polyglot/SandboxPolicy.html#ISOLATED`
```java
ByteArrayOutputStream output = new ByteArrayOutputStream();
ByteArrayOutputStream errorOutput = new ByteArrayOutputStream();
try (Context context = Context.newBuilder("js") //
.sandbox(SandboxPolicy.ISOLATED) //
.out(output) //
.err(errorOutput) //
.option("engine.MaxIsolateMemory", "1GB") //
.option("sandbox.MaxCPUTime", "10s") //
.build()) {
context.eval(source);
}
```
### UNTRUSTED
`UNTRUSTED`. Since 23.0. Policy intended for untrusted applications. This assumes that a malicious actor is supplying the guest code itself that is being run. A strong adversarial scenario is the execution of client-side Javascript in the browser that is supplied by an untrusted website. In this mode, the sandbox employs additional hardening mechanisms at the compiler and runtime level to mitigate e.g. speculative execution attacks. In addition to the `ISOLATED` constraints, the `UNTRUSTED` sandbox policy adds the following requirements: If `HostAccess` is not explicitly specified, the `HostAccess.UNTRUSTED` is utilized. In the case where a specific `HostAccess` is provided, it must strictly adhere to all the constraints outlined in the `ISOLATED` sandbox policy. Additionally, for UNTRUSTED, the following `HostAccess` options are not allowed: Setting `implementations of types annotated by an annotation`.; Setting `array access` to `true`.; Setting `list access` to `true`.; Setting `map access` to `true`.; Setting `buffer access` to `true`.; Setting `iterable access` to `true`.; Setting `iterator access` to `true`.; The `engine.UntrustedCodeMitigation` option is preset to `software` if it has not been explicitly set.; The `sandbox.MaxCPUTime`, `sandbox.MaxHeapMemory`, `sandbox.MaxASTDepth`, `sandbox.MaxThreads`, `sandbox.MaxOutputStreamSize`, `sandbox.MaxErrorStreamSize` limits options must be set. Use `sandbox.TraceLimits` to estimate an application's optimal sandbox parameters.; The `sandbox.MaxStackFrames` limit option may be set to restrict the number of guest stack frames. If the option is not set, no explicit guest stack frame limit is enforced. Untrusted Context building example: Cite: `org/graalvm/polyglot/SandboxPolicy.html#UNTRUSTED`
```java
ByteArrayOutputStream output = new ByteArrayOutputStream();
ByteArrayOutputStream errorOutput = new ByteArrayOutputStream();
try (Context context = Context.newBuilder("js") //
.sandbox(SandboxPolicy.UNTRUSTED) //
.out(output) //
.err(errorOutput) //
.option("engine.MaxIsolateMemory", "1GB") //
.option("sandbox.MaxHeapMemory", "800MB") //
.option("sandbox.MaxCPUTime", "10s") //
.option("sandbox.MaxASTDepth", "100") //
.option("sandbox.MaxThreads", "1") //
.option("sandbox.MaxOutputStreamSize", "1MB") //
.option("sandbox.MaxErrorStreamSize", "1MB") //
.build()) {
context.eval(source);
}
```
## Methods
### values()
`public static SandboxPolicy[] values()`. Returns the enum constants in declaration order. Returns `SandboxPolicy[]`: Returns the enum constants in declaration order. Cite: `org/graalvm/polyglot/SandboxPolicy.html#values()`
### valueOf(String)
`public static SandboxPolicy valueOf(String name)`. Returns the enum constant with the given name. Parameters: `name` `String`: The exact name of the enum constant. Returns `SandboxPolicy`: Returns the enum constant with the given name. Cite: `org/graalvm/polyglot/SandboxPolicy.html#valueOf(java.lang.String)`
### isStricterThan(SandboxPolicy)
`public boolean isStricterThan(SandboxPolicy other)`. Since 23.0. Tests whether this `SandboxPolicy` is stricter than `other`. Cite: `org/graalvm/polyglot/SandboxPolicy.html#isStricterThan(org.graalvm.polyglot.SandboxPolicy)`
### isStricterOrEqual(SandboxPolicy)
`public boolean isStricterOrEqual(SandboxPolicy other)`. Since 23.0. Tests whether this `SandboxPolicy` is stricter or equal to `other`. Cite: `org/graalvm/polyglot/SandboxPolicy.html#isStricterOrEqual(org.graalvm.polyglot.SandboxPolicy)`
## Inherited members
- From class [`Enum`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#clone%28%29), [`compareTo`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#compareTo%28E%29), [`describeConstable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#describeConstable%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#finalize%28%29), [`getDeclaringClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#getDeclaringClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#hashCode%28%29), [`name`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#name%28%29), [`ordinal`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#ordinal%28%29), [`toString`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#toString%28%29), [`valueOf`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Enum.html#valueOf%28java.lang.Class,java.lang.String%29)
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ Source
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0.
```java
public final class Source
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `Source`
Representation of a source code unit and its contents that can be evaluated in an execution [`context`](org/graalvm/polyglot/Context.md). Each source is associated with the ID of the language.
### From a file on disk
Each file is represented as a canonical object, indexed by the absolute, canonical path name of the file. File content is *read eagerly* and may be optionally *cached*. Sample usage:
```java
File file = new File(dir, name);
assert name.endsWith(".java") : "Imagine proper file";
String language = Source.findLanguage(file);
Source source = Source.newBuilder(language, file).build();
assert file.getName().equals(source.getName());
assert file.getPath().equals(source.getPath());
assert file.toURI().equals(source.getURI());
```
The starting point is [`Source.newBuilder(String, java.io.File)`](org/graalvm/polyglot/Source.md#newBuilder%28java.lang.String,java.io.File%29) method.
### Read from a URL
One can read remote or in JAR resources using the [`Source.newBuilder(String, java.net.URL)`](org/graalvm/polyglot/Source.md#newBuilder%28java.lang.String,java.net.URL%29) factory:
```java
URL resource = relativeClass.getResource("sample.js");
Source source = Source.newBuilder("js", resource).build();
assert resource.toExternalForm().equals(source.getPath());
assert "sample.js".equals(source.getName());
assert resource.toURI().equals(source.getURI());
```
Each URL source is represented as a canonical object, indexed by the URL. Contents are *read eagerly* once the [`Builder.build()`](org/graalvm/polyglot/Source.Builder.md#build%28%29) method is called.
### Source from a literal text
An anonymous immutable code snippet can be created from a string via the [`Source.newBuilder(String, java.lang.CharSequence, String)`](org/graalvm/polyglot/Source.md#newBuilder%28java.lang.String,java.lang.CharSequence,java.lang.String%29) factory method:
```java
Source source = Source.newBuilder("js", "function() {\n" + " return 'Hi';\n" + "}\n", "hi.js").buildLiteral();
assert "hi.js".equals(source.getName());
```
### Reading from a stream
If one has a [`Reader`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/Reader.html) one can convert its content into a [`Source`](org/graalvm/polyglot/Source.md) via [`Source.newBuilder(String, java.io.Reader, String)`](org/graalvm/polyglot/Source.md#newBuilder%28java.lang.String,java.io.Reader,java.lang.String%29) method:
```java
Reader stream = new InputStreamReader(
relativeClass.getResourceAsStream("sample.js"));
Source source = Source.newBuilder("js", stream, "sample.js").build();
assert "sample.js".equals(source.getName());
```
the content is *read eagerly* once the [`Builder.build()`](org/graalvm/polyglot/Source.Builder.md#build%28%29) method is called.
### Reading from bytes
Sources can be created from bytes. Please note that all character related methods will throw an [`UnsupportedOperationException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/UnsupportedOperationException.html) if that is the case.
```java
byte[] bytes = new byte[]{ /* Binary */ };
Source source = Source.newBuilder("llvm",
ByteSequence.create(bytes),
"").buildLiteral();
```
## Attributes
The source object can be associated with various attributes like [`getName()`](org/graalvm/polyglot/Source.md#getName%28%29) and [`getURI()`](org/graalvm/polyglot/Source.md#getURI%28%29), [`getMimeType()`](org/graalvm/polyglot/Source.md#getMimeType%28%29) and these are immutable. The system makes the best effort to derive values of these attributes from the location and/or content of the [`Source`](org/graalvm/polyglot/Source.md) object. However, to give the user that creates the source control over these attributes, the API offers an way to alter values of these attributes.
## Character and byte based Sources
A source is [`byte`](org/graalvm/polyglot/Source.md#hasBytes%28%29) or [`character`](org/graalvm/polyglot/Source.md#hasCharacters%28%29) based, or none of those when no content is specified. For literal sources it depends on whether the byte or character based factory method was used. When the source was loaded from a [`file`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/File.html) or [`url`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/net/URL.html) then the [`default MIME type`](org/graalvm/polyglot/Language.md#getDefaultMimeType%28%29) of the provided language will be used to determine whether bytes or characters should be loaded. The behavior can be customized by specifying a [`MIME type`](org/graalvm/polyglot/Source.Builder.md#mimeType%28java.lang.String%29) or [`content`](org/graalvm/polyglot/Source.Builder.md#content%28org.graalvm.polyglot.io.ByteSequence%29) explicitly. If the specified or inferred MIME type starts with `'text/` or the MIME types is `null` then it will be interpreted as character based, otherwise byte based.
**See also**
- [`To evaluate sources.`](org/graalvm/polyglot/Context.md#eval%28org.graalvm.polyglot.Source%29)
- [`To detect a language using a File`](org/graalvm/polyglot/Source.md#findLanguage%28java.io.File%29)
- [`To detect a language using a URL.`](org/graalvm/polyglot/Source.md#findLanguage%28java.net.URL%29)
- [`To detect a MIME type using a File.`](org/graalvm/polyglot/Source.md#findMimeType%28java.io.File%29)
- [`To detect a MIME type using a URL.`](org/graalvm/polyglot/Source.md#findMimeType%28java.net.URL%29)
## Nested types
- [`Source.Builder`](org/graalvm/polyglot/Source.Builder.md) (class): Represents a builder to build Source objects.
## Methods
### getLanguage()
`public String getLanguage()`. Since 19.0. Returns the language this source created with. The string returned matches the `id` of the language. Cite: `org/graalvm/polyglot/Source.html#getLanguage()`
### getName()
`public String getName()`. Since 19.0. Returns the name of this resource holding a guest language program. An example would be the name of a guest language source code file. Name is supposed to be shorter than `getPath()`. Returns `String`: the name of the guest language program. See also: `Builder.name(String)`. Cite: `org/graalvm/polyglot/Source.html#getName()`
### getPath()
`public String getPath()`. Since 19.0. The fully qualified name of the source. In case this source originates from a [`File`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/File.html), then the path is the normalized, [`canonical path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/File.html#getCanonicalPath%28%29) for absolute files, or the relative path otherwise. If the source originates from an [`URL`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/net/URL.html), then it's the path component of the URL. Cite: `org/graalvm/polyglot/Source.html#getPath()`
### getURL()
`public URL getURL()`. Since 19.0. The URL if the source is retrieved via URL. Returns `URL`: URL or `null`. Cite: `org/graalvm/polyglot/Source.html#getURL()`
### getURI()
`public URI getURI()`. Since 19.0. Get the URI of the source. Every source has an associated [`URI`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/net/URI.html), which can be used as a persistent identification of the source. The [`URI`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/net/URI.html) returned by this method should be as unique as possible, yet it can happen that different `sources` return the same `getURI` - for example when content of a `file on a disk` changes and is re-loaded. Returns `URI`: a URI, never `null`. Cite: `org/graalvm/polyglot/Source.html#getURI()`
### isInteractive()
`public boolean isInteractive()`. Since 19.0. Check whether this source has been marked as *interactive*. Interactive sources are provided by an entity which is able to interactively read output and provide an input during the source execution; that can be a user I/O through an interactive shell for instance. One can specify whether a source is interactive when `building it`. Returns `boolean`: whether this source is marked as *interactive*. Cite: `org/graalvm/polyglot/Source.html#isInteractive()`
### isInternal()
`public boolean isInternal()`. Since 19.0. Gets whether this source has been marked as *internal*, meaning that it has been provided by the infrastructure, language implementation, or system library. *Internal* sources are presumed to be irrelevant to guest language programmers, as well as possibly confusing and revealing of language implementation details. On the other hand, tools should be free to make *internal* sources visible in (possibly privileged) modes that are useful for language implementors. One can specify whether a source is internal when `building it`. Returns `boolean`: whether this source is marked as *internal*. Cite: `org/graalvm/polyglot/Source.html#isInternal()`
### getReader()
`public Reader getReader()`. Since 19.0. Returns a new reader that reads from the `characters` provided by this source. Throws: `UnsupportedOperationException` (unchecked): if this source cannot contain `characters`. Cite: `org/graalvm/polyglot/Source.html#getReader()`
### getInputStream()
`@Deprecated(since = "19.0") public InputStream getInputStream()`. Since 19.0. Deprecated since 19.0. use `getReader()`, `getCharacters()` or `getBytes()` instead. The implementation is inefficient and can not distinguish byte and character based sources. Cite: `org/graalvm/polyglot/Source.html#getInputStream()`
### getLength()
`public int getLength()`. Since 19.0. Gets the number of characters or bytes of the source. Cite: `org/graalvm/polyglot/Source.html#getLength()`
### getCharacters()
`public CharSequence getCharacters()`. Since 19.0. Returns all characters of the source. Throws: `UnsupportedOperationException` (unchecked): if this source cannot contain `characters`. Cite: `org/graalvm/polyglot/Source.html#getCharacters()`
### getCharacters(int)
`public CharSequence getCharacters(int lineNumber)`. Since 19.0. Gets the text (not including a possible terminating newline) in a (1-based) numbered line. Causes the contents of this source to be loaded if they are loaded lazily. Throws: `UnsupportedOperationException` (unchecked): if this source cannot contain `characters`. See also: `hasCharacters()`. Cite: `org/graalvm/polyglot/Source.html#getCharacters(int)`
### getMimeType()
`public String getMimeType()`. Since 19.0. Returns the MIME type that is associated with this source. Sources have a `null` MIME type by default. If the MIME type is `null` then the `default MIME type` of the language will be used to interpret the source. If set explicitly then the language needs to `support` the MIME type in order to `evaluate` the source. If not `null` the MIME type is already verified containing no spaces and a '/' between group and sub-group. An example for a valid MIME type is: `text/javascript`. The MIME type can be guessed by the system based on `files` or `urls`. Returns `String`: MIME type of this source or `null`, if not explicitly set. See also: `Language.getDefaultMimeType()`, `Language.getMimeTypes()`, `Source.findMimeType(File)`, `Source.findMimeType(URL)`. Cite: `org/graalvm/polyglot/Source.html#getMimeType()`
### getBytes()
`public ByteSequence getBytes()`. Since 19.0. Returns the bytes of the source if it is a `byte based source`. Throws: `UnsupportedOperationException` (unchecked): if this source cannot contain `bytes` . See also: `hasBytes()`. Cite: `org/graalvm/polyglot/Source.html#getBytes()`
### hasCharacters()
`public boolean hasCharacters()`. Since 19.0. Returns `true` if this source represents a character based source, else `false`. A source is either a byte based, a character based, or with no content, but never both byte and character based at the same time. The following methods are only supported if `hasCharacters()` is `true`: `getReader()`; `getCharacters()`; `getLineCount()`; `getLineNumber(int)`; `getColumnNumber(int)`; `getLineStartOffset(int)`; `getLineLength(int)`. Cite: `org/graalvm/polyglot/Source.html#hasCharacters()`
### hasBytes()
`public boolean hasBytes()`. Since 19.0. Returns `true` if this source represents a byte based source, else `false`. A source is either a byte based, a character based, or with no content, but never both byte and character based at the same time. The method `getBytes()` is only supported if this method returns `true`. See also: `getBytes()`. Cite: `org/graalvm/polyglot/Source.html#hasBytes()`
### getLineCount()
`public int getLineCount()`. Since 19.0. The number of text lines of a character based source, including empty lines; characters at the end of the source without a terminating newline count as a line. Causes the contents of this source to be loaded if they are loaded lazily. Throws: `UnsupportedOperationException` (unchecked): if this source cannot contain `characters`. Cite: `org/graalvm/polyglot/Source.html#getLineCount()`
### getLineNumber(int)
`public int getLineNumber(int offset) throws IllegalArgumentException`. Since 19.0. Given a 0-based character offset, return the 1-based number of the line that includes the position. Causes the contents of this source to be loaded if they are loaded lazily. Throws: `UnsupportedOperationException` (unchecked): if this source cannot contain `characters`. `IllegalArgumentException`: if the offset is outside the text contents. Cite: `org/graalvm/polyglot/Source.html#getLineNumber(int)`
### getColumnNumber(int)
`public int getColumnNumber(int offset) throws IllegalArgumentException`. Since 19.0. Given a 0-based character offset, return the 1-based number of the column at the position. Causes the contents of this source to be loaded if they are loaded lazily. Throws: `UnsupportedOperationException` (unchecked): if this source cannot contain `characters`. `IllegalArgumentException`: if the offset is outside the text contents. Cite: `org/graalvm/polyglot/Source.html#getColumnNumber(int)`
### getLineStartOffset(int)
`public int getLineStartOffset(int lineNumber) throws IllegalArgumentException`. Since 19.0. Given a 1-based line number, return the 0-based offset of the first character in the line. Throws: `UnsupportedOperationException` (unchecked): if this source cannot contain `characters`. `IllegalArgumentException`: if there is no such line in the text. Cite: `org/graalvm/polyglot/Source.html#getLineStartOffset(int)`
### getLineLength(int)
`public int getLineLength(int lineNumber) throws IllegalArgumentException`. Since 19.0. The number of characters (not counting a possible terminating newline) in a (1-based) numbered line. Causes the contents of this source to be loaded if they are loaded lazily. Throws: `UnsupportedOperationException` (unchecked): if this source cannot contain `characters`. `IllegalArgumentException`: if there is no such line in the text. Cite: `org/graalvm/polyglot/Source.html#getLineLength(int)`
### toString()
`public String toString()`. Since 19.0. Overrides `toString()`. Cite: `org/graalvm/polyglot/Source.html#toString()`
### hashCode()
`public int hashCode()`. Since 19.0. Overrides `hashCode()`. Cite: `org/graalvm/polyglot/Source.html#hashCode()`
### equals(Object)
`public boolean equals(Object obj)`. Since 19.0. Overrides `equals(java.lang.Object)`. Cite: `org/graalvm/polyglot/Source.html#equals(java.lang.Object)`
### newBuilder(String, CharSequence, String)
`public static Source.Builder newBuilder(String language, CharSequence characters, String name)`. Since 19.0. Creates a new character based literal source from a character sequence. The given characters must not mutate after they were accessed for the first time. Use this method for sources that do originate from a literal. For file or URL sources use the appropriate builder constructor and `Builder.content(CharSequence)`. Example usage: Parameters: `language` `String`: the language id, must not be `null`. `characters` `CharSequence`: the character sequence or string, must not be `null`. `name` `String`: the name of the source, if `null` then `"Unnamed"` will be used as name. Cite: `org/graalvm/polyglot/Source.html#newBuilder(java.lang.String,java.lang.CharSequence,java.lang.String)`
```java
Source source = Source.newBuilder("js", "function() {\n" + " return 'Hi';\n" + "}\n", "hi.js").buildLiteral();
assert "hi.js".equals(source.getName());
```
### newBuilder(String, ByteSequence, String)
`public static Source.Builder newBuilder(String language, ByteSequence bytes, String name)`. Since 19.0. Creates a new byte based literal source from a byte sequence. The given bytes must not mutate after they were accessed for the first time. Use this method for sources that do originate from a literal. For file or URL sources use the appropriate builder constructor and `Builder.content(CharSequence)`. Example usage: Parameters: `language` `String`: the language id, must not be `null`. `bytes` `ByteSequence`: the byte sequence or string, must not be `null`. `name` `String`: the name of the source, if `null` then `"Unnamed"` will be used as name. Cite: `org/graalvm/polyglot/Source.html#newBuilder(java.lang.String,org.graalvm.polyglot.io.ByteSequence,java.lang.String)`
```java
```
### newBuilder(String, File)
`public static Source.Builder newBuilder(String language, File file)`. Since 19.0. Creates a new file based source builder from a given file. A file based source is either interpreted as `binary` or `character` source depending on the `default MIME type` of the language, the `contents` or the specified `MIME type`. A language may be detected from an existing file using `findLanguage(File)`. Parameters: `language` `String`: the language id, must not be `null`. `file` `File`: the file to use, must not be `null`. Cite: `org/graalvm/polyglot/Source.html#newBuilder(java.lang.String,java.io.File)`
```java
File file = new File(dir, name);
assert name.endsWith(".java") : "Imagine proper file";
String language = Source.findLanguage(file);
Source source = Source.newBuilder(language, file).build();
assert file.getName().equals(source.getName());
assert file.getPath().equals(source.getPath());
assert file.toURI().equals(source.getURI());
```
### newBuilder(String, URL)
`public static Source.Builder newBuilder(String language, URL url)`. Since 19.0. Creates a new URL based source builder from a given URL. A URL based source is either interpreted as `binary` or `character` source depending on the `default MIME type` of the language, the `contents` or the specified `MIME type`. A language may be detected from an existing file using `findLanguage(URL)`. Example usage: Parameters: `language` `String`: the language id, must not be `null`. `url` `URL`: the URL to use and load, must not be `null`. Cite: `org/graalvm/polyglot/Source.html#newBuilder(java.lang.String,java.net.URL)`
```java
URL resource = relativeClass.getResource("sample.js");
Source source = Source.newBuilder("js", resource).build();
assert resource.toExternalForm().equals(source.getPath());
assert "sample.js".equals(source.getName());
assert resource.toURI().equals(source.getURI());
```
### newBuilder(String, Reader, String)
`public static Source.Builder newBuilder(String language, Reader source, String name)`. Since 19.0. Creates new character based literal source from a reader. Use this method for sources that do originate from a literal. For file or URL sources use the appropriate builder constructor and `Builder.content(CharSequence)`. See also: `Source`. Cite: `org/graalvm/polyglot/Source.html#newBuilder(java.lang.String,java.io.Reader,java.lang.String)`
```java
Reader stream = new InputStreamReader(
relativeClass.getResourceAsStream("sample.js"));
Source source = Source.newBuilder("js", stream, "sample.js").build();
assert "sample.js".equals(source.getName());
```
### create(String, CharSequence)
`public static Source create(String language, CharSequence source)`. Since 19.0. Shortcut for creating a source object from a language and char sequence. The given characters must not mutate after they were accessed for the first time. Use for sources that do not come from a file, or URL. If they do, use the appropriate builder and `Builder.content(CharSequence)`. Cite: `org/graalvm/polyglot/Source.html#create(java.lang.String,java.lang.CharSequence)`
### findLanguage(File)
`public static String findLanguage(File file) throws IOException`. Since 19.0. Returns the id of the first language that supports evaluating the probed mime type of a given [`file`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/File.html). This method is a shortcut for: ` `` String mimeType = Source.findMimeType(file); return mimeType != null ? Source.findLanguage(mimeType) : null; `` `. Parameters: `file` `File`: the file to find the first language for. Throws: `IOException`: if an error opening the file occurred. See also: `findMimeType(URL)`, `findLanguage(String)`. Cite: `org/graalvm/polyglot/Source.html#findLanguage(java.io.File)`
### findLanguage(URL)
`public static String findLanguage(URL url) throws IOException`. Since 19.0. Returns the id of the first language that supports evaluating the probed mime type of a given [`URL`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/net/URL.html). This method is a shortcut for: ` `` String mimeType = Source.findMimeType(url); return mimeType != null ? Source.findLanguage(mimeType) : null; `` `. Parameters: `url` `URL`: the url to find the first language for. Throws: `IOException`: if an error opening the url occurred. See also: `findMimeType(URL)`, `findLanguage(String)`. Cite: `org/graalvm/polyglot/Source.html#findLanguage(java.net.URL)`
### findLanguage(String)
`public static String findLanguage(String mimeType)`. Since 19.0. Returns the first installed language that supports evaluating sources for a given MIME type. Returns `null` if no language was found that supports a given MIME type. The languages are queried in the same order as returned by `Engine.getLanguages()`. Mime-types don't adhere to the MIME type format will return `null`. Cite: `org/graalvm/polyglot/Source.html#findLanguage(java.lang.String)`
### findMimeType(File)
`public static String findMimeType(File file) throws IOException`. Since 19.0. Returns the probed MIME type for a given file, or `null` if no MIME type could be resolved. Typically the MIME type is identified using the file extension and/or using its contents. Probing the MIME type of an [`File`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/File.html) may require to opening the file. Throws: `IOException`: if an error opening the file occurred. See also: `findLanguage(File)`. Cite: `org/graalvm/polyglot/Source.html#findMimeType(java.io.File)`
### findMimeType(URL)
`public static String findMimeType(URL url) throws IOException`. Since 19.0. Returns the probed MIME type for a given url, or `null` if no MIME type could be resolved. Typically the MIME type is identified using the file extension, connection meta-data and/or using it contents. Returns `null` if the language of the given file could not be detected. Probing the language of a URL may require to open a new URL connection. Throws: `IOException`: if an error opening the url occurred. See also: `findLanguage(URL)`. Cite: `org/graalvm/polyglot/Source.html#findMimeType(java.net.URL)`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ Source.Builder
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0. Nested in [`Source`](org/graalvm/polyglot/Source.md).
```java
public class Source.Builder
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `Builder`
Represents a builder to build [`Source`](org/graalvm/polyglot/Source.md) objects.
To load a source from disk one can use:
```java
File file = new File(dir, name);
assert name.endsWith(".java") : "Imagine proper file";
String language = Source.findLanguage(file);
Source source = Source.newBuilder(language, file).build();
assert file.getName().equals(source.getName());
assert file.getPath().equals(source.getPath());
assert file.toURI().equals(source.getURI());
```
To load source from a [`URL`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/net/URL.html) one can use:
```java
URL resource = relativeClass.getResource("sample.js");
Source source = Source.newBuilder("js", resource).build();
assert resource.toExternalForm().equals(source.getPath());
assert "sample.js".equals(source.getName());
assert resource.toURI().equals(source.getURI());
```
To create a source representing characters:
```java
Source source = Source.newBuilder("js", "function() {\n" + " return 'Hi';\n" + "}\n", "hi.js").buildLiteral();
assert "hi.js".equals(source.getName());
```
or read a source from a [`Reader`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/Reader.html):
```java
Reader stream = new InputStreamReader(
relativeClass.getResourceAsStream("sample.js"));
Source source = Source.newBuilder("js", stream, "sample.js").build();
assert "sample.js".equals(source.getName());
```
To create a source representing bytes:
```java
byte[] bytes = new byte[]{ /* Binary */ };
Source source = Source.newBuilder("llvm",
ByteSequence.create(bytes),
"").buildLiteral();
```
Once your builder is configured, call [`build()`](org/graalvm/polyglot/Source.Builder.md#build%28%29) to perform the loading and construction of new [`Source`](org/graalvm/polyglot/Source.md).
## Methods
### name(String)
`public Source.Builder name(String newName)`. Since 19.0. Specifies a name to the `to-be-built` `Source`. Parameters: `newName` `String`: name that replaces the previously given one. If set to `null` then `"Unnamed"` will be used. Returns `Source.Builder`: instance of `this` builder. Cite: `org/graalvm/polyglot/Source.Builder.html#name(java.lang.String)`
### content(String)
`public Source.Builder content(String code)`. Since 19.0. Specifies content of `to-be-built` `Source`. Using this method one can ignore the real content of a file or URL and use already read one, or completely different one. Example: Parameters: `code` `String`: the code to be available via `Source.getCharacters()`. Returns `Source.Builder`: instance of this builder. Cite: `org/graalvm/polyglot/Source.Builder.html#content(java.lang.String)`
```java
URL resource = relativeClass.getResource("sample.js");
Source source = Source.newBuilder("js", resource).content("{}").buildLiteral();
assert resource.toExternalForm().equals(source.getPath());
assert "sample.js".equals(source.getName());
assert resource.toExternalForm().equals(source.getURI().toString());
assert "{}".equals(source.getCharacters());
```
### content(CharSequence)
`public Source.Builder content(CharSequence characters)`. Since 19.0. Specifies character based content of `to-be-built` `Source`. Using this method one can ignore the real content of a file or URL and use already read one, or completely different one. The given characters must not mutate after they were accessed for the first time. Example: Parameters: `characters` `CharSequence`: the code to be available via `Source.getCharacters()`. Returns `Source.Builder`: instance of this builder - which's `build()` method no longer throws an [`IOException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html). Cite: `org/graalvm/polyglot/Source.Builder.html#content(java.lang.CharSequence)`
```java
URL resource = relativeClass.getResource("sample.js");
Source source = Source.newBuilder("js", resource).content("{}").buildLiteral();
assert resource.toExternalForm().equals(source.getPath());
assert "sample.js".equals(source.getName());
assert resource.toExternalForm().equals(source.getURI().toString());
assert "{}".equals(source.getCharacters());
```
### content(ByteSequence)
`public Source.Builder content(ByteSequence bytes)`. Since 19.0. Specifies byte based content of `to-be-built` `Source`. Using this method one can ignore the real content of a file or URL and use already read one, or completely different one. The given bytes must not mutate after they were accessed for the first time. Example: Parameters: `bytes` `ByteSequence`: the code to be available via `Source.getBytes()`. Returns `Source.Builder`: instance of this builder - which's `build()` method no longer throws an [`IOException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html). See also: `content(String)`. Cite: `org/graalvm/polyglot/Source.Builder.html#content(org.graalvm.polyglot.io.ByteSequence)`
```java
URL resource = relativeClass.getResource("sample.js");
Source source = Source.newBuilder("js", resource).content("{}").buildLiteral();
assert resource.toExternalForm().equals(source.getPath());
assert "sample.js".equals(source.getName());
assert resource.toExternalForm().equals(source.getURI().toString());
assert "{}".equals(source.getCharacters());
```
### mimeType(String)
`public Source.Builder mimeType(String mimeType)`. Since 19.0. Explicitly assigns a `MIME type` to the `to-be-built` `Source`. If the MIME type is `null` then the `default MIME type` of the language will be used to interpret the source. If set explicitly then the language needs to `support` the MIME type in order to `evaluate` the source. If not `null` the MIME type is already verified containing no spaces and a '/' between group and sub-group. An example for a valid MIME type is: `text/javascript`. The MIME type can be guessed by the system based on `files` or `urls`. If a source is `binary` based then the MIME type must also be a binary based MIME type. All MIME types starting with 'text/' will be interpreted as character based MIME types. Parameters: `mimeType` `String`: the new mime type to be assigned, or `null` if default MIME type should be used. Returns `Source.Builder`: instance of `this` builder ready to `create new source`. See also: `Language.getDefaultMimeType()`, `Language.getMimeTypes()`, `Source.findMimeType(File)`, `Source.findMimeType(URL)`. Cite: `org/graalvm/polyglot/Source.Builder.html#mimeType(java.lang.String)`
### interactive(boolean)
`public Source.Builder interactive(boolean interactive)`. Since 19.0. Marks the source as interactive. `Evaluation` of interactive sources by an `interactive language` can use the `Context` output streams to print the result and read an input. However, non-interactive languages are expected to ignore the interactive property of sources and not use the polyglot engine streams. Any desired printing of the evaluated result provided by a non-interactive language needs to be handled by the caller. Calling of this method influences the result of `Source.isInteractive()`. Returns `Source.Builder`: the instance of this builder. Cite: `org/graalvm/polyglot/Source.Builder.html#interactive(boolean)`
### internal(boolean)
`public Source.Builder internal(boolean internal)`. Since 19.0. Set whether this source has been marked as *internal*, meaning that it has been provided by the infrastructure, language implementation, or system library. *Internal* sources are presumed to be irrelevant to guest language programmers, as well as possibly confusing and revealing of language implementation details. On the other hand, tools should be free to make *internal* sources visible in (possibly privileged) modes that are useful for language implementors. Returns `Source.Builder`: the instance of this builder. Cite: `org/graalvm/polyglot/Source.Builder.html#internal(boolean)`
### cached(boolean)
`public Source.Builder cached(boolean cached)`. Since 19.0. Enables or disables code caching for this source. By default code caching is enabled. If `true` then the source does not require parsing every time this source is `evaluated`. If `false` then the source requires parsing every time the source is evaluated but does not remember any state. Disabling caching may be useful if the source is known to only be evaluated once. If a source instance is no longer referenced by the client then all code caches will be freed automatically. Also, if the underlying context or engine is no longer referenced then cached code for evaluated sources will be freed automatically. Returns `Source.Builder`: instance of `this` builder ready to `create new source`. Cite: `org/graalvm/polyglot/Source.Builder.html#cached(boolean)`
### uri(URI)
`public Source.Builder uri(URI newUri)`. Since 19.0. Assigns new [`URI`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/net/URI.html) to the `to-be-created` `Source`. Each source provides `Source.getURI()` as a persistent identification of its location. A default value for the method is deduced from the location or content, but one can change it by using this method. Parameters: `newUri` `URI`: the URL to use instead of default one, cannot be `null`. Returns `Source.Builder`: the instance of this builder. Cite: `org/graalvm/polyglot/Source.Builder.html#uri(java.net.URI)`
### encoding(Charset)
`public Source.Builder encoding(Charset encoding)`. Since 19.0. Assigns an encoding used to read the file content. If the encoding is `null` then the file contained encoding information is used. If the file doesn't provide an encoding information the default `UTF-8` encoding is used. Parameters: `encoding` `Charset`: the new file encoding to be used for reading the content. Returns `Source.Builder`: instance of `this` builder ready to `create new source`. Cite: `org/graalvm/polyglot/Source.Builder.html#encoding(java.nio.charset.Charset)`
### option(String, String)
`public Source.Builder option(String key, String value)`. Since 25.0. Sets a source option key and value for the built source. Source options allow you to attach language- or instrument-specific configuration to a source. These options are parsed and validated only when `Context.eval(Source)` or `Context.parse(Source)` is invoked, rather than when the source is created. If the source is validated, all source options will be validated. Therefore, each language or instrument associated with a source option must be installed. Source options of any language or instrument can be supplied to all sources. Some source options may only have an effect when provided to sources of the language with the same id. The available source option keys can be found in the respective language or instrument documentation, or at runtime via `Language.getSourceOptions()` or `Instrument.getSourceOptions()`. Parameters: `key` `String`: the option key (must not be null). `value` `String`: the option value (must not be null). See also: `Context.eval(Source)`, `Context.parse(Source)`, `Language.getSourceOptions()`, `Instrument.getSourceOptions()`. Cite: `org/graalvm/polyglot/Source.Builder.html#option(java.lang.String,java.lang.String)`
### options(Map)
`public Source.Builder options(Map options)`. Since 25.0. Shortcut for setting multiple `options` using a map. All values of the provided map must be non-null. Cite: `org/graalvm/polyglot/Source.Builder.html#options(java.util.Map)`
### toString()
`public String toString()`. Since 25.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/Source.Builder.html#toString()`
### build()
`public Source build() throws IOException`. Since 19.0. Uses configuration of this builder to create new `Source` object. The method throws an [`IOException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html) if an error loading the source occurred. Returns `Source`: the source object. Cite: `org/graalvm/polyglot/Source.Builder.html#build()`
### buildLiteral()
`public Source buildLiteral()`. Since 19.0. Uses configuration of this builder to create a new `Source` object. This method suppresses any [`IOException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html) as [`AssertionError`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AssertionError.html) and should only be used if the builder was created using `or Source#newBuilder(String, ByteSequence, String) byte sequence literal`. Returns `Source`: the source object. Cite: `org/graalvm/polyglot/Source.Builder.html#buildLiteral()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ SourceSection
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0.
```java
public final class SourceSection
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `SourceSection`
Description of contiguous section of text within a [`Source`](org/graalvm/polyglot/Source.md) of program code.; supports multiple modes of access to the text and its location. Two available source sections are considered equal if their sources, start and length are equal. [`Unavailable`](org/graalvm/polyglot/SourceSection.md#isAvailable%28%29) source sections are compared by identity. Source sections are designed to be used as keys in hash maps.
## Methods
### isAvailable()
`public boolean isAvailable()`. Since 19.0. Returns whether this is a special instance that signifies that source information is available. Available source sections are never equal to unavailable source sections. Unavailable source sections return the same indices and lengths as empty source sections starting at character index `0`. Cite: `org/graalvm/polyglot/SourceSection.html#isAvailable()`
### hasLines()
`public boolean hasLines()`. Since 19.0. Returns `true` if this section has a line number information, `false` otherwise. When `true`, `getStartLine()` and `getEndLine()` return valid line numbers, when `false`, `getStartLine()` and `getEndLine()` return `1`. Cite: `org/graalvm/polyglot/SourceSection.html#hasLines()`
### hasColumns()
`public boolean hasColumns()`. Since 19.0. Returns `true` if this section has a column number information, `false` otherwise. When `true`, `hasLines()` is `true` as well, `getStartColumn()` and `getEndColumn()` return valid column numbers. When `false`, `getStartColumn()` and `getEndColumn()` return `1`. Cite: `org/graalvm/polyglot/SourceSection.html#hasColumns()`
### hasCharIndex()
`public boolean hasCharIndex()`. Since 19.0. Returns `true` if this section has a character index information, `false` otherwise. When `true`, `getCharIndex()`, `getCharEndIndex()` and `getCharLength()` return valid character indices, when `false`, `getCharIndex()`, `getCharEndIndex()` and `getCharLength()` return `0`. Cite: `org/graalvm/polyglot/SourceSection.html#hasCharIndex()`
### getSource()
`public Source getSource()`. Since 19.0. Representation of the source program that contains this section. Returns `Source`: the source object. Cite: `org/graalvm/polyglot/SourceSection.html#getSource()`
### getStartLine()
`public int getStartLine()`. Since 19.0. Returns 1-based line number of the first character in this section (inclusive). Returns `1` for out of bounds or `unavailable` source sections, or source sections not `having lines`. Returns `int`: the starting line number. See also: `hasLines()`. Cite: `org/graalvm/polyglot/SourceSection.html#getStartLine()`
### getStartColumn()
`public int getStartColumn()`. Since 19.0. Returns the 1-based column number of the first character in this section (inclusive). Returns `1` for out of bounds or `unavailable` source sections, or source sections not `having columns`. Returns `int`: the starting column number. See also: `hasColumns()`. Cite: `org/graalvm/polyglot/SourceSection.html#getStartColumn()`
### getEndLine()
`public int getEndLine()`. Since 19.0. Returns 1-based line number of the last character in this section (inclusive). Returns `1` for out of bounds or `unavailable` source sections, or source sections not `having lines`. Returns `int`: the starting line number. See also: `hasLines()`. Cite: `org/graalvm/polyglot/SourceSection.html#getEndLine()`
### getEndColumn()
`public int getEndColumn()`. Since 19.0. Returns the 1-based column number of the last character in this section (inclusive). Returns `1` for out of bounds or `unavailable` source sections, or source sections not `having columns`. Returns `int`: the starting column number. See also: `hasColumns()`. Cite: `org/graalvm/polyglot/SourceSection.html#getEndColumn()`
### getCharIndex()
`public int getCharIndex()`. Since 19.0. Returns the 0-based index of the first character in this section. Returns `0` for `unavailable` source sections, or sections not `having character index`. The returned index might be out of bounds of the source code if assertions (-ea) are not enabled. Returns `int`: the starting character index. See also: `hasCharIndex()`. Cite: `org/graalvm/polyglot/SourceSection.html#getCharIndex()`
### getCharLength()
`public int getCharLength()`. Since 19.0. Returns the length of this section in characters. Returns `0` for `unavailable` source sections, or sections not `having character index`. The returned length might be out of bounds of the source code if assertions (-ea) are not enabled. Returns `int`: the number of characters in the section. See also: `hasCharIndex()`. Cite: `org/graalvm/polyglot/SourceSection.html#getCharLength()`
### getCharEndIndex()
`public int getCharEndIndex()`. Since 19.0. Returns the index of the text position immediately following the last character in the section. Returns `0` for `unavailable` source sections, or sections not `having character index`. The returned index might be out of bounds of the source code if assertions (-ea) are not enabled. Returns `int`: the end position of the section. See also: `hasCharIndex()`. Cite: `org/graalvm/polyglot/SourceSection.html#getCharEndIndex()`
### getCode()
`@Deprecated(since = "19.0") public CharSequence getCode()`. Since 19.0. Deprecated since 19.0. use `getCharacters()` instead. Cite: `org/graalvm/polyglot/SourceSection.html#getCode()`
### getCharacters()
`public CharSequence getCharacters()`. Since 19.0. Returns the source code fragment described by this section. Returns an empty string for out of bounds or `unavailable` source sections. Returns `CharSequence`: the code as a string. Cite: `org/graalvm/polyglot/SourceSection.html#getCharacters()`
### toString()
`public String toString()`. Since 19.0. Returns an implementation-defined string representation of this source section to be used for debugging purposes only. Overrides `toString()`. See also: `getCharacters()`. Cite: `org/graalvm/polyglot/SourceSection.html#toString()`
### hashCode()
`public int hashCode()`. Since 19.0 or earlier. Overrides `hashCode()`. Cite: `org/graalvm/polyglot/SourceSection.html#hashCode()`
### equals(Object)
`public boolean equals(Object obj)`. Since 19.0 or earlier. Overrides `equals(java.lang.Object)`. Cite: `org/graalvm/polyglot/SourceSection.html#equals(java.lang.Object)`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ TypeLiteral
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Abstract class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0.
```java
public abstract class TypeLiteral
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `TypeLiteral`
Represents a generic type `T`. Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval of the type information even at runtime.
For example, to create a type literal for `List`, you can create an empty anonymous inner class:
`TypeLiteral> list = new TypeLiteral>() {};`
**See also**
- [`org.graalvm.polyglot.Value.as(TypeLiteral)`](org/graalvm/polyglot/Value.md#as%28org.graalvm.polyglot.TypeLiteral%29)
## Constructors
### TypeLiteral()
`protected TypeLiteral()`. Since 19.0. Constructs a new type literal. Derives represented class from type parameter. Clients create an empty anonymous subclass. Doing so embeds the type parameter in the anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure. Cite: `org/graalvm/polyglot/TypeLiteral.html#()`
## Methods
### getType()
`public final Type getType()`. Since 19.0. Returns the type literal including generic type information. Cite: `org/graalvm/polyglot/TypeLiteral.html#getType()`
### getRawType()
`public final Class getRawType()`. Since 19.0. Returns the raw class type of the literal. Cite: `org/graalvm/polyglot/TypeLiteral.html#getRawType()`
### equals(Object)
`public final boolean equals(Object obj)`. Since 19.0. Overrides `equals(java.lang.Object)`. Cite: `org/graalvm/polyglot/TypeLiteral.html#equals(java.lang.Object)`
### hashCode()
`public final int hashCode()`. Since 19.0. Overrides `hashCode()`. Cite: `org/graalvm/polyglot/TypeLiteral.html#hashCode()`
### toString()
`public final String toString()`. Since 19.0. Overrides `toString()`. Cite: `org/graalvm/polyglot/TypeLiteral.html#toString()`
## Inherited members
- From class [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html): [`clone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#clone%28%29), [`finalize`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#finalize%28%29), [`getClass`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29), [`notify`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notify%28%29), [`notifyAll`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#notifyAll%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long%29), [`wait`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#wait%28long,int%29)
# ◆ Value
[polyglot](index.md) › [org.graalvm.polyglot](org/graalvm/polyglot/index.md) · Every page: [llms.txt](llms.txt)
Class in [`org.graalvm.polyglot`](org/graalvm/polyglot/index.md). Since 19.0.
```java
public final class Value extends AbstractValue
```
Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `AbstractValue` > `Value`
Represents a polyglot value that can be accessed using a set of language agnostic operations. Polyglot values represent values from [`host`](org/graalvm/polyglot/Value.md#isHostObject%28%29) or guest language. Polyglot values are bound to a [`context`](org/graalvm/polyglot/Context.md). If the context is closed then all value operations throw an [`IllegalStateException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html).
Polyglot values have one of the following type combinations:
- [`Null`](org/graalvm/polyglot/Value.md#isNull%28%29): This value represents a `null` like value. Certain languages might use a different name or use multiple values to represent `null` like values.
- [`Number`](org/graalvm/polyglot/Value.md#isNumber%28%29): This value represents a floating or fixed point number. The number value may be accessed as [`byte`](org/graalvm/polyglot/Value.md#asByte%28%29), [`short`](org/graalvm/polyglot/Value.md#asShort%28%29), [`int`](org/graalvm/polyglot/Value.md#asInt%28%29), [`long`](org/graalvm/polyglot/Value.md#asLong%28%29), [`asBigInteger()`](org/graalvm/polyglot/Value.md#asBigInteger%28%29) BigInteger}, [`float`](org/graalvm/polyglot/Value.md#asFloat%28%29), or [`double`](org/graalvm/polyglot/Value.md#asDouble%28%29) value.
- [`Boolean`](org/graalvm/polyglot/Value.md#isBoolean%28%29). This value represents a boolean value. The boolean value can be accessed using [`asBoolean()`](org/graalvm/polyglot/Value.md#asBoolean%28%29).
- [`String`](org/graalvm/polyglot/Value.md#isString%28%29): This value represents a string value. The string value can be accessed using [`asString()`](org/graalvm/polyglot/Value.md#asString%28%29).
- [`Date`](org/graalvm/polyglot/Value.md#isDate%28%29), [`Time`](org/graalvm/polyglot/Value.md#isTime%28%29) or [`Timezone`](org/graalvm/polyglot/Value.md#isTimeZone%28%29): This value represents a date, time or timezone. Multiple types may return `true` at the same time.
- [`Duration`](org/graalvm/polyglot/Value.md#isDuration%28%29): This value represents a duration value. The duration value can be accessed using [`asDuration()`](org/graalvm/polyglot/Value.md#asDuration%28%29).
- [`Host Object`](org/graalvm/polyglot/Value.md#isHostObject%28%29): This value represents a value of the host language (Java). The original Java value can be accessed using [`asHostObject()`](org/graalvm/polyglot/Value.md#asHostObject%28%29).
- [`Proxy Object`](org/graalvm/polyglot/Value.md#isProxyObject%28%29): This value represents a [`proxy`](org/graalvm/polyglot/proxy/Proxy.md) value.
- [`Native Pointer`](org/graalvm/polyglot/Value.md#isNativePointer%28%29): This value represents a native pointer. The native pointer value can be accessed using [`asNativePointer()`](org/graalvm/polyglot/Value.md#asNativePointer%28%29).
- [`Exception`](org/graalvm/polyglot/Value.md#isException%28%29): This value represents an exception object. The exception can be thrown using [`throwException()`](org/graalvm/polyglot/Value.md#throwException%28%29).
- [`Meta-Object`](org/graalvm/polyglot/Value.md#isMetaObject%28%29): This value represents a metaobject. Access metaobject operations using [`getMetaSimpleName()`](org/graalvm/polyglot/Value.md#getMetaSimpleName%28%29), [`getMetaQualifiedName()`](org/graalvm/polyglot/Value.md#getMetaQualifiedName%28%29) and [`isMetaInstance(Object)`](org/graalvm/polyglot/Value.md#isMetaInstance%28java.lang.Object%29).
- [`Iterator`](org/graalvm/polyglot/Value.md#isIterator%28%29): This value represents an iterator. The iterator can be iterated using [`hasIteratorNextElement()`](org/graalvm/polyglot/Value.md#hasIteratorNextElement%28%29) and [`getIteratorNextElement()`](org/graalvm/polyglot/Value.md#getIteratorNextElement%28%29).
In addition any value may have one or more of the following traits:
- [`Array Elements`](org/graalvm/polyglot/Value.md#hasArrayElements%28%29): This value may contain array elements. The array indices always start with `0`, also if the language uses a different style.
- [`Members`](org/graalvm/polyglot/Value.md#hasMembers%28%29): This value may contain members. Members are structural elements of an object. For example, the members of a Java object are all public methods and fields. Members are accessible using [`getMember(String)`](org/graalvm/polyglot/Value.md#getMember%28java.lang.String%29).
- [`Executable`](org/graalvm/polyglot/Value.md#canExecute%28%29): This value can be [`executed`](org/graalvm/polyglot/Value.md#execute%28java.lang.Object...%29). This indicates that the value represents an element that can be executed. Guest language examples for executable elements are functions, methods, closures or promises.
- [`Instantiable`](org/graalvm/polyglot/Value.md#canInstantiate%28%29): This value can be [`instantiated`](org/graalvm/polyglot/Value.md#newInstance%28java.lang.Object...%29). For example, Java classes are instantiable.
- [`Buffer Elements`](org/graalvm/polyglot/Value.md#hasBufferElements%28%29): This value may contain buffer elements. The buffer indices always start with `0`, also if the language uses a different style.
- [`Iterable`](org/graalvm/polyglot/Value.md#hasIterator%28%29): This value [`provides`](org/graalvm/polyglot/Value.md#getIterator%28%29) an [`iterator`](org/graalvm/polyglot/Value.md#isIterator%28%29) which can be used to [`iterate`](org/graalvm/polyglot/Value.md#getIteratorNextElement%28%29) value elements. For example, Guest language arrays are iterable.
- [`hasHashEntries()`](org/graalvm/polyglot/Value.md#hasHashEntries%28%29) Hash Entries}: This value represents a map.
- [`hasMetaParents()`](org/graalvm/polyglot/Value.md#hasMetaParents%28%29) Meta Parents}: This value represents Array Elements of Meta Objects.
In addition to the language agnostic types, the language specific type can be accessed using [`getMetaObject()`](org/graalvm/polyglot/Value.md#getMetaObject%28%29). The identity of value objects is unspecified and should not be relied upon. For example, multiple calls to [`getArrayElement(long)`](org/graalvm/polyglot/Value.md#getArrayElement%28long%29) with the same index might return the same or different instances of [`Value`](org/graalvm/polyglot/Value.md). The [`equality`](org/graalvm/polyglot/Value.md#equals%28java.lang.Object%29) of values is based on the identity of the value instance. All values return a human-readable [`string`](org/graalvm/polyglot/Value.md#toString%28%29) for debugging, formatted by the original language.
Polyglot values may be converted to host objects using [`as(Class)`](org/graalvm/polyglot/Value.md#as%28java.lang.Class%29). In addition values may be created from Java values using [`Context.asValue(Object)`](org/graalvm/polyglot/Context.md#asValue%28java.lang.Object%29).
### Naive and aware dates and times
If a date or time value has a [`timezone`](org/graalvm/polyglot/Value.md#isTimeZone%28%29) then it is called *aware*, otherwise *naive*.
An aware time and date has sufficient knowledge of applicable algorithmic and political time adjustments, such as time zone and daylight saving time information, to locate itself relative to other aware objects. An aware object is used to represent a specific moment in time that is not open to interpretation.
A naive time and date does not contain enough information to unambiguously locate itself relative to other date/time objects. Whether a naive object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it is up to the program whether a particular number represents metres, miles, or mass. Naive objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.
### Scoped Values
In the case of a guest-to-host callback, a value may be passed as a parameter. These values may represent objects that are only valid during the invocation of the callback function, i.e. they are scoped, with the scope being the callback function. If enabled via the corresponding settings in [`HostAccess`](org/graalvm/polyglot/HostAccess.md), such values are released when the function returns, with all future invocations of value operations throwing an exception. If an embedder wishes to extend the scope of the value beyond the callback's return, the value can be [pinned](org/graalvm/polyglot/Value.md#pin%28%29), such that it is not released automatically.
**See also**
- [`Context`](org/graalvm/polyglot/Context.md)
- [`Engine`](org/graalvm/polyglot/Engine.md)
- [`PolyglotException`](org/graalvm/polyglot/PolyglotException.md)
## Nested types
- [`Value.StringEncoding`](org/graalvm/polyglot/Value.StringEncoding.md) (class): Enum like class representing the supported string encodings.
## Methods
### getMetaObject()
`public Value getMetaObject()`. Since 19.0 revised in 20.1. Returns the metaobject that is associated with this value or `null` if no metaobject is available. The metaobject represents a description of the object, reveals it's kind and it's features. Some information that a metaobject might define includes the base object's type, interface, class, methods, attributes, etc. The returned value returns `true` for `isMetaObject()` and provides implementations for `getMetaSimpleName()`, `getMetaQualifiedName()`, and `isMetaInstance(Object)`. This method does not cause any observable side-effects. Throws: `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. See also: `isMetaObject()`. Cite: `org/graalvm/polyglot/Value.html#getMetaObject()`
### isMetaObject()
`public boolean isMetaObject()`. Since 20.1. Returns `true` if the value represents a metaobject. Metaobjects may be values that naturally occur in a language or they may be returned by `getMetaObject()`. A metaobject represents a description of the object, reveals its kind and its features. Returns `false` by default. Metaobjects are often also `instantiable`, but not necessarily. **Sample interpretations:** In Java an instance of the type [`Class`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Class.html) is a metaobject. In JavaScript any function instance is a metaobject. For example, the metaobject of a JavaScript class is the associated constructor function. This method does not cause any observable side-effects. If this method is implemented then also `getMetaQualifiedName()`, `getMetaSimpleName()` and `isMetaInstance(Object)` must be implemented as well. Throws: `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. See also: `getMetaQualifiedName()`, `getMetaSimpleName()`, `isMetaInstance(Object)`, `getMetaObject()`. Cite: `org/graalvm/polyglot/Value.html#isMetaObject()`
### getMetaQualifiedName()
`public String getMetaQualifiedName()`. Since 20.1. Returns the qualified name of a metaobject as `String`. **Sample interpretations:** The qualified name of a Java class includes the package name and its class name. JavaScript does not have the notion of qualified name and therefore returns the `simple name` instead. Throws: `UnsupportedOperationException` (unchecked): if and only if `isMetaObject()` returns `false` for the same value. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#getMetaQualifiedName()`
### getMetaSimpleName()
`public String getMetaSimpleName()`. Since 20.1. Returns the simple name of a metaobject as `string`. **Sample interpretations:** The simple name of a Java class is the class name. Throws: `UnsupportedOperationException` (unchecked): if and only if `isMetaObject()` returns `false` for the same value. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#getMetaSimpleName()`
### isMetaInstance(Object)
`public boolean isMetaInstance(Object instance)`. Since 20.1. Returns `true` if the given instance is an instance of this value, else `false`. The instance value is subject to polyglot value mapping rules as described in `Context.asValue(Object)`. **Sample interpretations:** A Java object is an instance of its returned [`class`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#getClass%28%29). Parameters: `instance` `Object`: the instance object to check. Throws: `UnsupportedOperationException` (unchecked): if and only if `isMetaObject()` returns `false` for the same value. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#isMetaInstance(java.lang.Object)`
### hasMetaParents()
`public boolean hasMetaParents()`. Since 22.2. Returns `true` if the value represents a metaobject and the metaobject has meta parents. Returns `false` by default. **Sample interpretations:** In Java an instance of the type [`Class`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Class.html) is a metaobject. Further, the superclass and the implemented interfaces types of that type constitute the meta parents. In JavaScript any function instance is a metaobject. For example, the metaobject of a JavaScript class is the associated constructor function. This method does not cause any observable side-effects. If this method is implemented then also `getMetaParents()` must be implemented as well. Throws: `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. See also: `getMetaParents()`. Cite: `org/graalvm/polyglot/Value.html#hasMetaParents()`
### getMetaParents()
`public Value getMetaParents()`. Since 22.2. Returns the meta parents of a meta object as an array object `hasArrayElements()`. This method does not cause any observable side-effects. If this method is implemented then also `hasMetaParents()` must be implemented as well. Throws: `IllegalStateException` (unchecked): if the context is already closed. `UnsupportedOperationException` (unchecked): if the value does not have any `hasMetaParents()` meta parents. `PolyglotException` (unchecked): if a guest language error occurred during execution. See also: `hasMetaParents()`. Cite: `org/graalvm/polyglot/Value.html#getMetaParents()`
### hasArrayElements()
`public boolean hasArrayElements()`. Since 19.0. Returns `true` if this polyglot value has array elements. In this case array elements can be accessed using `getArrayElement(long)`, `setArrayElement(long, Object)`, `removeArrayElement(long)` and the array size can be queried using `getArraySize()`. Throws: `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#hasArrayElements()`
### getArrayElement(long)
`public Value getArrayElement(long index)`. Since 19.0. Returns the array element of a given index. Polyglot arrays start with index `0`, independent of the guest language. The given array index must be greater or equal to 0. Throws: `ArrayIndexOutOfBoundsException` (unchecked): if the array index does not exist. `UnsupportedOperationException` (unchecked): if the value does not have any `array elements` or if the index exists but is not readable. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#getArrayElement(long)`
### setArrayElement(long, Object)
`public void setArrayElement(long index, Object value)`. Since 19.0. Sets the value at a given index. Polyglot arrays start with index `0`, independent of the guest language. The array element value is subject to polyglot value mapping rules as described in `Context.asValue(Object)`. Throws: `ArrayIndexOutOfBoundsException` (unchecked): if the array index does not exist. `ClassCastException` (unchecked): if the provided value type is not allowed to be written. `UnsupportedOperationException` (unchecked): if the value does not have any `array elements` or if the index exists but is not modifiable. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#setArrayElement(long,java.lang.Object)`
### removeArrayElement(long)
`public boolean removeArrayElement(long index)`. Since 19.0. Removes an array element at a given index. Returns `true` if the underlying array element could be removed, otherwise `false`. Throws: `ArrayIndexOutOfBoundsException` (unchecked): if the array index does not exist. `UnsupportedOperationException` (unchecked): if the value does not have any `array elements` or if the index exists but is not removable. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#removeArrayElement(long)`
### getArraySize()
`public long getArraySize()`. Since 19.0. Returns the array size for values with array elements. Throws: `UnsupportedOperationException` (unchecked): if the value does not have any `array elements`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#getArraySize()`
### hasBufferElements()
`public boolean hasBufferElements()`. Since 21.1. Returns `true` if the receiver may have buffer elements. In this case, the buffer size can be queried using `getBufferSize()` and elements can be read using `readBufferByte(long)`, `readBufferShort(ByteOrder, long)`, `readBufferInt(ByteOrder, long)`, `readBufferLong(ByteOrder, long)`, `readBufferFloat(ByteOrder, long)` and `readBufferDouble(ByteOrder, long)`. If `isBufferWritable()` returns `true`, then buffer elements can also be written using `writeBufferByte(long, byte)`, `writeBufferShort(ByteOrder, long, short)`, `writeBufferInt(ByteOrder, long, int)`, `writeBufferLong(ByteOrder, long, long)`, `writeBufferFloat(ByteOrder, long, float)` and `writeBufferDouble(ByteOrder, long, double)`. Invoking this method does not cause any observable side-effects. Throws: `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. See also: `hasBufferElements()`. Cite: `org/graalvm/polyglot/Value.html#hasBufferElements()`
### isBufferWritable()
`public boolean isBufferWritable() throws UnsupportedOperationException`. Since 21.1. Returns true if the receiver object is a modifiable buffer. In this case, elements can be written using `writeBufferByte(long, byte)`, `writeBufferShort(ByteOrder, long, short)`, `writeBufferInt(ByteOrder, long, int)`, `writeBufferLong(ByteOrder, long, long)`, `writeBufferFloat(ByteOrder, long, float)` and `writeBufferDouble(ByteOrder, long, double)`. Invoking this method does not cause any observable side-effects. Throws: `UnsupportedOperationException`: if the value does not have `buffer elements`. Cite: `org/graalvm/polyglot/Value.html#isBufferWritable()`
### getBufferSize()
`public long getBufferSize() throws UnsupportedOperationException`. Since 21.1. Returns the buffer size in bytes for values with buffer elements. Invoking this method does not cause any observable side-effects. Throws: `UnsupportedOperationException`: if the value does not have `buffer elements`. Cite: `org/graalvm/polyglot/Value.html#getBufferSize()`
### readBufferByte(long)
`public byte readBufferByte(long byteOffset) throws UnsupportedOperationException, IndexOutOfBoundsException`. Since 21.1. Reads the byte at the given byte offset from the start of the buffer. The access is *not* guaranteed to be atomic. Therefore, this method is *not* thread-safe. Invoking this method does not cause any observable side-effects. Parameters: `byteOffset` `long`: the offset, in bytes, from the start of the buffer at which the byte will be read. Returns `byte`: the byte at the given byte offset from the start of the buffer. Throws: `IndexOutOfBoundsException`: if and only if `byteOffset < 0 || byteOffset >= ``getBufferSize()`. `UnsupportedOperationException`: if the value does not have `buffer elements`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#readBufferByte(long)`
### readBuffer(long, byte[], …)
`public void readBuffer(long byteOffset, byte[] destination, int destinationOffset, int length) throws UnsupportedOperationException, IndexOutOfBoundsException`. Since 24.0. Reads bytes from the receiver object into the specified byte array. The access is *not* guaranteed to be atomic. Therefore, this message is *not* thread-safe. Invoking this message does not cause any observable side-effects. **Example** reading into an output stream using a 4k auxiliary byte array: In case the goal is to read the whole contents into a single byte array, the easiest way is to do that through `ByteSequence`: Parameters: `byteOffset` `long`: offset in the buffer to start reading from. `destination` `byte[]`: byte array to write the read bytes into. `destinationOffset` `int`: offset in the destination array to start writing from. `length` `int`: number of bytes to read. Throws: `IndexOutOfBoundsException`: if and only if `byteOffset < 0 || length < 0 || byteOffset + length > ``getBufferSize()`` || destinationOffset < 0 || destinationOffset + length > destination.length`. `UnsupportedOperationException`: if the value does not have `buffer elements`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#readBuffer(long,byte[],int,int)`
```java
Value val = ...
assert val.hasBufferElements();
try (OutputStream out = ...) {
byte[] aux = new byte[4096];
long bufferSize = val.getBufferSize();
for (long offset = 0; offset < bufferSize; offset += aux.length) {
int bytesToRead = (int) Math.min(bufferSize - offset, aux.length);
val.readBuffer(offset, aux, 0, bytesToRead);
out.write(aux, 0, bytesToRead);
}
}
```
```java
byte[] byteArray = val.as(ByteSequence.class).toByteArray();
```
### writeBufferByte(long, byte)
`public void writeBufferByte(long byteOffset, byte value) throws UnsupportedOperationException, IndexOutOfBoundsException`. Since 21.1. Writes the given byte at the given byte offset from the start of the buffer. The access is *not* guaranteed to be atomic. Therefore, this method is *not* thread-safe. Parameters: `byteOffset` `long`: the offset, in bytes, from the start of the buffer at which the byte will be written. `value` `byte`: the byte value to be written. Throws: `IndexOutOfBoundsException`: if and only if `byteOffset < 0 || byteOffset >= ``getBufferSize()`. `UnsupportedOperationException`: if the value does not have `buffer elements` or is not `modifiable`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#writeBufferByte(long,byte)`
### readBufferShort(ByteOrder, long)
`public short readBufferShort(ByteOrder order, long byteOffset) throws UnsupportedOperationException, IndexOutOfBoundsException`. Since 21.1. Reads the short at the given byte offset from the start of the buffer in the given byte order. Unaligned accesses are supported. The access is *not* guaranteed to be atomic. Therefore, this method is *not* thread-safe. Invoking this method does not cause any observable side-effects. Parameters: `order` `ByteOrder`: the order in which to read the individual bytes of the short. `byteOffset` `long`: the offset, in bytes, from the start of the buffer from which the short will be read. Returns `short`: the short at the given byte offset from the start of the buffer. Throws: `IndexOutOfBoundsException`: if and only if `byteOffset ``<`` 0 || byteOffset ``>``= ``getBufferSize()`` - 1`. `UnsupportedOperationException`: if the value does not have `buffer elements`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#readBufferShort(java.nio.ByteOrder,long)`
### writeBufferShort(ByteOrder, long, short)
`public void writeBufferShort(ByteOrder order, long byteOffset, short value) throws UnsupportedOperationException, IndexOutOfBoundsException`. Since 21.1. Writes the given short in the given byte order at the given byte offset from the start of the buffer. Unaligned accesses are supported. The access is *not* guaranteed to be atomic. Therefore, this method is *not* thread-safe. Parameters: `order` `ByteOrder`: the order in which to write the individual bytes of the short. `byteOffset` `long`: the offset, in bytes, from the start of the buffer from which the short will be written. `value` `short`: the short value to be written. Throws: `IndexOutOfBoundsException`: if and only if `byteOffset ``<`` 0 || byteOffset ``>``= ``getBufferSize()`` - 1`. `UnsupportedOperationException`: if the value does not have `buffer elements` or is not `modifiable`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#writeBufferShort(java.nio.ByteOrder,long,short)`
### readBufferInt(ByteOrder, long)
`public int readBufferInt(ByteOrder order, long byteOffset) throws UnsupportedOperationException, IndexOutOfBoundsException`. Since 21.1. Reads the int at the given byte offset from the start of the buffer in the given byte order. Unaligned accesses are supported. The access is *not* guaranteed to be atomic. Therefore, this method is *not* thread-safe. Invoking this method does not cause any observable side-effects. Parameters: `order` `ByteOrder`: the order in which to read the individual bytes of the int. `byteOffset` `long`: the offset, in bytes, from the start of the buffer from which the int will be read. Returns `int`: the int at the given byte offset from the start of the buffer. Throws: `IndexOutOfBoundsException`: if and only if `byteOffset ``<`` 0 || byteOffset ``>``= ``getBufferSize()`` - 3`. `UnsupportedOperationException`: if the value does not have `buffer elements`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#readBufferInt(java.nio.ByteOrder,long)`
### writeBufferInt(ByteOrder, long, int)
`public void writeBufferInt(ByteOrder order, long byteOffset, int value) throws UnsupportedOperationException, IndexOutOfBoundsException`. Since 21.1. Writes the given int in the given byte order at the given byte offset from the start of the buffer. Unaligned accesses are supported. The access is *not* guaranteed to be atomic. Therefore, this method is *not* thread-safe. Parameters: `order` `ByteOrder`: the order in which to write the individual bytes of the int. `byteOffset` `long`: the offset, in bytes, from the start of the buffer from which the int will be written. `value` `int`: the int value to be written. Throws: `IndexOutOfBoundsException`: if and only if `byteOffset ``<`` 0 || byteOffset ``>``= ``getBufferSize()`` - 3`. `UnsupportedOperationException`: if the value does not have `buffer elements` or is not `modifiable`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#writeBufferInt(java.nio.ByteOrder,long,int)`
### readBufferLong(ByteOrder, long)
`public long readBufferLong(ByteOrder order, long byteOffset) throws UnsupportedOperationException, IndexOutOfBoundsException`. Since 21.1. Reads the long at the given byte offset from the start of the buffer in the given byte order. Unaligned accesses are supported. The access is *not* guaranteed to be atomic. Therefore, this method is *not* thread-safe. Invoking this method does not cause any observable side-effects. Parameters: `order` `ByteOrder`: the order in which to read the individual bytes of the long. `byteOffset` `long`: the offset, in bytes, from the start of the buffer from which the int will be read. Returns `long`: the int at the given byte offset from the start of the buffer. Throws: `IndexOutOfBoundsException`: if and only if `byteOffset ``<`` 0 || byteOffset ``>``= ``getBufferSize()`` - 7`. `UnsupportedOperationException`: if the value does not have `buffer elements`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#readBufferLong(java.nio.ByteOrder,long)`
### writeBufferLong(ByteOrder, long, long)
`public void writeBufferLong(ByteOrder order, long byteOffset, long value) throws UnsupportedOperationException, IndexOutOfBoundsException`. Since 21.1. Writes the given long in the given byte order at the given byte offset from the start of the buffer. Unaligned accesses are supported. The access is *not* guaranteed to be atomic. Therefore, this method is *not* thread-safe. Parameters: `order` `ByteOrder`: the order in which to write the individual bytes of the long. `byteOffset` `long`: the offset, in bytes, from the start of the buffer from which the int will be written. `value` `long`: the int value to be written. Throws: `IndexOutOfBoundsException`: if and only if `byteOffset ``<`` 0 || byteOffset ``>``= ``getBufferSize()`` - 7`. `UnsupportedOperationException`: if the value does not have `buffer elements` or is not `modifiable`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#writeBufferLong(java.nio.ByteOrder,long,long)`
### readBufferFloat(ByteOrder, long)
`public float readBufferFloat(ByteOrder order, long byteOffset) throws UnsupportedOperationException, IndexOutOfBoundsException`. Since 21.1. Reads the float at the given byte offset from the start of the buffer in the given byte order. Unaligned accesses are supported. The access is *not* guaranteed to be atomic. Therefore, this method is *not* thread-safe. Invoking this method does not cause any observable side-effects. Parameters: `order` `ByteOrder`: the order in which to read the individual bytes of the float. `byteOffset` `long`: the offset, in bytes, from the start of the buffer from which the float will be read. Returns `float`: the float at the given byte offset from the start of the buffer. Throws: `IndexOutOfBoundsException`: if and only if `byteOffset ``<`` 0 || byteOffset ``>``= ``getBufferSize()`` - 3`. `UnsupportedOperationException`: if the value does not have `buffer elements`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#readBufferFloat(java.nio.ByteOrder,long)`
### writeBufferFloat(ByteOrder, long, float)
`public void writeBufferFloat(ByteOrder order, long byteOffset, float value) throws UnsupportedOperationException, IndexOutOfBoundsException`. Since 21.1. Writes the given float in the given byte order at the given byte offset from the start of the buffer. Unaligned accesses are supported. The access is *not* guaranteed to be atomic. Therefore, this method is *not* thread-safe. Parameters: `order` `ByteOrder`: the order in which to read the individual bytes of the float. `byteOffset` `long`: the offset, in bytes, from the start of the buffer from which the float will be written. `value` `float`: the float value to be written. Throws: `IndexOutOfBoundsException`: if and only if `byteOffset ``<`` 0 || byteOffset ``>``= ``getBufferSize()`` - 3`. `UnsupportedOperationException`: if the value does not have `buffer elements` or is not `modifiable`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#writeBufferFloat(java.nio.ByteOrder,long,float)`
### readBufferDouble(ByteOrder, long)
`public double readBufferDouble(ByteOrder order, long byteOffset) throws UnsupportedOperationException, IndexOutOfBoundsException`. Since 21.1. Reads the double at the given byte offset from the start of the buffer in the given byte order. Unaligned accesses are supported. The access is *not* guaranteed to be atomic. Therefore, this method is *not* thread-safe. Invoking this method does not cause any observable side-effects. Parameters: `order` `ByteOrder`: the order in which to write the individual bytes of the double. `byteOffset` `long`: the offset, in bytes, from the start of the buffer from which the double will be read. Returns `double`: the double at the given byte offset from the start of the buffer. Throws: `IndexOutOfBoundsException`: if and only if `byteOffset ``<`` 0 || byteOffset ``>``= ``getBufferSize()`` - 7`. `UnsupportedOperationException`: if the value does not have `buffer elements`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#readBufferDouble(java.nio.ByteOrder,long)`
### writeBufferDouble(ByteOrder, long, double)
`public void writeBufferDouble(ByteOrder order, long byteOffset, double value) throws UnsupportedOperationException, IndexOutOfBoundsException`. Since 21.1. Writes the given double in the given byte order at the given byte offset from the start of the buffer. Unaligned accesses are supported. The access is *not* guaranteed to be atomic. Therefore, this method is *not* thread-safe. Parameters: `order` `ByteOrder`: the order in which to write the individual bytes of the double. `byteOffset` `long`: the offset, in bytes, from the start of the buffer from which the double will be written. `value` `double`: the double value to be written. Throws: `IndexOutOfBoundsException`: if and only if `byteOffset ``<`` 0 || byteOffset ``>``= ``getBufferSize()`` - 7`. `UnsupportedOperationException`: if the value does not have `buffer elements` or is not `modifiable`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#writeBufferDouble(java.nio.ByteOrder,long,double)`
### hasMembers()
`public boolean hasMembers()`. Since 19.0. Returns `true` if this value generally supports containing members. To check whether a value has *no* members use `getMemberKeys()``.`[`isEmpty()`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Set.html#isEmpty%28%29) instead. If polyglot value has members, it may also support `getMember(String)`, `putMember(String, Object)` and `removeMember(String)`. Throws: `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. See also: `To check the existence of members.`, `To read members.`, `To write members.`, `To remove a member.`, `For a list of members.`. Cite: `org/graalvm/polyglot/Value.html#hasMembers()`
### hasMember(String)
`public boolean hasMember(String identifier)`. Since 19.0. Returns `true` if such a member exists for a given `identifier`. If the value has no `members` then `hasMember(String)` returns `false`. Throws: `PolyglotException` (unchecked): if a guest language error occurred during execution. `NullPointerException` (unchecked): if the identifier is null. Cite: `org/graalvm/polyglot/Value.html#hasMember(java.lang.String)`
### getMember(String)
`public Value getMember(String identifier)`. Since 19.0. Returns the member with a given `identifier` or `null` if the member does not exist. Throws: `UnsupportedOperationException` (unchecked): if the value `has no members` or the given identifier exists but is not readable. `PolyglotException` (unchecked): if a guest language error occurred during execution. `NullPointerException` (unchecked): if the identifier is null. Cite: `org/graalvm/polyglot/Value.html#getMember(java.lang.String)`
### getMemberKeys()
`public Set getMemberKeys()`. Since 19.0. Returns a set of all member keys. Calling [`Set.contains(Object)`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Set.html#contains%28java.lang.Object%29) with a string key is equivalent to calling `hasMember(String)`. Removing an element from the returned set is equivalent to calling `removeMember(String)`. Adding an element to the set is equivalent to calling putMember(key, null). If the value does not support `members` then an empty unmodifiable set is returned. If the context gets closed while the returned set is still alive, then the set will throw an [`IllegalStateException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html) if any methods except Object methods are invoked. Throws: `IllegalStateException` (unchecked): if the context is already `closed`. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#getMemberKeys()`
### putMember(String, Object)
`public void putMember(String identifier, Object value)`. Since 19.0. Sets the value of a member using an identifier. The member value is subject to polyglot value mapping rules as described in `Context.asValue(Object)`. Throws: `IllegalStateException` (unchecked): if the context is already `closed`. `UnsupportedOperationException` (unchecked): if the value does not have any `members`, the key does not exist and new members cannot be added, or the existing member is not modifiable. `IllegalArgumentException` (unchecked): if the provided value type is not allowed to be written. `PolyglotException` (unchecked): if a guest language error occurred during execution. `NullPointerException` (unchecked): if the identifier is null. Cite: `org/graalvm/polyglot/Value.html#putMember(java.lang.String,java.lang.Object)`
### removeMember(String)
`public boolean removeMember(String identifier)`. Since 19.0. Removes a single member from the object. Returns `true` if the member was successfully removed, `false` if such a member does not exist. Throws: `UnsupportedOperationException` (unchecked): if the value does not have any `members` or if the key `exists` but cannot be removed. `IllegalStateException` (unchecked): if the context is already `closed`. `PolyglotException` (unchecked): if a guest language error occurred during execution. `NullPointerException` (unchecked): if the identifier is null. Cite: `org/graalvm/polyglot/Value.html#removeMember(java.lang.String)`
### hasStaticScope()
`public boolean hasStaticScope()`. Since 25.1. Returns `true` if this value is a meta object that provides a static scope. A static scope represents the static or class level members associated with the type described by this meta object, such as static fields or methods. Throws: `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurs during execution. See also: `isMetaObject()`, `getStaticScope()`. Cite: `org/graalvm/polyglot/Value.html#hasStaticScope()`
### getStaticScope()
`public Value getStaticScope()`. Since 25.1. Returns the static scope associated with this value. This value must be a meta-object. A static scope is an object that exposes static members, members whose values or behavior are independent of any particular instance. The returned static scope can be used to access static members using `getMember(String)`, `getMemberKeys()`, or `invokeMember(String, Object...)`. The returned static scope is always expected to provide `members`, representing the static context. **Examples:** In Java, the static scope exposes static fields and methods of a class.; In Python, the static scope exposes class-level attributes and methods, effectively corresponding to the members provided by the Python metaobject. Throws: `UnsupportedOperationException` (unchecked): if and only if this value does not have a static scope. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurs during execution. See also: `hasStaticScope()`, `isMetaObject()`, `hasMembers()`. Cite: `org/graalvm/polyglot/Value.html#getStaticScope()`
### canExecute()
`public boolean canExecute()`. Since 19.0. Returns `true` if the value can be `executed`. Throws: `IllegalStateException` (unchecked): if the underlying context was closed. See also: `execute(Object...)`. Cite: `org/graalvm/polyglot/Value.html#canExecute()`
### execute(Object...)
`public Value execute(Object... arguments)`. Since 19.0. Executes this value if it `can` be executed and returns its result. If no result value is expected or needed use `executeVoid(Object...)` for better performance. All arguments are subject to polyglot value mapping rules as described in `Context.asValue(Object)`. Throws: `IllegalStateException` (unchecked): if the underlying context was closed. `IllegalArgumentException` (unchecked): if a wrong number of arguments was provided or one of the arguments was not applicable. `UnsupportedOperationException` (unchecked): if this value cannot be executed. `PolyglotException` (unchecked): if a guest language error occurred during execution. `NullPointerException` (unchecked): if the arguments array is null. See also: `executeVoid(Object...)`. Cite: `org/graalvm/polyglot/Value.html#execute(java.lang.Object...)`
### executeVoid(Object...)
`public void executeVoid(Object... arguments)`. Since 19.0. Executes this value if it `can` be executed. All arguments are subject to polyglot value mapping rules as described in `Context.asValue(Object)`. Throws: `IllegalStateException` (unchecked): if the underlying context was closed. `IllegalArgumentException` (unchecked): if a wrong number of arguments was provided or one of the arguments was not applicable. `UnsupportedOperationException` (unchecked): if this value cannot be executed. `PolyglotException` (unchecked): if a guest language error occurred during execution. `NullPointerException` (unchecked): if the arguments array is null. See also: `execute(Object...)`. Cite: `org/graalvm/polyglot/Value.html#executeVoid(java.lang.Object...)`
### canInstantiate()
`public boolean canInstantiate()`. Since 19.0. Returns `true` if the value can be instantiated. This indicates that the `newInstance(Object...)` can be used with this value. If a value is instantiable it is often also a `isMetaObject()`, but this is not a requirement. See also: `isMetaObject()`. Cite: `org/graalvm/polyglot/Value.html#canInstantiate()`
### newInstance(Object...)
`public Value newInstance(Object... arguments)`. Since 19.0. Instantiates this value if it `can` be instantiated. All arguments are subject to polyglot value mapping rules as described in `Context.asValue(Object)`. Throws: `IllegalStateException` (unchecked): if the underlying context was closed. `IllegalArgumentException` (unchecked): if a wrong number of arguments was provided or one of the arguments was not applicable. `UnsupportedOperationException` (unchecked): if this value cannot be instantiated. `PolyglotException` (unchecked): if a guest language error occurred during execution. `NullPointerException` (unchecked): if the arguments array is null. Cite: `org/graalvm/polyglot/Value.html#newInstance(java.lang.Object...)`
### canInvokeMember(String)
`public boolean canInvokeMember(String identifier)`. Since 19.0. Returns `true` if the given member exists and can be invoked. Returns `false` if the member does not exist (`hasMember(String)` returns `false`), or is not invocable. Parameters: `identifier` `String`: the member identifier. Throws: `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred. See also: `For a list of members.`, `invokeMember(String, Object...)`. Cite: `org/graalvm/polyglot/Value.html#canInvokeMember(java.lang.String)`
### invokeMember(String, Object...)
`public Value invokeMember(String identifier, Object... arguments)`. Since 19.0. Invokes the given member of this value. Unlike `execute(Object...)`, this is an object oriented execution of a member of an object. To test whether invocation is supported, call `canInvokeMember(String)`. When object oriented semantics are not supported, use `getMember(String)``.``execute(Object...)` instead. Parameters: `identifier` `String`: the member identifier to invoke. `arguments` `Object...`: the invocation arguments. Throws: `UnsupportedOperationException` (unchecked): if this member cannot be invoked. `PolyglotException` (unchecked): if a guest language error occurred during invocation. `NullPointerException` (unchecked): if the arguments array is null. See also: `canInvokeMember(String)`. Cite: `org/graalvm/polyglot/Value.html#invokeMember(java.lang.String,java.lang.Object...)`
### isString()
`public boolean isString()`. Since 19.0. Returns `true` if this value represents a string. Throws: `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#isString()`
### asString()
`public String asString()`. Since 19.0. Returns the [`String`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html) value if this value `is` a string. This method returns `null` if this value represents a `null` value. Throws: `ClassCastException` (unchecked): if this value could not be converted to string. `UnsupportedOperationException` (unchecked): if this value does not represent a string. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#asString()`
### asStringBytes(Value.StringEncoding)
`public byte[] asStringBytes(Value.StringEncoding encoding)`. Since 24.2. Returns the bytes of a given string value without converting it to a Java [`String`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html). This method retrieves the raw bytes of the string in the specified `StringEncoding`, avoiding intermediate conversions to a Java `String`. This is particularly useful for performance-sensitive scenarios where the overhead of creating a Java `String` is undesirable. If the string is not already encoded in the specified encoding, it will be re-encoded before the bytes are returned. Note that re-encoding may involve additional computational overhead depending on the size of the string and the differences between its current encoding and the target encoding. **Usage Note:** The returned byte array represents the raw data of the string in the requested encoding. Modifications to the array will not affect the underlying string value. Parameters: `encoding` `Value.StringEncoding`: the desired encoding for the string. Must not be `null`. Supported encodings are defined in `StringEncoding`. Returns `byte[]`: a byte array containing the string's raw bytes in the specified encoding. Throws: `NullPointerException` (unchecked): if `encoding` is `null`. `IllegalStateException` (unchecked): if the string value is no longer valid (e.g., the associated context has been closed). Cite: `org/graalvm/polyglot/Value.html#asStringBytes(org.graalvm.polyglot.Value.StringEncoding)`
### fitsInInt()
`public boolean fitsInInt()`. Since 19.0. Returns `true` if this value represents a `number` and the value fits in `int`, else `false`. Throws: `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. See also: `asInt()`. Cite: `org/graalvm/polyglot/Value.html#fitsInInt()`
### asInt()
`public int asInt()`. Since 19.0. Returns an `int` representation of this value if it is `number` and the value `fits`. Throws: `NullPointerException` (unchecked): if this value represents `null`. `ClassCastException` (unchecked): if this value could not be converted. `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#asInt()`
### isBoolean()
`public boolean isBoolean()`. Since 19.0. Returns `true` if this value represents a boolean value. Throws: `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. See also: `asBoolean()`. Cite: `org/graalvm/polyglot/Value.html#isBoolean()`
### asBoolean()
`public boolean asBoolean()`. Since 19.0. Returns a `boolean` representation of this value if it is `boolean`. Throws: `NullPointerException` (unchecked): if this value represents `null`. `ClassCastException` (unchecked): if this value could not be converted. `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#asBoolean()`
### isNumber()
`public boolean isNumber()`. Since 19.0. Returns `true` if this value represents a `number`, else `false`. The number value may be accessed as `byte`, `short` `int` `long`, `float` or `double` value. Throws: `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#isNumber()`
### fitsInLong()
`public boolean fitsInLong()`. Since 19.0. Returns `true` if this value represents a `number` and the value fits in `long`, else `false`. Throws: `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. See also: `asLong()`. Cite: `org/graalvm/polyglot/Value.html#fitsInLong()`
### asLong()
`public long asLong()`. Since 19.0. Returns a `long` representation of this value if it is `number` and the value `fits`. Throws: `NullPointerException` (unchecked): if this value represents `null`. `ClassCastException` (unchecked): if this value could not be converted to long. `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#asLong()`
### fitsInBigInteger()
`public boolean fitsInBigInteger()`. Since 23.0. Returns `true` if this value represents a `number` and the value fits in `BigInteger`, else `false`. Throws: `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. See also: `asBigInteger()`. Cite: `org/graalvm/polyglot/Value.html#fitsInBigInteger()`
### asBigInteger()
`public BigInteger asBigInteger()`. Since 23.0. Returns a `BigInteger` representation of this value if it is `number` and the value `fits`. Throws: `NullPointerException` (unchecked): if this value represents `null`. `ClassCastException` (unchecked): if this value could not be converted to BigInteger. `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#asBigInteger()`
### fitsInDouble()
`public boolean fitsInDouble()`. Since 19.0. Returns `true` if this value represents a `number` and the value fits in `double`, else `false`. Throws: `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. See also: `asDouble()`. Cite: `org/graalvm/polyglot/Value.html#fitsInDouble()`
### asDouble()
`public double asDouble()`. Since 19.0. Returns a `double` representation of this value if it is `number` and the value `fits`. Throws: `NullPointerException` (unchecked): if this value represents `null`. `ClassCastException` (unchecked): if this value could not be converted. `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#asDouble()`
### fitsInFloat()
`public boolean fitsInFloat()`. Since 19.0. Returns `true` if this value represents a `number` and the value fits in `float`, else `false`. Throws: `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. See also: `asFloat()`. Cite: `org/graalvm/polyglot/Value.html#fitsInFloat()`
### asFloat()
`public float asFloat()`. Since 19.0. Returns a `float` representation of this value if it is `number` and the value `fits`. Throws: `NullPointerException` (unchecked): if this value represents `null`. `ClassCastException` (unchecked): if this value could not be converted. `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#asFloat()`
### fitsInByte()
`public boolean fitsInByte()`. Since 19.0. Returns `true` if this value represents a `number` and the value fits in `byte`, else `false`. Throws: `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. See also: `asByte()`. Cite: `org/graalvm/polyglot/Value.html#fitsInByte()`
### asByte()
`public byte asByte()`. Since 19.0. Returns a `byte` representation of this value if it is `number` and the value `fits`. Throws: `NullPointerException` (unchecked): if this value represents `null`. `ClassCastException` (unchecked): if this value could not be converted. `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#asByte()`
### fitsInShort()
`public boolean fitsInShort()`. Since 19.0. Returns `true` if this value represents a `number` and the value fits in `short`, else `false`. Throws: `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. See also: `asShort()`. Cite: `org/graalvm/polyglot/Value.html#fitsInShort()`
### asShort()
`public short asShort()`. Since 19.0. Returns a `short` representation of this value if it is `number` and the value `fits`. Throws: `NullPointerException` (unchecked): if this value represents `null`. `ClassCastException` (unchecked): if this value could not be converted. `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#asShort()`
### isNull()
`public boolean isNull()`. Since 19.0. Returns `true` if this value is a `null` like. Throws: `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#isNull()`
### isNativePointer()
`public boolean isNativePointer()`. Since 19.0. Returns `true` if this value is a native pointer. The value of the pointer can be accessed using `asNativePointer()`. Throws: `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#isNativePointer()`
### asNativePointer()
`public long asNativePointer()`. Since 19.0. Returns the value of the pointer as `long` value. Throws: `ClassCastException` (unchecked): if the value is not a pointer. `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#asNativePointer()`
### isHostObject()
`public boolean isHostObject()`. Since 19.0. Returns `true` if the value originated form the host language Java. In such a case the value can be accessed using `asHostObject()`. Throws: `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#isHostObject()`
### asHostObject()
`public T asHostObject()`. Since 19.0. Returns the original Java host language object. Throws: `ClassCastException` (unchecked): if `isHostObject()` is `false`. `UnsupportedOperationException` (unchecked): if Java host language object is allocated in a foreign heap. `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#asHostObject()`
### isProxyObject()
`public boolean isProxyObject()`. Since 19.0. Returns `true` if this value represents a `Proxy`. The proxy instance can be unboxed using `asProxyObject()`. Throws: `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#isProxyObject()`
### asProxyObject()
`public T asProxyObject()`. Since 19.0. Returns the unboxed instance of the `Proxy`. Proxies are not automatically boxed to `host objects` on host language call boundaries (Java methods). Throws: `ClassCastException` (unchecked): if a value is not a proxy object. `PolyglotException` (unchecked): if a guest language error occurred during execution. `IllegalStateException` (unchecked): if the underlying context was closed. Cite: `org/graalvm/polyglot/Value.html#asProxyObject()`
### as(Class)
`public T as(Class targetType) throws ClassCastException, IllegalStateException, PolyglotException`. Since 19.0. Maps a polyglot value to a value with a given Java target type. Target type mapping The following target types are supported and interpreted in the following order: Custom `target type mappings` specified in the `HostAccess` configuration with precedence `TargetMappingPrecedence.HIGHEST` or `TargetMappingPrecedence.HIGH`. These custom target type mappings may override all the type mappings below. This allows for customization if one of the below type mappings is not suitable.; `Value``.class` is always supported and returns this instance.; If the value represents a `host object` then all classes implemented or extended by the host object can be used as target type.; [`String`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html)`.class` is supported if the value is a `string`.; [`Character`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Character.html)`.class` is supported if the value is a `string` of length one or if a number can be safely be converted to a character.; [`Number`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Number.html)`.class` is supported if the value is a `number`. [`Byte`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Byte.html), [`Short`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Short.html), [`Integer`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Integer.html), [`Long`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Long.html), [`Float`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Float.html) and [`Double`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Double.html) are allowed if they fit without conversion. If a conversion is necessary then a [`ClassCastException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/ClassCastException.html) is thrown. Primitive class literals throw a [`NullPointerException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/NullPointerException.html) if the value represents `null`.; [`Boolean`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Boolean.html)`.class` is supported if the value is a `boolean`. Primitive [`boolean.class`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Boolean.html) literal is also supported. The primitive class literal throws a [`NullPointerException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/NullPointerException.html) if the value represents `null`.; [`LocalDate`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/LocalDate.html)`.class` is supported if the value is a `date`; [`LocalTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/LocalTime.html)`.class` is supported if the value is a `time`; [`LocalDateTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/LocalDateTime.html)`.class` is supported if the value is a `date` and `time`.; [`Instant`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Instant.html)`.class` is supported if the value is an `instant`.; [`ZonedDateTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/ZonedDateTime.html)`.class` and [`OffsetDateTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/OffsetDateTime.html)`.class` are supported if the value is a `date`, `time` and `timezone`.; [`OffsetTime`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/OffsetTime.html)`.class` is supported if the value is a `time` and `timezone`.; [`ZoneId`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/ZoneId.html)`.class` is supported if the value is a `timezone`.; [`Duration`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Duration.html)`.class` is supported if the value is a `duration`.; `PolyglotException``.class` is supported if the value is an `exception object`.; Any Java type in the type hierarchy of a `host object`.; Custom `target type mappings` specified in the `HostAccess` configuration with precedence `TargetMappingPrecedence.LOW`.; [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html)`.class` is always supported. See section Object mapping rules.; [`Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html)`.class` is supported if `HostAccess.MutableTargetMapping.MEMBERS_TO_JAVA_MAP` respectively `HostAccess.MutableTargetMapping.HASH_TO_JAVA_MAP` are `allowed` and the value has `hasHashEntries()` hash entries}, `members` or `array elements`. The returned map can be safely cast to Map\