# ⬢ 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 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 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 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\. For value with `members` the key type is [`String`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html). For value with `array elements` the key type is [`Long`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Long.html). It is recommended to use `type literals` to specify the expected collection component types. With type literals the value type can be restricted, for example to `Map`. If the raw [`Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html)`.class` or an Object component type is used, then the return types of the list are subject to Object target type mapping rules recursively.; [`List`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html)`.class` is supported if `HostAccess.MutableTargetMapping.ARRAY_TO_JAVA_LIST` is `allowed` and the value has `array elements` and it has an `array size` that is smaller or equal to [`Integer.MAX_VALUE`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Integer.html#MAX_VALUE). The returned list can be safely cast to `List`. It is recommended to use `type literals` to specify the expected component type. With type literals the value type can be restricted to any supported target type, for example to `List`. If the raw [`List`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html)`.class` or an Object component type is used, then the return types of the list are recursively subject to Object target type mapping rules.; `ByteSequence``.class` is supported if the value has `buffer elements` and it has a `buffer size` that is smaller or equal to [`Integer.MAX_VALUE`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Integer.html#MAX_VALUE).; `byte[].class` is supported if the value has `buffer elements` and it has a `buffer size` that is smaller or equal to [`Integer.MAX_VALUE`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Integer.html#MAX_VALUE)` - 8`. The contents of the buffer will be copied to a new byte array with appropriate size.; Any Java array type of a supported target type. The values of the value will be eagerly coerced and copied into a new instance of the provided array type. This means that changes in returned array will not be reflected in the original value. Since conversion to a Java array might be an expensive operation it is recommended to use the \`List\` or \`Collection\` target type if possible.; [`Iterable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Iterable.html)`.class` is supported if `HostAccess.MutableTargetMapping.ITERATOR_TO_JAVA_ITERATOR` is `allowed` and the value has an `iterator`. The returned iterable can be safely cast to `Iterable`. It is recommended to use `type literals` to specify the expected component type. With type literals the value type can be restricted to any supported target type, for example to `Iterable`.; [`Iterator`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Iterator.html)`.class` is supported if `HostAccess.MutableTargetMapping.ITERATOR_TO_JAVA_ITERATOR` is `allowed` and the value is an `iterator` The returned iterator can be safely cast to `Iterator`. It is recommended to use `type literals` to specify the expected component type. With type literals the value type can be restricted to any supported target type, for example to `Iterator`. If the raw [`Iterator`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Iterator.html)`.class` or an Object component type is used, then the return types of the iterator are recursively subject to Object target type mapping rules. The returned iterator's [`next`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Iterator.html#next%28%29) method may throw a [`ConcurrentModificationException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/ConcurrentModificationException.html) when an underlying iterable has changed or [`UnsupportedOperationException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/UnsupportedOperationException.html) when the iterator's current element is not readable.; Any [`functional`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/FunctionalInterface.html) interface if `HostAccess.MutableTargetMapping.EXECUTABLE_TO_JAVA_INTERFACE` is `allowed` and the value can be `executed` or `instantiated` and the interface type is `implementable`. Note that [`FunctionalInterface`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/FunctionalInterface.html) are implementable by default in with the `explicit` host access policy. In case a value can be executed and instantiated then the returned implementation of the interface will be `executed`. The coercion to the parameter types of functional interface method is converted using the semantics of `as(Class)`. If a standard functional interface like [`Function`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/function/Function.html) is used, it is recommended to use `type literals` to specify the expected generic method parameter and return type.; Any interface if the value `has members` and the interface type is `implementable` and `HostAccess.MutableTargetMapping.MEMBERS_TO_JAVA_INTERFACE` is `allowed`. Each interface method maps to one `member` of the value. Whenever a method of the interface is executed a member with the method or field name must exist otherwise an [`UnsupportedOperationException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/UnsupportedOperationException.html) is thrown when the method is executed. If one of the parameters or the return value cannot be mapped to the target type a [`ClassCastException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/ClassCastException.html) or a [`NullPointerException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/NullPointerException.html) is thrown.; JVM only: Any abstract class with an accessible default constructor if the value `has members` and the class is `implementable`. Each interface method maps to one `member` of the value. Whenever an abstract method of the class is executed a member with the method or field name must exist otherwise an [`UnsupportedOperationException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/UnsupportedOperationException.html) is thrown when the method is executed. If one of the parameters or the return value cannot be mapped to the target type a [`ClassCastException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/ClassCastException.html) or a [`NullPointerException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/NullPointerException.html) is thrown.; Custom `target type mappings` specified in the `HostAccess` configuration with precedence `TargetMappingPrecedence.LOWEST`. A [`ClassCastException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/ClassCastException.html) is thrown for other unsupported target types. **JavaScript Usage Examples:** Object target type mapping Object target mapping is useful to map polyglot values to its closest corresponding standard JDK type. The following rules apply when `Object` is used as a target type: If the value represents `null` then `null` is returned.; If the value is a `host object` then the value is coerced to `host object value`.; If the value is a `string` then the value is coerced to [`String`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html) or [`Character`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Character.html).; If the value is a `boolean` then the value is coerced to [`Boolean`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Boolean.html).; If the value is a `number` then the value is coerced to [`Number`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Number.html). The specific sub type of the [`Number`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Number.html) is not specified. Users need to be prepared for any Number subclass including [`BigInteger`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/math/BigInteger.html) or [`BigDecimal`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/math/BigDecimal.html). It is recommended to cast to [`Number`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Number.html) and then convert to a Java primitive like with [`Number.longValue()`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Number.html#longValue%28%29).; If the value has `array elements` and it has an `array size` that is smaller or equal than [`Integer.MAX_VALUE`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Integer.html#MAX_VALUE) then the result value will implement [`List`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html). Every array element of the value maps to one list element. The size of the returned list maps to the array size of the value. The returned value may also implement [`Function`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/function/Function.html) if the value can be `executed` or `instantiated`.; If the value has `hash entries` then the result value will implement [`Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html). The [`size`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html#size%28%29) of the returned [`Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html) is equal to the `hash entries count`. The returned value may also implement [`Function`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/function/Function.html) if the value can be `executed` or `instantiated`.; If the value `has members` then the result value will implement [`Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html). If this value `has members` then all members are accessible using [`String`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html) keys. The [`size`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html#size%28%29) of the returned [`Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html) is equal to the count of all members. The returned value may also implement [`Function`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/function/Function.html) if the value can be `executed` or `instantiated`.; If the value has an `hasIterator()` iterator} then the result value will implement [`Iterable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Iterable.html). The returned value may also implement [`Function`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/function/Function.html) if the value can be `executed` or `instantiated`.; If the value is an `isIterator()` iterator} then the result value will implement [`Iterator`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Iterator.html). The returned value may also implement [`Function`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/function/Function.html) if the value can be `executed` or `instantiated`.; If the value can be `executed` or `instantiated` then the result value implements [`Function`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/function/Function.html). By default the argument of the function will be used as single argument to the function when executed. If a value of type [`Object[]`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) is provided then the function will be executed with those arguments. The returned function may also implement [`List`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html) or [`Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html) if the value has `array elements` or `members`, respectively.; Mappings to mutable target types such as [`List`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html), [`Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html), [`Iterator`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Iterator.html) and [`Iterable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Iterable.html) are only available if the corresponding mappings are enabled (see `org.graalvm.polyglot.HostAccess.Builder.allowMutableTargetMappings(org.graalvm.polyglot.HostAccess.MutableTargetMapping...)`).; If none of the above rules apply then this `Value` instance is returned. Returned `host objects`, [`String`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html), [`Number`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Number.html), [`Boolean`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Boolean.html) and `null` values have unlimited lifetime. Other values will throw an [`IllegalStateException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html) for any operation if their originating `context` was closed. If a [`Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html) element is modified, a [`List`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html) element is modified or a [`Function`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/function/Function.html) argument is provided then these values are interpreted according to the `host to polyglot value mapping rules`. **JavaScript Usage Examples:** Object Identity If polyglot values are mapped as Java primitives such as [`Boolean`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Boolean.html), `null`, [`String`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html), [`Character`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Character.html) or [`Number`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Number.html), then the identity of the polyglot value is not preserved. All other results can be converted back to a `polyglot value` using `Context.asValue(Object)`. **Mapping Example using JavaScript:** This example first creates a new JavaScript object and maps it to a [`Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html). Using the `Context.asValue(Object)` it is possible to recreate the `polyglot value` from the Java map. The JavaScript object identity is preserved in the process. Parameters: `targetType` `Class`: the target Java type to map. Throws: `ClassCastException`: if polyglot value could not be mapped to the target type. `PolyglotException`: if the conversion triggered a guest language error. `IllegalStateException`: if the underlying context is already closed. `NullPointerException` (unchecked): if the target type is null. See also: `to map to generic type signatures.`. Cite: `org/graalvm/polyglot/Value.html#as(java.lang.Class)` ```java Context context = Context.newBuilder().allowHostAccess(HostAccess.ALL).build(); assert context.eval("js", "undefined").as(Object.class) == null; assert context.eval("js", "'foobar'").as(String.class).equals("foobar"); assert context.eval("js", "42").as(Integer.class) == 42; assert context.eval("js", "({foo:'bar'})").as(Map.class).get("foo").equals("bar"); assert context.eval("js", "[42]").as(List.class).get(0).equals(42); assert Arrays.equals(context.eval("js", "([0, 1, 127])").as(byte[].class), new byte[]{0, 1, 127}); assert Arrays.equals(context.eval("js", "(new Uint8Array([0, 1, 127, 255]))").getMember("buffer").as(byte[].class), new byte[]{0, 1, 127, -1}); assert ((Map) context.eval("js", "[{foo:'bar'}]").as(List.class).get(0)).get("foo").equals("bar"); @FunctionalInterface interface IntFunction { int foo(int value); } assert context.eval("js", "(function(a){return a})").as(IntFunction.class).foo(42).asInt() == 42; @FunctionalInterface interface StringListFunction { int foo(List value); } assert context.eval("js", "(function(a){return a.length})").as(StringListFunction.class).foo(new String[]{"42"}).asInt() == 1; public abstract class AbstractClass { public AbstractClass() { } int foo(int value); } assert context.eval("js", "({foo: function(a){return a}})").as(AbstractClass.class).foo(42).asInt() == 42; ``` ```java Context context = Context.create(); assert context.eval("js", "undefined").as(Object.class) == null; assert context.eval("js", "'foobar'").as(Object.class) instanceof String; assert context.eval("js", "42").as(Object.class) instanceof Number; assert context.eval("js", "[]").as(Object.class) instanceof Map; assert context.eval("js", "{}").as(Object.class) instanceof Map; assert ((Map) context.eval("js", "[{}]").as(Object.class)).get(0) instanceof Map; assert context.eval("js", "(function(){})").as(Object.class) instanceof Function; ``` ```java Context context = Context.create(); Map javaMap = context.eval("js", "{}").as(Map.class); Value polyglotValue = context.asValue(javaMap); ``` ### as(TypeLiteral) `public T as(TypeLiteral targetType)`. Since 19.0. Maps a polyglot value to a given Java target type literal. For usage instructions see `TypeLiteral`. Usage example: Throws: `NullPointerException` (unchecked): if the target type is null. See also: `as(Class)`. Cite: `org/graalvm/polyglot/Value.html#as(org.graalvm.polyglot.TypeLiteral)` ```java static final TypeLiteral> STRING_LIST = new TypeLiteral>() { }; public static void main(String[] args) { Context context = Context.create(); List javaList = context.eval("js", "['foo', 'bar', 'bazz']").as(STRING_LIST); assert javaList.get(0).equals("foo"); } ``` ### toString() `public String toString()`. Since 19.0. Converts this value to a human readable string. Each language may have special formating conventions - even primitive values may not follow the traditional Java formating rules. The format of the returned string is intended to be interpreted by humans not machines and should therefore not be relied upon by machines. By default this value class name and its [`identity hash code`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/System.html#identityHashCode%28java.lang.Object%29) is used as string representation. Overrides `toString()`. Cite: `org/graalvm/polyglot/Value.html#toString()` ### getSourceLocation() `public SourceSection getSourceLocation()`. Since 19.0. Returns the declared source location of the value. Returns `SourceSection`: the `SourceSection` or null if unknown. Cite: `org/graalvm/polyglot/Value.html#getSourceLocation()` ### isDate() `public boolean isDate()`. Since 19.2.0. Returns `true` if this object represents a date, else `false`. If this value is also a `timezone` then the date is aware, otherwise it is naive. Throws: `ClassCastException` (unchecked): if polyglot value could not be mapped to the target type. `NullPointerException` (unchecked): if the target type is null. `PolyglotException` (unchecked): if the conversion triggered a guest language error. `IllegalStateException` (unchecked): if the underlying context is already closed. See also: `asDate()`. Cite: `org/graalvm/polyglot/Value.html#isDate()` ### asDate() `public LocalDate asDate()`. Since 19.2.0. Returns this value as date if this object represents a `date`. The returned date is either aware if the value has a `timezone` otherwise it is naive. Throws: `ClassCastException` (unchecked): if polyglot value could not be mapped to the target type. `NullPointerException` (unchecked): if the target type is null. `PolyglotException` (unchecked): if the conversion triggered a guest language error. `IllegalStateException` (unchecked): if the underlying context is already closed. See also: `isDate()`. Cite: `org/graalvm/polyglot/Value.html#asDate()` ### isTime() `public boolean isTime()`. Since 19.2.0. Returns `true` if this object represents a time, else `false`. If the value is also a `timezone` then the time is aware, otherwise it is naive. Throws: `IllegalStateException` (unchecked): if the underlying context is already closed. See also: `asTime()`. Cite: `org/graalvm/polyglot/Value.html#isTime()` ### asTime() `public LocalTime asTime()`. Since 19.2.0. Returns this value as time if this object represents a `time`. The returned time is either aware if the value has a `timezone` otherwise it is naive. Throws: `ClassCastException` (unchecked): if polyglot value could not be mapped to the target type. `NullPointerException` (unchecked): if the target type is null. `PolyglotException` (unchecked): if the conversion triggered a guest language error. `IllegalStateException` (unchecked): if the underlying context is already closed. See also: `isTime()`. Cite: `org/graalvm/polyglot/Value.html#asTime()` ### isInstant() `public boolean isInstant()`. Since 19.2.0. Returns `true` if this value represents an instant. If a value is an instant then it is also a `date`, `time` and `timezone`. This method is short-hand for: Throws: `IllegalStateException` (unchecked): if the underlying context is already closed. See also: `isDate()`, `isTime()`, `isInstant()`, `asInstant()`. Cite: `org/graalvm/polyglot/Value.html#isInstant()` ```java v.isDate() && v.isTime() && v.isTimeZone() ``` ### asInstant() `public Instant asInstant()`. Since 19.2.0. Returns this value as instant if this object represents an `instant`. If a value is an instant then it is also a `date`, `time` and `timezone`. Using this method may be more efficient than reconstructing the timestamp from the date, time and timezone data. The following assertion always holds if `isInstant()` returns `true`: Throws: `ClassCastException` (unchecked): if polyglot value could not be mapped to the target type. `NullPointerException` (unchecked): if the target type is null. `PolyglotException` (unchecked): if the conversion triggered a guest language error. `IllegalStateException` (unchecked): if the underlying context is already closed. See also: `isDate()`, `isTime()`, `isTimeZone()`. Cite: `org/graalvm/polyglot/Value.html#asInstant()` ```java ZoneId zone = getTimeZone(receiver); LocalDate date = getDate(receiver); LocalTime time = getTime(receiver); assert ZonedDateTime.of(date, time, zone).toInstant().equals(getInstant(receiver)); ``` ### isTimeZone() `public boolean isTimeZone()`. Since 19.2.0. Returns `true` if this object represents a timezone, else `false`. The interpretation of timezone objects may vary: If `isDate()` and `isTime()` return `true`, then the returned date or time information is aware of this timezone.; If `isDate()` and `isTime()` returns `false`, then it represents just timezone information. Objects with only date information must not have timezone information attached and objects with only time information must have either none, or [`fixed zone`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/zone/ZoneRules.html#isFixedOffset%28%29) only. If this rule is violated then an [`AssertionError`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AssertionError.html) is thrown if assertions are enabled. If this method is implemented then also `asTimeZone()` must be implemented. Throws: `IllegalStateException` (unchecked): if the underlying context is already closed. See also: `asTimeZone()`, `asInstant()`. Cite: `org/graalvm/polyglot/Value.html#isTimeZone()` ### asTimeZone() `public ZoneId asTimeZone()`. Since 19.2.0. Returns this value as timestamp if this object represents a `timezone`. Throws: `ClassCastException` (unchecked): if polyglot value could not be mapped to the target type. `PolyglotException` (unchecked): if the conversion triggered a guest language error. `IllegalStateException` (unchecked): if the underlying context is already closed. `NullPointerException` (unchecked): if the target type is null. See also: `isTimeZone()`. Cite: `org/graalvm/polyglot/Value.html#asTimeZone()` ### isDuration() `public boolean isDuration()`. Since 19.2.0. Returns `true` if this object represents a duration, else `false`. Throws: `IllegalStateException` (unchecked): if the underlying context is already closed. See also: [`Duration`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/time/Duration.html), `asDuration()`. Cite: `org/graalvm/polyglot/Value.html#isDuration()` ### asDuration() `public Duration asDuration()`. Since 19.2.0. Returns this value as duration if this object represents a `duration`. Throws: `ClassCastException` (unchecked): if polyglot value could not be mapped to the target type. `PolyglotException` (unchecked): if the conversion triggered a guest language error. `IllegalStateException` (unchecked): if the underlying context is already closed. `NullPointerException` (unchecked): if the target type is null. See also: `isDuration()`. Cite: `org/graalvm/polyglot/Value.html#asDuration()` ### isException() `public boolean isException()`. Since 19.3. Returns `true` if this object represents an exception, else `false`. Throws: `IllegalStateException` (unchecked): if the underlying context is already closed. See also: `throwException()`. Cite: `org/graalvm/polyglot/Value.html#isException()` ### throwException() `public RuntimeException throwException()`. Since 19.3. Throws this value if this object represents an `exception`. Throws: `UnsupportedOperationException` (unchecked): if the value is not an exception. `IllegalStateException` (unchecked): if the underlying context is already closed. See also: `isException()`. Cite: `org/graalvm/polyglot/Value.html#throwException()` ### getContext() `public Context getContext()`. Since 19.3.0. Returns the context this value was created with. The returned context may be `null` if the value was created using `Value.asValue(Object)` and no current context was `entered` at the time. 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 and that a context is not closed while it is still active. Cite: `org/graalvm/polyglot/Value.html#getContext()` ### equals(Object) `public boolean equals(Object obj)`. Since 20.1. Compares the identity of the underlying polyglot objects. This method does not do any structural comparisons. Overrides `equals(java.lang.Object)`. Cite: `org/graalvm/polyglot/Value.html#equals(java.lang.Object)` ### hashCode() `public int hashCode()`. Since 20.1. Returns the identity hash code of the underlying object. This method does not compute the hash code depending on the contents of the value. Overrides `hashCode()`. Cite: `org/graalvm/polyglot/Value.html#hashCode()` ### hasIterator() `public boolean hasIterator()`. Since 21.1. Returns `true` if this polyglot value provides an iterator. In this case the iterator can be obtained using `getIterator()`. Throws: `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. See also: `getIterator()`. Cite: `org/graalvm/polyglot/Value.html#hasIterator()` ### getIterator() `public Value getIterator()`. Since 21.1. Creates a new iterator that allows read each element of a sequence. Throws: `UnsupportedOperationException` (unchecked): if the value does not provide `iterator`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. See also: `hasIterator()`. Cite: `org/graalvm/polyglot/Value.html#getIterator()` ### isIterator() `public boolean isIterator()`. Since 21.1. Returns `true` if the value represents an iterator object. In this case the iterator elements can be accessed using `getIteratorNextElement()`. Throws: `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. See also: `hasIteratorNextElement()`, `getIteratorNextElement()`. Cite: `org/graalvm/polyglot/Value.html#isIterator()` ### hasIteratorNextElement() `public boolean hasIteratorNextElement()`. Since 21.1. Returns `true` if the value represents an iterator which has more elements, else `false`. Multiple calls to the `hasIteratorNextElement()` might lead to different results if the underlying data structure is modified. Throws: `UnsupportedOperationException` (unchecked): if the value is not an `iterator`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. See also: `isIterator()`, `getIteratorNextElement()`. Cite: `org/graalvm/polyglot/Value.html#hasIteratorNextElement()` ### getIteratorNextElement() `public Value getIteratorNextElement()`. Since 21.1. Returns the next element in the iteration. When the underlying data structure is modified the `getIteratorNextElement()` may throw the [`NoSuchElementException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/NoSuchElementException.html) despite the `hasIteratorNextElement()` returned `true`, or it may throw a language error. Throws: `UnsupportedOperationException` (unchecked): if the value is not an `iterator` or when the underlying iterable element exists but is not readable. `NoSuchElementException` (unchecked): if the iteration has no more elements. Even if the [`NoSuchElementException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/NoSuchElementException.html) was thrown it might not be thrown again by a next call of the `getIteratorNextElement()` due to a modification of an underlying iterable. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. See also: `isIterator()`, `hasIteratorNextElement()`. Cite: `org/graalvm/polyglot/Value.html#getIteratorNextElement()` ### hasHashEntries() `public boolean hasHashEntries()`. Since 21.1. Returns `true` if this polyglot value represents a map. In this case map entries can be accessed using `getHashValue(Object)`, `getHashValueOrDefault(Object, Object)`, `putHashEntry(Object, Object)`, `removeHashEntry(Object)`, `getHashEntriesIterator()` and the map size can be queried using `getHashSize()`. 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#hasHashEntries()` ### getHashSize() `public long getHashSize() throws UnsupportedOperationException`. Since 21.1. Returns the number of map entries for values with hash entries. Throws: `UnsupportedOperationException`: if the value does not have any `hasHashEntries()` hash entries}. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#getHashSize()` ### hasHashEntry(Object) `public boolean hasHashEntry(Object key)`. Since 21.1. Returns `true` if mapping for the specified key exists. If the value has no `hash entries` then `hasHashEntry(Object)` returns `false`. The key is subject to polyglot value mapping rules as described in `Context.asValue(Object)`. 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#hasHashEntry(java.lang.Object)` ### getHashValue(Object) `public Value getHashValue(Object key) throws UnsupportedOperationException`. Since 21.1. Returns the value for the specified key or `null` if the mapping for the specified key does not exist. The key is subject to polyglot value mapping rules as described in `Context.asValue(Object)`. Throws: `UnsupportedOperationException`: if the value has no `hash entries` or the mapping for given key 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#getHashValue(java.lang.Object)` ### getHashValueOrDefault(Object, Object) `public Value getHashValueOrDefault(Object key, Object defaultValue) throws UnsupportedOperationException`. Since 21.1. Returns the value for the specified key or the default value if the mapping for the specified key does not exist or is not readable. The key and the default value are subject to polyglot value mapping rules as described in `Context.asValue(Object)`. Throws: `UnsupportedOperationException`: if the value has no `hash entries` at all. `IllegalStateException` (unchecked): if the context is already `closed`. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#getHashValueOrDefault(java.lang.Object,java.lang.Object)` ### putHashEntry(Object, Object) `public void putHashEntry(Object key, Object value) throws IllegalArgumentException, UnsupportedOperationException`. Since 21.1. Associates the specified value with the specified key. Both key and value are subject to polyglot value mapping rules as described in `Context.asValue(Object)`. Throws: `UnsupportedOperationException`: if the value does not have any `hash entries`, the mapping for specified key does not exist and new members cannot be added, or the existing mapping for specified key is not modifiable. `IllegalArgumentException`: if the provided key type or value type is not allowed to be written. `IllegalStateException` (unchecked): if the context is already `closed`. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#putHashEntry(java.lang.Object,java.lang.Object)` ### removeHashEntry(Object) `public boolean removeHashEntry(Object key) throws UnsupportedOperationException`. Since 21.1. Removes the mapping for a given key. Returns `true` if the mapping was successfully removed, `false` if mapping for a given key does not exist. The key is subject to polyglot value mapping rules as described in `Context.asValue(Object)`. Throws: `UnsupportedOperationException`: if the value does not have any `hash entries` or if mapping for specified key `exists` but cannot be removed. `IllegalStateException` (unchecked): if the context is already `closed`. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#removeHashEntry(java.lang.Object)` ### getHashEntriesIterator() `public Value getHashEntriesIterator() throws UnsupportedOperationException`. Since 21.1. Creates a new hash entries iterator that allows read each map entry. The return value is always an `iterator` of `array elements`. The first array element is a key, the second array element is an associated value. Even if the value array element is `modifiable` writing to array may not update the mapping, always use `putHashEntry(Object, Object)` to update the mapping. Throws: `UnsupportedOperationException`: if the value does not have any `hash entries`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#getHashEntriesIterator()` ### getHashKeysIterator() `public Value getHashKeysIterator() throws UnsupportedOperationException`. Since 21.1. Creates a new hash keys iterator that allows read each map key. The return value is always an `iterator`. Throws: `UnsupportedOperationException`: if the value does not have any `hash entries`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#getHashKeysIterator()` ### getHashValuesIterator() `public Value getHashValuesIterator() throws UnsupportedOperationException`. Since 21.1. Creates a new hash values iterator that allows read each map value. The return value is always an `iterator`. Throws: `UnsupportedOperationException`: if the value does not have any `hash entries`. `IllegalStateException` (unchecked): if the context is already closed. `PolyglotException` (unchecked): if a guest language error occurred during execution. Cite: `org/graalvm/polyglot/Value.html#getHashValuesIterator()` ### asValue(Object) `public static Value asValue(Object o)`. Since 19.0. Converts a Java host value to a polyglot value. Returns a value for any host or guest value. If there is a context available use `Context.asValue(Object)` for efficiency instead. The value is bound the `current` context when created. If there is no context available when the value was constructed then Values constructed with this method may return `null` for `getContext()`. Parameters: `o` `Object`: the object to convert. Throws: `IllegalStateException` (unchecked): if no context is currently entered. See also: `Conversion rules.`. Cite: `org/graalvm/polyglot/Value.html#asValue(java.lang.Object)` ### pin() `public void pin()`. Since 21.3. Pins a scoped value such that it can be used beyond the scope of a scoped host method call. Pinning is an idempotent operation, i.e. pinning an already pinned value just results in a pinned value again. Trying to pin a value that is not scoped will not cause an effect. Trying to pin a scoped value that has already been released will raise a [`IllegalStateException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html). Throws: `IllegalStateException` (unchecked): if the method scope of the value was finished. See also: `HostAccess.SCOPED`. Cite: `org/graalvm/polyglot/Value.html#pin()` ### fromByteBasedString(byte[], Value.StringEncoding) `public static Value fromByteBasedString(byte[] bytes, Value.StringEncoding encoding)`. Since 24.2. Creates a byte-based string value that can be passed to polyglot languages. The returned value is guaranteed to return `true` for `Value.isString()`. The string can later be retrieved as a byte array using `Value.asStringBytes(StringEncoding)`. This method ensures immutability by conservatively copying the byte array before passing it to the underlying implementation. **Performance Note:** Copying the byte array can have a performance impact. Use this method when immutability is required, or use the more flexible overloaded method `fromByteBasedString(byte[], int, int, StringEncoding, boolean)` to control copying behavior. Parameters: `bytes` `byte[]`: the byte array representing the string. `encoding` `Value.StringEncoding`: the encoding of the byte array. Returns `Value`: a polyglot string `Value`. Throws: `NullPointerException` (unchecked): if either `bytes` or `encoding` is null. Cite: `org/graalvm/polyglot/Value.html#fromByteBasedString(byte[],org.graalvm.polyglot.Value.StringEncoding)` ### fromByteBasedString(byte[], int, …) `public static Value fromByteBasedString(byte[] bytes, int offset, int length, Value.StringEncoding encoding, boolean copy)`. Since 24.2. Creates a byte-based string value with more granular control over the byte array's usage. This method provides additional flexibility by allowing a subset of the byte array to be passed and controlling whether the byte array should be copied to ensure immutability. Parameters: `bytes` `byte[]`: the byte array representing the string. `offset` `int`: the starting offset in the byte array. `length` `int`: the number of bytes to include starting from `offset`. `encoding` `Value.StringEncoding`: the encoding of the byte array. `copy` `boolean`: whether to copy the byte array to ensure immutability. Returns `Value`: a polyglot string `Value`. Cite: `org/graalvm/polyglot/Value.html#fromByteBasedString(byte[],int,int,org.graalvm.polyglot.Value.StringEncoding,boolean)` ### fromNativeString(long, int, …) `public static Value fromNativeString(long basePointer, int byteOffset, int byteLength, Value.StringEncoding encoding, boolean copy)`. Since 24.2. Creates a native string object that can be passed to polyglot languages. Native strings avoid copying, offering better performance for certain use cases. However, clients must guarantee the lifetime of the native string as long as the `Value` is alive. The returned value is guaranteed to return `true` for `Value.isString()`. **Usage Warning:** The polyglot context or engine does not manage the lifetime of the native pointer. Clients must ensure that the pointer remains valid and that the memory is not deallocated while the string is in use. Passing a deallocated or invalid pointer can result in crashes or undefined behavior. **Note:** Whenever possible, use `fromByteBasedString(byte[], StringEncoding)` to avoid the risks associated with native memory management. The native string's memory must remain valid for the lifetime of the context it is passed to.; The native bytes must not be mutated after being passed to this method.; The bytes must already be encoded with the specified encoding. Parameters: `basePointer` `long`: the raw base pointer to the native string in memory. `byteLength` `int`: the length of the string in bytes. `encoding` `Value.StringEncoding`: the encoding of the native string. `copy` `boolean`: whether to copy the native string bytes for additional safety. Returns `Value`: a polyglot string `Value`. Cite: `org/graalvm/polyglot/Value.html#fromNativeString(long,int,int,org.graalvm.polyglot.Value.StringEncoding,boolean)` ### fromNativeString(long, int, Value.StringEncoding) `public static Value fromNativeString(long basePointer, int byteLength, Value.StringEncoding encoding)`. Since 24.2. Creates a native string object with default safety settings. This method is equivalent to calling `fromNativeString(long, int, int, StringEncoding, boolean)` with `copy` set to `true`. Parameters: `basePointer` `long`: the raw base pointer to the native string in memory. `byteLength` `int`: the length of the string in bytes. `encoding` `Value.StringEncoding`: the encoding of the native string. Returns `Value`: a polyglot string `Value`. Cite: `org/graalvm/polyglot/Value.html#fromNativeString(long,int,org.graalvm.polyglot.Value.StringEncoding)` ## 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.StringEncoding [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 24.2. Nested in [`Value`](org/graalvm/polyglot/Value.md). ```java public static final class Value.StringEncoding ``` Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `StringEncoding` Enum like class representing the supported string encodings. The encodings determine how byte arrays or native strings are interpreted when creating or retrieving string values. This class is not directly a enum to support compatible evolution. ## Fields ### UTF_8 `public static final Value.StringEncoding UTF_8`. Since 24.2. Cite: `org/graalvm/polyglot/Value.StringEncoding.html#UTF_8` ### UTF_16_LITTLE_ENDIAN `public static final Value.StringEncoding UTF_16_LITTLE_ENDIAN`. Since 24.2. Cite: `org/graalvm/polyglot/Value.StringEncoding.html#UTF_16_LITTLE_ENDIAN` ### UTF_16_BIG_ENDIAN `public static final Value.StringEncoding UTF_16_BIG_ENDIAN`. Since 24.2. Cite: `org/graalvm/polyglot/Value.StringEncoding.html#UTF_16_BIG_ENDIAN` ### UTF_32_LITTLE_ENDIAN `public static final Value.StringEncoding UTF_32_LITTLE_ENDIAN`. Since 24.2. Cite: `org/graalvm/polyglot/Value.StringEncoding.html#UTF_32_LITTLE_ENDIAN` ### UTF_32_BIG_ENDIAN `public static final Value.StringEncoding UTF_32_BIG_ENDIAN`. Since 24.2. Cite: `org/graalvm/polyglot/Value.StringEncoding.html#UTF_32_BIG_ENDIAN` ### UTF_16 `public static final Value.StringEncoding UTF_16`. Since 24.2. The native UTF 16 encoding for the current platform. See also: [`ByteOrder.nativeOrder()`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/ByteOrder.html#nativeOrder%28%29). Cite: `org/graalvm/polyglot/Value.StringEncoding.html#UTF_16` ### UTF_32 `public static final Value.StringEncoding UTF_32`. Since 24.2. The native UTF 32 encoding for the current platform. See also: [`ByteOrder.nativeOrder()`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/ByteOrder.html#nativeOrder%28%29). Cite: `org/graalvm/polyglot/Value.StringEncoding.html#UTF_32` ## 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) # ▣ org.graalvm.polyglot.io [polyglot](index.md) · Every page: [llms.txt](llms.txt) Package in polyglot. Since 19.0. Input/Output support for the GraalVM SDK polyglot API. The [`org.graalvm.polyglot.io.FileSystem`](org/graalvm/polyglot/io/FileSystem.md) allows an embedder to virtualize Input/Output operations done by the `TruffleLanguage`s. A custom filesystem is registered using an IOAccess configuration [`builder`](org/graalvm/polyglot/io/IOAccess.Builder.md#fileSystem%28org.graalvm.polyglot.io.FileSystem%29). ## Interfaces - [`ByteSequence`](org/graalvm/polyglot/io/ByteSequence.md): A ByteSequence is a readable sequence of byte values. - [`FileChannel`](org/graalvm/polyglot/io/FileChannel.md): A seekable byte channel that supports file locking and, on JDK 22 and later, mapping regions of its file into memory. - [`FileLock`](org/graalvm/polyglot/io/FileLock.md): Represents a lock on a region of a file acquired through a FileChannel. - [`FileSystem`](org/graalvm/polyglot/io/FileSystem.md): Service-provider for Truffle files. - [`MessageEndpoint`](org/graalvm/polyglot/io/MessageEndpoint.md): An endpoint representing one side of message transport. - [`MessageTransport`](org/graalvm/polyglot/io/MessageTransport.md): Allows to take over transport of message communication initiated by an instrument. - [`ProcessHandler`](org/graalvm/polyglot/io/ProcessHandler.md): Service-provider for guest languages process builder. ## Classes - [`IOAccess`](org/graalvm/polyglot/io/IOAccess.md): Represents an IO access configuration of a polyglot context. # ◇ ByteSequence [polyglot](index.md) › [org.graalvm.polyglot.io](org/graalvm/polyglot/io/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.io`](org/graalvm/polyglot/io/index.md). Since 19.0. ```java public interface ByteSequence ``` A `ByteSequence` is a readable sequence of `byte` values. This interface provides uniform, read-only access to many different kinds of `byte` sequences. This interface does not refine the general contracts of the [`equals`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#equals%28java.lang.Object%29) and [`hashCode`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html#hashCode%28%29) methods. The result of comparing two objects that implement `ByteSequence` is therefore, in general, undefined. Each object may be implemented by a different class, and there is no guarantee that each class will be capable of testing its instances for equality with those of the other. It is therefore inappropriate to use arbitrary `ByteSequence` instances as elements in a set or as keys in a map. ## Methods ### length() `int length()`. Since 19.0. Returns the length of this byte sequence. Returns `int`: the number of `byte`s in this sequence. Cite: `org/graalvm/polyglot/io/ByteSequence.html#length()` ### byteAt(int) `byte byteAt(int index)`. Since 19.0. Returns the `byte` value at the specified index. An index ranges from zero to `length() - 1`. The first `char` value of the sequence is at index zero, the next at index one, and so on, as for array indexing. Parameters: `index` `int`: the index of the `byte` value to be returned. Returns `byte`: the specified `byte` value. Throws: `IndexOutOfBoundsException` (unchecked): if the `index` argument is negative or not less than `length()`. Cite: `org/graalvm/polyglot/io/ByteSequence.html#byteAt(int)` ### subSequence(int, int) `default ByteSequence subSequence(int startIndex, int endIndex)`. Since 19.0. Returns a `ByteSequence` that is a subsequence of this sequence. The subsequence starts with the `byte` value at the specified index and ends with the `byte` value at index `end - 1`. The length (in `byte`s) of the returned sequence is `end - start`, so if `start == end` then an empty sequence is returned. Parameters: `startIndex` `int`: the start index, inclusive. `endIndex` `int`: the end index, exclusive. Returns `ByteSequence`: the specified subsequence. Throws: `IndexOutOfBoundsException` (unchecked): if `start` or `end` are negative, if `end` is greater than `length()`, or if `start` is greater than `end`. Cite: `org/graalvm/polyglot/io/ByteSequence.html#subSequence(int,int)` ### toByteArray() `default byte[] toByteArray()`. Since 19.0. Returns a `byte[]` containing the bytes in this sequence in the same order as this sequence. The length of the byte array will be the length of this sequence. Creates a new byte array with every invocation. Cite: `org/graalvm/polyglot/io/ByteSequence.html#toByteArray()` ### bytes() `default IntStream bytes()`. Since 19.0. Returns a stream of `int` zero-extending the `byte` values from this sequence. Returns `IntStream`: an IntStream of byte values from this sequence. Cite: `org/graalvm/polyglot/io/ByteSequence.html#bytes()` ### create(byte[]) `static ByteSequence create(byte[] buffer)`. Since 19.0. Creates a `ByteSequence` from an existing `byte[]`. The byte array is not defensively copied, therefore the given bytes must not mutate to ensure the contract of an immutable ByteSequence. Cite: `org/graalvm/polyglot/io/ByteSequence.html#create(byte[])` # ◇ FileChannel [polyglot](index.md) › [org.graalvm.polyglot.io](org/graalvm/polyglot/io/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.io`](org/graalvm/polyglot/io/index.md). Since 25.5. ```java public interface FileChannel extends SeekableByteChannel ``` Extends: [`SeekableByteChannel`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/channels/SeekableByteChannel.html) A seekable byte channel that supports file locking and, on JDK 22 and later, mapping regions of its file into memory. File system implementations can support locking and memory mapping by returning either a [`java.nio.channels.FileChannel`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/channels/FileChannel.html) or a [`FileChannel`](org/graalvm/polyglot/io/FileChannel.md) from [`FileSystem.newByteChannel(Path, Set, FileAttribute[])`](org/graalvm/polyglot/io/FileSystem.md#newByteChannel%28java.nio.file.Path,java.util.Set,java.nio.file.attribute.FileAttribute...%29). ## Methods ### position(long) `FileChannel position(long newPosition) throws IOException`. Since 25.5. Overrides `position(long)`. Cite: `org/graalvm/polyglot/io/FileChannel.html#position(long)` ### truncate(long) `FileChannel truncate(long size) throws IOException`. Since 25.5. Overrides `truncate(long)`. Cite: `org/graalvm/polyglot/io/FileChannel.html#truncate(long)` ### lock() `default FileLock lock() throws IOException`. Since 25.5. Acquires an exclusive lock on this channel's file, blocking until the lock is acquired, this channel is closed, or the invoking thread is interrupted. This method is equivalent to invoking `lock(0, Long.MAX_VALUE, false)`. Returns `FileLock`: a newly acquired exclusive lock. Throws: `ClosedChannelException` (unchecked): if this channel is closed. `AsynchronousCloseException` (unchecked): if another thread closes this channel while the invoking thread is blocked. `FileLockInterruptionException` (unchecked): if the invoking thread is interrupted while blocked. `OverlappingFileLockException` (unchecked): if an overlapping lock is already held by this Java virtual machine, or another thread is waiting for an overlapping lock. `NonWritableChannelException` (unchecked): if this channel was not opened for writing. `UnsupportedOperationException` (unchecked): if this channel does not support file locking. `IOException`: if another I/O error occurs. Cite: `org/graalvm/polyglot/io/FileChannel.html#lock()` ### lock(long, long, boolean) `default FileLock lock(long position, long size, boolean shared) throws IOException`. Since 25.5. Acquires a lock on a region of this channel's file, blocking until the lock is acquired, this channel is closed, or the invoking thread is interrupted. The region need not be contained within or overlap the current file contents. A requested shared lock may be converted to an exclusive lock when shared locks are not supported by the operating system. Parameters: `position` `long`: the position of the first byte in the region; must be non-negative. `size` `long`: the size of the region; must be non-negative and `position + size` must not overflow. `shared` `boolean`: `true` to request a shared lock, or `false` to request an exclusive lock. Returns `FileLock`: the newly acquired lock. Throws: `IllegalArgumentException` (unchecked): if `position` or `size` is negative or their sum overflows. `ClosedChannelException` (unchecked): if this channel is closed. `AsynchronousCloseException` (unchecked): if another thread closes this channel while the invoking thread is blocked. `FileLockInterruptionException` (unchecked): if the invoking thread is interrupted while blocked. `OverlappingFileLockException` (unchecked): if an overlapping lock is already held by this Java virtual machine, or another thread is waiting for an overlapping lock. `NonReadableChannelException` (unchecked): if a shared lock is requested and this channel was not opened for reading. `NonWritableChannelException` (unchecked): if an exclusive lock is requested and this channel was not opened for writing. `UnsupportedOperationException` (unchecked): if this channel does not support file locking. `IOException`: if another I/O error occurs. Cite: `org/graalvm/polyglot/io/FileChannel.html#lock(long,long,boolean)` ### tryLock() `default FileLock tryLock() throws IOException`. Since 25.5. Attempts to acquire an exclusive lock on this channel's file without blocking. This method is equivalent to invoking `tryLock(0, Long.MAX_VALUE, false)`. Returns `FileLock`: a newly acquired exclusive lock, or `null` if another program holds an overlapping lock. Throws: `ClosedChannelException` (unchecked): if this channel is closed. `OverlappingFileLockException` (unchecked): if an overlapping lock is already held by this Java virtual machine, or another thread is waiting for an overlapping lock. `NonWritableChannelException` (unchecked): if this channel was not opened for writing. `UnsupportedOperationException` (unchecked): if this channel does not support file locking. `IOException`: if another I/O error occurs. Cite: `org/graalvm/polyglot/io/FileChannel.html#tryLock()` ### tryLock(long, long, boolean) `default FileLock tryLock(long position, long size, boolean shared) throws IOException`. Since 25.5. Attempts to acquire a lock on a region of this channel's file without blocking. The region need not be contained within or overlap the current file contents. A requested shared lock may be converted to an exclusive lock when shared locks are not supported by the operating system. Parameters: `position` `long`: the position of the first byte in the region; must be non-negative. `size` `long`: the size of the region; must be non-negative and `position + size` must not overflow. `shared` `boolean`: `true` to request a shared lock, or `false` to request an exclusive lock. Returns `FileLock`: the newly acquired lock, or `null` if another program holds an overlapping lock. Throws: `IllegalArgumentException` (unchecked): if `position` or `size` is negative or their sum overflows. `ClosedChannelException` (unchecked): if this channel is closed. `OverlappingFileLockException` (unchecked): if an overlapping lock is already held by this Java virtual machine, or another thread is waiting for an overlapping lock. `NonReadableChannelException` (unchecked): if a shared lock is requested and this channel was not opened for reading. `NonWritableChannelException` (unchecked): if an exclusive lock is requested and this channel was not opened for writing. `UnsupportedOperationException` (unchecked): if this channel does not support file locking. `IOException`: if another I/O error occurs. Cite: `org/graalvm/polyglot/io/FileChannel.html#tryLock(long,long,boolean)` ### map(FileChannel.MapMode, long, …) `default Object map(FileChannel.MapMode mode, long offset, long size, Object arena) throws IOException`. Since 25.5. Maps a region of this channel's file into a memory segment associated with the given arena. This channel must have been opened for reading for a read-only mapping and for both reading and writing for a read/write or private mapping. Closing this channel does not invalidate the returned segment. Closing `arena` invalidates the segment and permits the mapped region to be unmapped. The arena parameter and return type are intentionally erased to [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) to avoid a static dependency on the Foreign Function and Memory API, which is not available on all JDK versions supported by this API. The `arena` argument must be a `java.lang.foreign.Arena`, and the returned object is a `java.lang.foreign.MemorySegment`. When JDK 22 or later becomes the minimum supported version, this method is expected to be deprecated and replaced by a strongly typed variant. Parameters: `mode` `FileChannel.MapMode`: the mode in which the file region is mapped. `offset` `long`: the offset within the file at which the mapped region starts; must be non-negative. `size` `long`: the size of the mapped region, in bytes; must be non-negative. `arena` `Object`: the `java.lang.foreign.Arena` associated with the returned segment. Returns `Object`: a `java.lang.foreign.MemorySegment` whose lifetime is controlled by `arena`. Throws: `IOException`: if an I/O error occurs. `NonReadableChannelException` (unchecked): if `mode` requires read access and this channel was not opened for reading. `NonWritableChannelException` (unchecked): if `mode` requires write access and this channel was not opened for writing. `UnsupportedOperationException` (unchecked): if this channel does not support memory mapping or the requested `mode`. `IllegalArgumentException` (unchecked): if `offset` or `size` is negative or their sum overflows the range of `long`. `IllegalStateException` (unchecked): if `arena` has already been closed. `ClassCastException` (unchecked): if `arena` is not a `java.lang.foreign.Arena`. `RuntimeException` (unchecked): if `arena` is confined and this method is called from a thread other than the arena's owner thread; on JDK 22 and later, the concrete exception is `java.lang.WrongThreadException`. `NullPointerException` (unchecked): if `mode` or `arena` is `null`. `SecurityException` (unchecked): if the `FileSystem` denied the operation. Cite: `org/graalvm/polyglot/io/FileChannel.html#map(java.nio.channels.FileChannel.MapMode,long,long,java.lang.Object)` ## Inherited members - From interface [`SeekableByteChannel`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/channels/SeekableByteChannel.html): [`position`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/channels/SeekableByteChannel.html#position%28%29), [`read`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/channels/SeekableByteChannel.html#read%28java.nio.ByteBuffer%29), [`size`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/channels/SeekableByteChannel.html#size%28%29), [`write`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/channels/SeekableByteChannel.html#write%28java.nio.ByteBuffer%29) - From interface [`Channel`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/channels/Channel.html): [`close`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/channels/Channel.html#close%28%29), [`isOpen`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/channels/Channel.html#isOpen%28%29) # ◇ FileLock [polyglot](index.md) › [org.graalvm.polyglot.io](org/graalvm/polyglot/io/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.io`](org/graalvm/polyglot/io/index.md). Since 25.5. ```java public interface FileLock extends AutoCloseable ``` Extends: [`AutoCloseable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AutoCloseable.html) Represents a lock on a region of a file acquired through a [`FileChannel`](org/graalvm/polyglot/io/FileChannel.md). A lock remains valid until it is released by [`close()`](org/graalvm/polyglot/io/FileLock.md#close%28%29) or its associated channel is closed, whichever occurs first. File locks are held on behalf of the entire Java virtual machine and are not suitable for coordinating access between threads in the same virtual machine. ## Methods ### acquiredBy() `FileChannel acquiredBy()`. Since 25.5. Returns the channel through which this lock was acquired. Returns `FileChannel`: the channel through which this lock was acquired. Cite: `org/graalvm/polyglot/io/FileLock.html#acquiredBy()` ### position() `long position()`. Since 25.5. Returns the position of the first byte in the locked region. The position may exceed the current size of the file. Returns `long`: the position of the first byte in the locked region. Cite: `org/graalvm/polyglot/io/FileLock.html#position()` ### size() `long size()`. Since 25.5. Returns the size of the locked region in bytes. The locked region need not be contained within or overlap the current file contents. Returns `long`: the size of the locked region in bytes. Cite: `org/graalvm/polyglot/io/FileLock.html#size()` ### isShared() `boolean isShared()`. Since 25.5. Returns whether this lock is shared. A request for a shared lock may be converted to an exclusive lock when shared locks are not supported by the operating system. Returns `boolean`: `true` if this lock is shared, or `false` if it is exclusive. Cite: `org/graalvm/polyglot/io/FileLock.html#isShared()` ### isValid() `boolean isValid()`. Since 25.5. Returns whether this lock is valid. Returns `boolean`: `true` if this lock is valid. Cite: `org/graalvm/polyglot/io/FileLock.html#isValid()` ### close() `void close() throws IOException`. Since 25.5. Releases this lock. If the lock is already invalid, invoking this method has no effect. Throws: `ClosedChannelException` (unchecked): if the channel used to acquire this lock is closed. `IOException`: if an I/O error occurs. Overrides `close()`. Cite: `org/graalvm/polyglot/io/FileLock.html#close()` # ◇ FileSystem [polyglot](index.md) › [org.graalvm.polyglot.io](org/graalvm/polyglot/io/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.io`](org/graalvm/polyglot/io/index.md). Since 19.0. ```java public interface FileSystem ``` Service-provider for `Truffle` files. ## Nested types - [`FileSystem.Selector`](org/graalvm/polyglot/io/FileSystem.Selector.md) (abstract class): A selector for determining which FileSystem should handle operations on a given Path. ## Methods ### parsePath(URI) `Path parsePath(URI uri)`. Since 19.0. Parses a path from an [`URI`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/net/URI.html). Parameters: `uri` `URI`: the [`URI`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/net/URI.html) to be converted to [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html). Returns `Path`: the [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html) representing given [`URI`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/net/URI.html). Throws: `UnsupportedOperationException` (unchecked): when [`URI`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/net/URI.html) scheme is not supported. `IllegalArgumentException` (unchecked): if preconditions on the `uri` do not hold. The format of the URI is `FileSystem` specific. Cite: `org/graalvm/polyglot/io/FileSystem.html#parsePath(java.net.URI)` ### parsePath(String) `Path parsePath(String path)`. Since 19.0. Parses a path from a [`String`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html). This method is called only on the `FileSystem` with `file` scheme. Parameters: `path` `String`: the string path to be converted to [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html). Returns `Path`: the [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html). Throws: `UnsupportedOperationException` (unchecked): when the `FileSystem` supports only [`URI`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/net/URI.html). `IllegalArgumentException` (unchecked): if the `path` string cannot be converted to a [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html). Cite: `org/graalvm/polyglot/io/FileSystem.html#parsePath(java.lang.String)` ### checkAccess(Path, Set, LinkOption...) `void checkAccess(Path path, Set modes, LinkOption... linkOptions) throws IOException`. Since 19.0. Checks existence and accessibility of a file. Parameters: `path` `Path`: the path to the file to check. `modes` `Set`: the access modes to check, possibly empty to check existence only. `linkOptions` `LinkOption...`: options determining how the symbolic links should be handled. Throws: `NoSuchFileException` (unchecked): if the file denoted by the path does not exist. `IOException`: in case of IO error. `SecurityException` (unchecked): if this `FileSystem` denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#checkAccess(java.nio.file.Path,java.util.Set,java.nio.file.LinkOption...)` ### createDirectory(Path, FileAttribute...) `void createDirectory(Path dir, FileAttribute... attrs) throws IOException`. Since 19.0. Creates a directory. Parameters: `dir` `Path`: the directory to create. `attrs` `FileAttribute...`: the optional attributes to set atomically when creating the directory. Throws: `FileAlreadyExistsException` (unchecked): if a file on given path already exists. `IOException`: in case of IO error. `UnsupportedOperationException` (unchecked): if the attributes contain an attribute which cannot be set atomically. `SecurityException` (unchecked): if this `FileSystem` denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#createDirectory(java.nio.file.Path,java.nio.file.attribute.FileAttribute...)` ### delete(Path) `void delete(Path path) throws IOException`. Since 19.0. Deletes a file. Parameters: `path` `Path`: the path to the file to delete. Throws: `NoSuchFileException` (unchecked): if a file on given path does not exist. `DirectoryNotEmptyException` (unchecked): if the path denotes a non empty directory. `IOException`: in case of IO error. `SecurityException` (unchecked): if this `FileSystem` denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#delete(java.nio.file.Path)` ### newByteChannel(Path, Set, FileAttribute...) `SeekableByteChannel newByteChannel(Path path, Set options, FileAttribute... attrs) throws IOException`. Since 19.0. Opens or creates a file returning a [`SeekableByteChannel`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/channels/SeekableByteChannel.html) to access the file content. To support file locking and, on JDK 22 and later, memory mapping, an implementation should return either a [`java.nio.channels.FileChannel`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/channels/FileChannel.html) or a `FileChannel`. Parameters: `path` `Path`: the path to the file to open. `options` `Set`: the options specifying how the file should be opened. `attrs` `FileAttribute...`: the optional attributes to set atomically when creating the new file. Returns `SeekableByteChannel`: the created [`SeekableByteChannel`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/channels/SeekableByteChannel.html). Throws: `FileAlreadyExistsException` (unchecked): if [`StandardOpenOption.CREATE_NEW`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/StandardOpenOption.html#CREATE_NEW) option is set and a file already exists on given path. `IOException`: in case of IO error. `UnsupportedOperationException` (unchecked): if the attributes contain an attribute which cannot be set atomically. `IllegalArgumentException` (unchecked): in case of invalid options combination. `SecurityException` (unchecked): if this `FileSystem` denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#newByteChannel(java.nio.file.Path,java.util.Set,java.nio.file.attribute.FileAttribute...)` ### newDirectoryStream(Path, DirectoryStream.Filter) `DirectoryStream newDirectoryStream(Path dir, DirectoryStream.Filter filter) throws IOException`. Since 19.0. Returns directory entries. Parameters: `dir` `Path`: the path to the directory to iterate entries for. `filter` `DirectoryStream.Filter`: the filter. Returns `DirectoryStream`: the new [`DirectoryStream`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/DirectoryStream.html). Throws: `NotDirectoryException` (unchecked): when given path does not denote a directory. `IOException`: in case of IO error. `SecurityException` (unchecked): if this `FileSystem` denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#newDirectoryStream(java.nio.file.Path,java.nio.file.DirectoryStream.Filter)` ### toAbsolutePath(Path) `Path toAbsolutePath(Path path)`. Since 19.0. Resolves given path to an absolute path. Parameters: `path` `Path`: the path to resolve, may be a non normalized path. Returns `Path`: an absolute [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html). Throws: `SecurityException` (unchecked): if this `FileSystem` denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#toAbsolutePath(java.nio.file.Path)` ### toRealPath(Path, LinkOption...) `Path toRealPath(Path path, LinkOption... linkOptions) throws IOException`. Since 19.0. Returns the real (canonical) path of an existing file. Parameters: `path` `Path`: the path to resolve, may be a non normalized path. `linkOptions` `LinkOption...`: options determining how the symbolic links should be handled. Returns `Path`: an absolute canonical path. Throws: `IOException`: in case of IO error. `SecurityException` (unchecked): if this `FileSystem` denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#toRealPath(java.nio.file.Path,java.nio.file.LinkOption...)` ### readAttributes(Path, String, LinkOption...) `Map readAttributes(Path path, String attributes, LinkOption... options) throws IOException`. Since 19.0. Reads a file's attributes as a bulk operation. Parameters: `path` `Path`: the path to file to read attributes for. `attributes` `String`: the attributes to read. The `attributes` parameter has the form: `[view-name:]attribute-list`. The optional `view-name` corresponds to [`FileAttributeView.name()`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/attribute/AttributeView.html#name%28%29) and determines the set of attributes, the default value is `"basic"`. The `attribute-list` is a comma separated list of attributes. If the `attribute-list` contains `'*'` then all the attributes from given view are read. `options` `LinkOption...`: the options determining how the symbolic links should be handled. Returns `Map`: the [`Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html) containing the file attributes. The map's keys are attribute names, map's values are the attribute values. The map may contain a subset of required attributes in case when the `FileSystem` does not support some of the required attributes. Throws: `UnsupportedOperationException` (unchecked): if the attribute view is not supported. At least the `"basic"` attribute view has to be supported by the file system. `IllegalArgumentException` (unchecked): is the `attribute-list` is empty or contains an unknown attribute. `IOException`: in case of IO error. `SecurityException` (unchecked): if this `FileSystem` denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#readAttributes(java.nio.file.Path,java.lang.String,java.nio.file.LinkOption...)` ### setAttribute(Path, String, …) `default void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException`. Since 19.0. Sets a file's attribute. Parameters: `path` `Path`: the path to file to set an attribute to. `attribute` `String`: the attribute to set. The `attribute` parameter has the form: `[view-name:]attribute-name`. The optional `view-name` corresponds to [`FileAttributeView.name()`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/attribute/AttributeView.html#name%28%29) and determines the set of attributes, the default value is `"basic"`. The `attribute-name` is a name of an attribute. `value` `Object`: the attribute value. `options` `LinkOption...`: the options determining how the symbolic links should be handled. Throws: `ClassCastException` (unchecked): if `value` is not of the expected type or `value` is a [`Collection`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Collection.html) containing element of a non expected type. `UnsupportedOperationException` (unchecked): if the attribute view is not supported. `IllegalArgumentException` (unchecked): is the `attribute-name` is an unknown attribute or `value` has an inappropriate value. `IOException`: in case of IO error. `SecurityException` (unchecked): if this `FileSystem` denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#setAttribute(java.nio.file.Path,java.lang.String,java.lang.Object,java.nio.file.LinkOption...)` ### copy(Path, Path, CopyOption...) `default void copy(Path source, Path target, CopyOption... options) throws IOException`. Since 19.0. Copies source file to target file. Parameters: `source` `Path`: the path to file to copy. `target` `Path`: the path to the target file. `options` `CopyOption...`: the options specifying how the copy should be performed, see [`StandardCopyOption`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/StandardCopyOption.html). Throws: `UnsupportedOperationException` (unchecked): if `options` contains unsupported option. `FileAlreadyExistsException` (unchecked): if the target path already exists and the `options` don't contain [`StandardCopyOption.REPLACE_EXISTING`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/StandardCopyOption.html#REPLACE_EXISTING) option. `DirectoryNotEmptyException` (unchecked): if the `options` contain [`StandardCopyOption.REPLACE_EXISTING`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/StandardCopyOption.html#REPLACE_EXISTING) but the `target` is a non empty directory. `IOException`: in case of IO error. `SecurityException` (unchecked): if this `FileSystem` denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#copy(java.nio.file.Path,java.nio.file.Path,java.nio.file.CopyOption...)` ### move(Path, Path, CopyOption...) `default void move(Path source, Path target, CopyOption... options) throws IOException`. Since 19.0. Moves (renames) source file to target file. Parameters: `source` `Path`: the path to file to move. `target` `Path`: the path to the target file. `options` `CopyOption...`: the options specifying how the move should be performed, see [`StandardCopyOption`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/StandardCopyOption.html). Throws: `UnsupportedOperationException` (unchecked): if `options` contains unsupported option. `FileAlreadyExistsException` (unchecked): if the target path already exists and the `options` don't contain [`StandardCopyOption.REPLACE_EXISTING`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/StandardCopyOption.html#REPLACE_EXISTING) option. `DirectoryNotEmptyException` (unchecked): if the `options` contain [`StandardCopyOption.REPLACE_EXISTING`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/StandardCopyOption.html#REPLACE_EXISTING) but the `target` is a non empty directory. `AtomicMoveNotSupportedException` (unchecked): if the `options` contain [`StandardCopyOption.ATOMIC_MOVE`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/StandardCopyOption.html#ATOMIC_MOVE) but file cannot be moved atomically. `IOException`: in case of IO error. `SecurityException` (unchecked): if this `FileSystem` denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#move(java.nio.file.Path,java.nio.file.Path,java.nio.file.CopyOption...)` ### createLink(Path, Path) `default void createLink(Path link, Path existing) throws IOException`. Since 19.0. Creates a new link for an existing file. Parameters: `link` `Path`: the path to link to create. `existing` `Path`: the path to existing file. Throws: `UnsupportedOperationException` (unchecked): if links are not supported by file system. `FileAlreadyExistsException` (unchecked): if a file on given link path already exists. `IOException`: in case of IO error. `SecurityException` (unchecked): if this `FileSystem` denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#createLink(java.nio.file.Path,java.nio.file.Path)` ### createSymbolicLink(Path, Path, FileAttribute...) `default void createSymbolicLink(Path link, Path target, FileAttribute... attrs) throws IOException`. Since 19.0. Creates a new symbolic link. Parameters: `link` `Path`: the path to symbolic link to create. `target` `Path`: the target path of the symbolic link. `attrs` `FileAttribute...`: the optional attributes to set atomically when creating the new symbolic link. Throws: `UnsupportedOperationException` (unchecked): if symbolic links are not supported by file system. `FileAlreadyExistsException` (unchecked): if a file on given link path already exists. `IOException`: in case of IO error. `SecurityException` (unchecked): if this `FileSystem` denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#createSymbolicLink(java.nio.file.Path,java.nio.file.Path,java.nio.file.attribute.FileAttribute...)` ### readSymbolicLink(Path) `default Path readSymbolicLink(Path link) throws IOException`. Since 19.0. Reads the target of the symbolic link. Parameters: `link` `Path`: the path to symbolic link to read. Returns `Path`: the [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html) representing the symbolic link target. Throws: `UnsupportedOperationException` (unchecked): if symbolic links are not supported by file system. `NotLinkException` (unchecked): if the `link` does not denote a symbolic link. `IOException`: in case of IO error. `SecurityException` (unchecked): if this `FileSystem` denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#readSymbolicLink(java.nio.file.Path)` ### setCurrentWorkingDirectory(Path) `default void setCurrentWorkingDirectory(Path currentWorkingDirectory)`. Since 19.0. Sets the current working directory. The current working directory is used to resolve non absolute paths in `FileSystem` operations. Parameters: `currentWorkingDirectory` `Path`: the new current working directory. Throws: `UnsupportedOperationException` (unchecked): if setting of the current working directory is not supported. `IllegalArgumentException` (unchecked): if the `currentWorkingDirectory` is not a valid current working directory. `SecurityException` (unchecked): if `currentWorkingDirectory` is not readable. Cite: `org/graalvm/polyglot/io/FileSystem.html#setCurrentWorkingDirectory(java.nio.file.Path)` ### getSeparator() `default String getSeparator()`. Since 19.0. Returns the name separator used to separate names in a path string. The separator is used when creating path strings by invoking the [`toString()`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html#toString%28%29) method. Returns `String`: the name separator. Cite: `org/graalvm/polyglot/io/FileSystem.html#getSeparator()` ### getPathSeparator() `default String getPathSeparator()`. Since 19.1.0. Returns the path separator used to separate filenames in a path list. On UNIX the path separator is `':'`. On Windows it's `';'`. Returns `String`: the path separator. Cite: `org/graalvm/polyglot/io/FileSystem.html#getPathSeparator()` ### getMimeType(Path) `default String getMimeType(Path path)`. Since 19.0. Returns a MIME type for given path. An optional operation for `filesystem` implementations which can provide MIME types in an efficient way. Parameters: `path` `Path`: the file to find a MIME type for. Returns `String`: the MIME type or `null` if the MIME type is not recognized or the `filesystem` does not support MIME type detection. Cite: `org/graalvm/polyglot/io/FileSystem.html#getMimeType(java.nio.file.Path)` ### getEncoding(Path) `default Charset getEncoding(Path path)`. Since 19.0. Returns an file encoding for given path. An optional operation for `filesystem` implementations which can provide file encodings in an efficient way. Parameters: `path` `Path`: the file to find an file encoding for. Returns `Charset`: the file encoding or `null` if the file encoding is not detected or the `filesystem` does not support file encoding detection. Cite: `org/graalvm/polyglot/io/FileSystem.html#getEncoding(java.nio.file.Path)` ### getTempDirectory() `default Path getTempDirectory()`. Since 19.3.0. Returns the default temporary directory. Cite: `org/graalvm/polyglot/io/FileSystem.html#getTempDirectory()` ### isSameFile(Path, Path, LinkOption...) `default boolean isSameFile(Path path1, Path path2, LinkOption... options) throws IOException`. Since 20.2.0. Tests if the given paths refer to the same physical file. The default implementation firstly converts the paths into absolute paths. If the absolute paths are equal it returns `true` without checking if the file exists. Otherwise, this method converts the paths into canonical representations and tests the canonical paths for equality. The `FileSystem` may re-implement the method with a more efficient test. When re-implemented the method must have the same security privileges as the `toAbsolutePath` and `toRealPath`. Parameters: `path1` `Path`: the path to the file. `path2` `Path`: the other path. `options` `LinkOption...`: the options determining how the symbolic links should be handled. Returns `boolean`: `true` if the given paths refer to the same physical file. Throws: `IOException`: in case of IO error. `SecurityException` (unchecked): if this `FileSystem` denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#isSameFile(java.nio.file.Path,java.nio.file.Path,java.nio.file.LinkOption...)` ### getFileStoreTotalSpace(Path) `default long getFileStoreTotalSpace(Path path) throws IOException`. Since 25.0.0. Returns the size, in bytes, of the file store that contains the given `path`. If the file store's size exceeds [`Long.MAX_VALUE`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Long.html#MAX_VALUE), `Long.MAX_VALUE` is returned. Parameters: `path` `Path`: the path whose file store size is to be determined. Returns `long`: the size of the file store in bytes. Throws: `UnsupportedOperationException` (unchecked): if the file system does not support retrieving file store information. `IOException`: if an I/O error occurs while accessing the file store. `SecurityException` (unchecked): if the `FileSystem` implementation denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#getFileStoreTotalSpace(java.nio.file.Path)` ### getFileStoreUnallocatedSpace(Path) `default long getFileStoreUnallocatedSpace(Path path) throws IOException`. Since 25.0.0. Returns the number of unallocated bytes in the file store that contains the given `path`. The returned value represents the raw free space on the storage device, regardless of access permissions or user quotas. If the number of unallocated bytes exceeds [`Long.MAX_VALUE`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Long.html#MAX_VALUE), `Long.MAX_VALUE` is returned. Note that the value may be imprecise, as it can change at any time due to external I/O operations, including those performed outside this virtual machine. Parameters: `path` `Path`: the path whose file store is to be queried. Returns `long`: the number of unallocated bytes. Throws: `UnsupportedOperationException` (unchecked): if the file system does not support retrieving file store information. `IOException`: if an I/O error occurs while accessing the file store. `SecurityException` (unchecked): if the `FileSystem` implementation denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#getFileStoreUnallocatedSpace(java.nio.file.Path)` ### getFileStoreUsableSpace(Path) `default long getFileStoreUsableSpace(Path path) throws IOException`. Since 25.0.0. Returns the number of bytes available to this Java virtual machine on the file store that contains the given `path`. Unlike `getFileStoreUnallocatedSpace(Path)`, this method accounts for operating system level restrictions, user quotas, and file system permissions, and therefore may return a smaller value. If the available space exceeds [`Long.MAX_VALUE`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Long.html#MAX_VALUE), `Long.MAX_VALUE` is returned. Note that the returned value may be imprecise, as it can change at any time due to external I/O activity, including operations performed outside this virtual machine. Parameters: `path` `Path`: the path whose file store is to be queried. Returns `long`: the number of usable bytes available to this Java virtual machine. Throws: `UnsupportedOperationException` (unchecked): if the file system does not support retrieving file store information. `IOException`: if an I/O error occurs while accessing the file store. `SecurityException` (unchecked): if the `FileSystem` implementation denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#getFileStoreUsableSpace(java.nio.file.Path)` ### getFileStoreBlockSize(Path) `default long getFileStoreBlockSize(Path path) throws IOException`. Since 25.0.0. Returns the number of bytes per block in the file store that contains the given `path`. Parameters: `path` `Path`: the path whose file store is to be queried. Returns `long`: the block size. Throws: `UnsupportedOperationException` (unchecked): if the file system does not support retrieving file store information. `IOException`: if an I/O error occurs while accessing the file store. `SecurityException` (unchecked): if the `FileSystem` implementation denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#getFileStoreBlockSize(java.nio.file.Path)` ### isFileStoreReadOnly(Path) `default boolean isFileStoreReadOnly(Path path) throws IOException`. Since 25.0.0. Determines whether the file store containing the given `path` is read-only. Note that even if the file store is not read-only, individual write operations may still be denied due to restrictions imposed by the `FileSystem` implementation, operating system level policies, user quotas, or file system permissions. Parameters: `path` `Path`: the path whose file store is to be queried. Throws: `UnsupportedOperationException` (unchecked): if the file system does not support retrieving file store information. `IOException`: if an I/O error occurs while accessing the file store. `SecurityException` (unchecked): if the `FileSystem` implementation denied the operation. Cite: `org/graalvm/polyglot/io/FileSystem.html#isFileStoreReadOnly(java.nio.file.Path)` ### newDefaultFileSystem() `static FileSystem newDefaultFileSystem()`. Since 20.2.0. Creates a `FileSystem` implementation based on the host Java NIO. The returned instance can be used as a delegate by a decorating `FileSystem`. For an untrusted code execution, access to the host filesystem should be prevented either by using `IOAccess.NONE` or an `newFileSystem(java.nio.file.FileSystem)` in-memory filesystem}. For more details on executing untrusted code, see the [Polyglot Sandboxing Security Guide](https://www.graalvm.org/dev/security-guide/polyglot-sandbox/). The following example shows a `FileSystem` logging filesystem operations. See also: `Builder.fileSystem(FileSystem)`, `org.graalvm.polyglot.Context.Builder.allowIO(IOAccess)`. Cite: `org/graalvm/polyglot/io/FileSystem.html#newDefaultFileSystem()` ```java class TracingFileSystem implements FileSystem { private static final Logger LOGGER = Logger.getLogger(TracingFileSystem.class.getName()); private final FileSystem delegate; TracingFileSystem() { this.delegate = FileSystem.newDefaultFileSystem(); } @Override public Path parsePath(String path) { return delegate.parsePath(path); } @Override public Path parsePath(URI uri) { return delegate.parsePath(uri); } @Override public SeekableByteChannel newByteChannel(Path path, Set options, FileAttribute... attrs) throws IOException { boolean success = false; try { SeekableByteChannel result = delegate.newByteChannel(path, options, attrs); success = true; return result; } finally { trace("newByteChannel", path, success); } } ... private void trace(String operation, Path path, boolean success) { LOGGER.log(Level.FINE, "The {0} request for the path {1} {2}.",new Object[] { operation, path, success ? "was successful" : "failed" }); } } ``` ### allowLanguageHomeAccess(FileSystem) `@Deprecated static FileSystem allowLanguageHomeAccess(FileSystem fileSystem)`. Since 22.2. Deprecated. Use `allowInternalResources(FileSystem)` instead to expose language homes and other internal resources through a read-only view. Decorates the given `fileSystem` by an implementation that forwards access to files in the language home to the default file system. The method is intended to be used by custom filesystem implementations with non default storage to allow guest languages to access files in the languages homes. As the returned filesystem uses a default file system to access files in the language home, the `fileSystem` has to use the same [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html) type, `separator` and `path separator` as the `default filesystem`. Throws: `IllegalArgumentException` (unchecked): when the `fileSystem` does not use the same [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html) type or has a different `separator` or `path separator` as the `default file system`. Cite: `org/graalvm/polyglot/io/FileSystem.html#allowLanguageHomeAccess(org.graalvm.polyglot.io.FileSystem)` ### allowInternalResourceAccess(FileSystem) `@Deprecated(since = "25.1") static FileSystem allowInternalResourceAccess(FileSystem fileSystem)`. Since 24.0. Deprecated since 25.1. Use `allowInternalResources(FileSystem)` instead when migrating code that only reads internal resources. The replacement exposes internal resources and language homes through a read-only view. Code that needs mutable files based on internal resources should copy the resources to an application-controlled location, for example with `Engine.copyResources(Path, String...)`, and expose that location through its configured `fileSystem`. Decorates the given `fileSystem` by an implementation that forwards access to the internal resources, including language homes, to the default file system. The method is intended to be used by custom file system implementations with non-default storage to allow guest languages to access internal resources. As the returned file system uses a default file system to access internal resources, the `fileSystem` has to use the same [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html) type, `separator` and `path separator` as the `default file system`. This method preserves the historical behavior and does not make internal resources read-only: write operations for internal resource paths are forwarded to the default file system and are subject to its permissions. Parameters: `fileSystem` `FileSystem`: the file system used to access files that are not internal resources. Throws: `IllegalArgumentException` (unchecked): when the `fileSystem` does not use the same [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html) type or has a different `separator` or `path separator` as the `default file system`. See also: `Engine.copyResources(Path, String...)`. Cite: `org/graalvm/polyglot/io/FileSystem.html#allowInternalResourceAccess(org.graalvm.polyglot.io.FileSystem)` ### allowInternalResources(FileSystem) `static FileSystem allowInternalResources(FileSystem fileSystem)`. Since 25.1. Decorates the given `fileSystem` by an implementation that forwards access to the internal resources, including language homes, to the default file system. The method is intended to be used by custom file system implementations with non-default storage to allow guest languages to access internal resources. As the returned file system uses a default file system to access internal resources, the `fileSystem` has to use the same [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html) type, `separator` and `path separator` as the `default file system`. Internal resources and language homes are exposed through a read-only view of the default file system. Write operations, such as creating, deleting, or modifying files or directories, are rejected for internal resource paths. Paths that are not internal resources continue to be handled by `fileSystem` and retain its access permissions. Parameters: `fileSystem` `FileSystem`: the file system used to access files that are not internal resources. Throws: `IllegalArgumentException` (unchecked): when the `fileSystem` does not use the same [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html) type or has a different `separator` or `path separator` as the `default file system`. See also: `Engine.copyResources(Path, String...)`. Cite: `org/graalvm/polyglot/io/FileSystem.html#allowInternalResources(org.graalvm.polyglot.io.FileSystem)` ### newReadOnlyFileSystem(FileSystem) `static FileSystem newReadOnlyFileSystem(FileSystem fileSystem)`. Since 22.2. Decorates the given `fileSystem` by an implementation that makes the passed `fileSystem` read-only by forbidding all write operations. This method can be used to make an existing file system, such as the `default filesystem`, read-only. Making the default file system read-only still exposes host files and does not make it suitable for a sandbox policy that prohibits host file access. Cite: `org/graalvm/polyglot/io/FileSystem.html#newReadOnlyFileSystem(org.graalvm.polyglot.io.FileSystem)` ### newFileSystem(FileSystem) `static FileSystem newFileSystem(FileSystem fileSystem)`. Since 23.0. Creates a `FileSystem` implementation based on the given Java NIO filesystem. The returned `FileSystem` delegates all operations to `fileSystem`'s [`provider`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/spi/FileSystemProvider.html). The returned file system has access to all resources exposed by the supplied Java NIO file system. In particular, passing [`java.nio.file.FileSystems.getDefault()`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/FileSystems.html#getDefault%28%29) exposes the host file system and is not suitable for a sandbox policy that prohibits host file access. The following example shows how to configure `Context` so that languages read files from a prepared zip file. See also: `IOAccess`. Cite: `org/graalvm/polyglot/io/FileSystem.html#newFileSystem(java.nio.file.FileSystem)` ```java Path zipFile = Paths.get("filesystem.zip"); try (java.nio.file.FileSystem nioFs = FileSystems.newFileSystem(zipFile)) { IOAccess ioAccess = IOAccess.newBuilder().fileSystem(FileSystem.newFileSystem(nioFs)).build(); try (Context ctx = Context.newBuilder().allowIO(ioAccess).build()) { Value result = ctx.eval("js", "load('scripts/app.sh'); execute()"); } } ``` ### newDenyIOFileSystem() `static FileSystem newDenyIOFileSystem()`. Since 24.2. Creates a `FileSystem` that denies all file operations except for path parsing. Any attempt to perform file operations such as reading, writing, or deletion will result in a [`SecurityException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/SecurityException.html) being thrown. Typically, this file system does not need to be explicitly installed to restrict access to host file systems. Instead, use `Context.newBuilder().allowIO(IOAccess.NONE)`. This method is intended primarily for use as a fallback file system in a `composite file system`. Cite: `org/graalvm/polyglot/io/FileSystem.html#newDenyIOFileSystem()` ### newCompositeFileSystem(FileSystem, FileSystem.Selector...) `static FileSystem newCompositeFileSystem(FileSystem fallbackFileSystem, FileSystem.Selector... delegates)`. Since 24.2. Creates a composite `FileSystem` that delegates operations to the provided `delegates`. The `FileSystem` of the first `delegate` whose `Selector.test(Path)` method accepts the path is used for the file system operation. If no `delegate` accepts the path, the `fallbackFileSystem` is used. The `fallbackFileSystem` is responsible for parsing [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html) objects. All provided file systems must use the same [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html) type, `separator`, and `path separator`. If any file system does not meet this requirement, an [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) is thrown. The composite file system maintains its own notion of the current working directory and ensures that the `setCurrentWorkingDirectory(Path)` method is not invoked on any of the delegates. When a request to set the current working directory is received, the composite file system verifies that the specified path corresponds to an existing directory by consulting either the appropriate delegate or the `fallbackFileSystem`. If an explicit current working directory has been set, the composite file system normalizes and resolves all relative paths to absolute paths prior to delegating operations. Conversely, if no explicit current working directory is set, the composite file system directly forwards the incoming path, whether relative or absolute, to the appropriate delegate. Furthermore, when an explicit current working directory is set, the composite file system does not delegate `toAbsolutePath` operations, as delegates do not maintain an independent notion of the current working directory. If the current working directory is unset, `toAbsolutePath` operations are delegated to the `fallbackFileSystem`. Operations that are independent of path context, including `getTempDirectory`, `getSeparator`, and `getPathSeparator`, are handled exclusively by the `fallbackFileSystem`. Throws: `IllegalArgumentException` (unchecked): if the file systems do not use the same [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html) type, `separator`, or `path separator`. Cite: `org/graalvm/polyglot/io/FileSystem.html#newCompositeFileSystem(org.graalvm.polyglot.io.FileSystem,org.graalvm.polyglot.io.FileSystem.Selector...)` # ◆ FileSystem.Selector [polyglot](index.md) › [org.graalvm.polyglot.io](org/graalvm/polyglot/io/index.md) · Every page: [llms.txt](llms.txt) Abstract class in [`org.graalvm.polyglot.io`](org/graalvm/polyglot/io/index.md). Since 24.2. Nested in [`FileSystem`](org/graalvm/polyglot/io/FileSystem.md). ```java public abstract class FileSystem.Selector implements Predicate ``` Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `Selector` Implements: [`Predicate`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/function/Predicate.html)`<`[`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html)`>` A selector for determining which [`FileSystem`](org/graalvm/polyglot/io/FileSystem.md) should handle operations on a given [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html). This class encapsulates a [`FileSystem`](org/graalvm/polyglot/io/FileSystem.md) and defines a condition for selecting it. ## Constructors ### Selector(FileSystem) `protected Selector(FileSystem fileSystem)`. Since 24.2. Creates a `Selector` for the specified `FileSystem`. Cite: `org/graalvm/polyglot/io/FileSystem.Selector.html#(org.graalvm.polyglot.io.FileSystem)` ## Methods ### getFileSystem() `public final FileSystem getFileSystem()`. Since 24.2. Returns the `FileSystem` associated with this selector. Cite: `org/graalvm/polyglot/io/FileSystem.Selector.html#getFileSystem()` ### test(Path) `public abstract boolean test(Path path)`. Since 24.2. Tests whether the `FileSystem` associated with this selector can handle operations on the specified [`Path`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Path.html). Parameters: `path` `Path`: the path to test, provided as a normalized absolute path. The given `path` has no path components equal to `"."` or `".."`. Returns `boolean`: `true` if the associated `FileSystem` can handle the `path`; `false` otherwise. Overrides `test(T)`. Cite: `org/graalvm/polyglot/io/FileSystem.Selector.html#test(java.nio.file.Path)` ### of(FileSystem, Predicate) `public static FileSystem.Selector of(FileSystem fileSystem, Predicate predicate)`. Since 24.2. Creates a `Selector` for the specified `FileSystem` using the provided [`Predicate`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/function/Predicate.html). Parameters: `fileSystem` `FileSystem`: the `FileSystem` to associate with the selector. `predicate` `Predicate`: the condition to determine if the `FileSystem` can handle a given path. Returns `FileSystem.Selector`: a new `Selector` that delegates path testing to the `predicate`. Cite: `org/graalvm/polyglot/io/FileSystem.Selector.html#of(org.graalvm.polyglot.io.FileSystem,java.util.function.Predicate)` ## 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) - From interface [`Predicate`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/function/Predicate.html): [`and`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/function/Predicate.html#and%28java.util.function.Predicate%29), [`negate`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/function/Predicate.html#negate%28%29), [`or`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/function/Predicate.html#or%28java.util.function.Predicate%29) # ◆ IOAccess [polyglot](index.md) › [org.graalvm.polyglot.io](org/graalvm/polyglot/io/index.md) · Every page: [llms.txt](llms.txt) Class in [`org.graalvm.polyglot.io`](org/graalvm/polyglot/io/index.md). Since 23.0. ```java public final class IOAccess ``` Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `IOAccess` Represents an IO access configuration of a polyglot context. The IO access configuration determines how a guest language can access the host IO. The access to host IO can be [`disabled`](org/graalvm/polyglot/io/IOAccess.md#NONE), [`enabled`](org/graalvm/polyglot/io/IOAccess.md#ALL), or virtualized using a custom [`file system`](org/graalvm/polyglot/io/FileSystem.md). ## Nested types - [`IOAccess.Builder`](org/graalvm/polyglot/io/IOAccess.Builder.md) (class): Builder to create a custom IO access configuration. ## Fields ### NONE `public static final IOAccess NONE`. Since 23.0. Provides guest language no access to IO. Guest language only has read-only access to the language's home files. The `NONE` is a default value for `Context`s created without `all access`. If you are using this preset, the newly added privileges will default to `false` for this preset. Equivalent of using the following builder configuration: Cite: `org/graalvm/polyglot/io/IOAccess.html#NONE` ```java IOAccess.newBuilder().build(); ``` ### ALL `public static final IOAccess ALL`. Since 23.0. Provides guest language full access to host IO. Guest language have full access to host file system and host sockets. The `ALL` is a default value for `Context`s created with `all access` set to `true`. If you are using this preset, the newly added privileges will default to `true` for this preset. Equivalent of using the following builder configuration: Cite: `org/graalvm/polyglot/io/IOAccess.html#ALL` ```java IOAccess.newBuilder() .allowHostFileAccess(true) .allowHostSocketAccess(true) .build(); ``` ## Methods ### newBuilder() `public static IOAccess.Builder newBuilder()`. Since 23.0. Creates a new builder that allows to create a custom IO access configuration. The builder configuration needs to be completed using the `method`. Cite: `org/graalvm/polyglot/io/IOAccess.html#newBuilder()` ### newBuilder(IOAccess) `public static IOAccess.Builder newBuilder(IOAccess prototype)`. Since 23.0. Creates a new builder that allows to create a custom IO access configuration based of a preset configuration. The preset configuration is copied and used as a template for the returned builder. The builder configuration needs to be completed using the `method`. Cite: `org/graalvm/polyglot/io/IOAccess.html#newBuilder(org.graalvm.polyglot.io.IOAccess)` ### hashCode() `public int hashCode()`. Since 23.0. Overrides `hashCode()`. Cite: `org/graalvm/polyglot/io/IOAccess.html#hashCode()` ### equals(Object) `public boolean equals(Object obj)`. Since 23.0. Overrides `equals(java.lang.Object)`. Cite: `org/graalvm/polyglot/io/IOAccess.html#equals(java.lang.Object)` ### toString() `public String toString()`. Since 23.0. Overrides `toString()`. Cite: `org/graalvm/polyglot/io/IOAccess.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) # ◆ IOAccess.Builder [polyglot](index.md) › [org.graalvm.polyglot.io](org/graalvm/polyglot/io/index.md) · Every page: [llms.txt](llms.txt) Class in [`org.graalvm.polyglot.io`](org/graalvm/polyglot/io/index.md). Since 23.0. Nested in [`IOAccess`](org/graalvm/polyglot/io/IOAccess.md). ```java public static final class IOAccess.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 [`IO access configuration`](org/graalvm/polyglot/io/IOAccess.md). ## Methods ### allowHostFileAccess(boolean) `public IOAccess.Builder allowHostFileAccess(boolean allow)`. Since 23.0. If `true`, it allows the guest language unrestricted access to files on the host system. Cite: `org/graalvm/polyglot/io/IOAccess.Builder.html#allowHostFileAccess(boolean)` ### allowHostSocketAccess(boolean) `public IOAccess.Builder allowHostSocketAccess(boolean allow)`. Since 23.0. If `true`, it allows the guest language unrestricted access to host system sockets. Cite: `org/graalvm/polyglot/io/IOAccess.Builder.html#allowHostSocketAccess(boolean)` ### fileSystem(FileSystem) `public IOAccess.Builder fileSystem(FileSystem fileSystem)`. Since 23.0. Sets a new `FileSystem`. Access to the file system in the guest language will be virtualized using the `fileSystem`. A file system can restrict access to files or fully virtualize file system operations. An example of virtualization is a [memory-based file system](https://github.com/oracle/graal/blob/master/truffle/src/com.oracle.truffle.api.test/src/com/oracle/truffle/api/test/polyglot/MemoryFileSystem.java). GraalVM trusts a custom file system supplied by the embedder. Its methods may be invoked with guest-controlled input, so the embedder must ensure that the implementation is safe for use with the selected `sandbox policy`. Sandbox validation rejects file systems known to expose the default host file system, but it does not inspect the behavior of arbitrary custom implementations. Parameters: `fileSystem` `FileSystem`: the file system to use in the guest language. Returns `IOAccess.Builder`: the `Builder`. Cite: `org/graalvm/polyglot/io/IOAccess.Builder.html#fileSystem(org.graalvm.polyglot.io.FileSystem)` ### toString() `public String toString()`. Since 25.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/io/IOAccess.Builder.html#toString()` ### build() `public IOAccess build()`. Since 23.0. Creates an instance of the custom IO access configuration. Throws: `IllegalArgumentException` (unchecked): if host file access is enabled and a custom file system is set. Cite: `org/graalvm/polyglot/io/IOAccess.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) # ◇ MessageEndpoint [polyglot](index.md) › [org.graalvm.polyglot.io](org/graalvm/polyglot/io/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.io`](org/graalvm/polyglot/io/index.md). Since 19.0. ```java public interface MessageEndpoint ``` An endpoint representing one side of [`message transport`](org/graalvm/polyglot/io/MessageTransport.md). The methods throw [`IOException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/io/IOException.html) when an I/O issue occurs or when the endpoint is closed. **See also** - [`MessageTransport`](org/graalvm/polyglot/io/MessageTransport.md) ## Methods ### sendText(String) `void sendText(String text) throws IOException`. Since 19.0. Send a text message. Cite: `org/graalvm/polyglot/io/MessageEndpoint.html#sendText(java.lang.String)` ### sendBinary(ByteBuffer) `void sendBinary(ByteBuffer data) throws IOException`. Since 19.0. Send a binary message. Cite: `org/graalvm/polyglot/io/MessageEndpoint.html#sendBinary(java.nio.ByteBuffer)` ### sendPing(ByteBuffer) `void sendPing(ByteBuffer data) throws IOException`. Since 19.0. Send a ping request. Cite: `org/graalvm/polyglot/io/MessageEndpoint.html#sendPing(java.nio.ByteBuffer)` ### sendPong(ByteBuffer) `void sendPong(ByteBuffer data) throws IOException`. Since 19.0. Send a pong reply as a response to ping. Cite: `org/graalvm/polyglot/io/MessageEndpoint.html#sendPong(java.nio.ByteBuffer)` ### sendClose() `void sendClose() throws IOException`. Since 19.0. Close the connection. Cite: `org/graalvm/polyglot/io/MessageEndpoint.html#sendClose()` # ◇ MessageTransport [polyglot](index.md) › [org.graalvm.polyglot.io](org/graalvm/polyglot/io/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.io`](org/graalvm/polyglot/io/index.md). Since 19.0. ```java public interface MessageTransport ``` Allows to take over transport of message communication initiated by an instrument. Implement this interface to provide a transport of message communication. When an instrument is about to create a server endpoint, it calls the [`MessageTransport.open(URI, MessageEndpoint)`](org/graalvm/polyglot/io/MessageTransport.md#open%28java.net.URI,org.graalvm.polyglot.io.MessageEndpoint%29) method with the server URI. Usage example: ```java class RoutedServer implements MessageEndpoint { private final MessageEndpoint remoteEndpoint; private final OutputStream routerOut = getRouterOutputStream(); private final WritableByteChannel routerOutChannel; RoutedServer(MessageEndpoint remoteEndpoint) { this.remoteEndpoint = remoteEndpoint; this.routerOutChannel = Channels.newChannel(routerOut); new Thread(() -> { try { runInputLoop(); } catch (IOException ex) { } }).start(); } @Override public void sendText(String text) throws IOException { routerOut.write(text.getBytes()); routerOut.flush(); } @Override public void sendBinary(ByteBuffer data) throws IOException { routerOutChannel.write(data); routerOut.flush(); } @Override public void sendPing(ByteBuffer data) throws IOException { remoteEndpoint.sendPong(data); } @Override public void sendPong(ByteBuffer data) throws IOException { // Did we send ping? } @Override public void sendClose() throws IOException { routerOut.close(); } private void runInputLoop() throws IOException { try (InputStream routerIn = getRouterInputStream()) { byte[] buf = new byte[1024]; ByteBuffer bb = ByteBuffer.wrap(buf); int l; while ((l = routerIn.read(buf)) > 0) { bb.limit(l); remoteEndpoint.sendBinary(bb); bb.rewind(); } } finally { remoteEndpoint.sendClose(); } } } Engine.newBuilder().serverTransport( (uri, peerEndpoint) -> { if (denyHost.equals(uri.getHost())) { throw new MessageTransport.VetoException("Denied access."); } else if (routedURI.equals(uri)) { return new RoutedServer(peerEndpoint); } else { // Permit instruments to setup the servers themselves return null; } }).build(); ``` **See also** - [`org.graalvm.polyglot.Engine.Builder.serverTransport(MessageTransport)`](org/graalvm/polyglot/Engine.Builder.md#serverTransport%28org.graalvm.polyglot.io.MessageTransport%29) - [`org.graalvm.polyglot.Context.Builder.serverTransport(MessageTransport)`](org/graalvm/polyglot/Context.Builder.md#serverTransport%28org.graalvm.polyglot.io.MessageTransport%29) ## Nested types - [`MessageTransport.VetoException`](org/graalvm/polyglot/io/MessageTransport.VetoException.md) (exception): Thrown when a transport connection is vetoed. ## Methods ### open(URI, MessageEndpoint) `MessageEndpoint open(URI uri, MessageEndpoint peerEndpoint) throws IOException, MessageTransport.VetoException`. Since 19.0. Called when a connection to an URI is to be established. The virtualized connection is either opened and an endpoint call back is returned, or the connection is not virtualized in which case `null` is returned. This method can be called concurrently from multiple threads. However, the `MessageEndpoint` ought to be called on one thread at a time, unless you're sure that the particular implementation can handle concurrent calls. The same holds true for the returned endpoint, it's called synchronously. Parameters: `uri` `URI`: the connection URI. `peerEndpoint` `MessageEndpoint`: the peer endpoint representation. Returns `MessageEndpoint`: an implementation of `MessageEndpoint` call back, or `null`. Throws: `MessageTransport.VetoException`: to veto connection to the URL. Cite: `org/graalvm/polyglot/io/MessageTransport.html#open(java.net.URI,org.graalvm.polyglot.io.MessageEndpoint)` # ⚡︎ MessageTransport.VetoException [polyglot](index.md) › [org.graalvm.polyglot.io](org/graalvm/polyglot/io/index.md) · Every page: [llms.txt](llms.txt) Exception in [`org.graalvm.polyglot.io`](org/graalvm/polyglot/io/index.md). Since 19.0. Nested in [`MessageTransport`](org/graalvm/polyglot/io/MessageTransport.md). ```java public final class MessageTransport.VetoException extends Exception ``` 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) > `VetoException` Thrown when a transport connection is vetoed. The initiator of the connection is obliged to abandon it when this exception is thrown. ## Constructors ### VetoException(String) `public VetoException(String message)`. Since 19.0. Create a new VetoException. Cite: `org/graalvm/polyglot/io/MessageTransport.VetoException.html#(java.lang.String)` ## 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), [`fillInStackTrace`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#fillInStackTrace%28%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), [`getMessage`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#getMessage%28%29), [`getStackTrace`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#getStackTrace%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), [`printStackTrace`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#printStackTrace%28%29), [`printStackTrace`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#printStackTrace%28java.io.PrintStream%29), [`printStackTrace`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#printStackTrace%28java.io.PrintWriter%29), [`setStackTrace`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#setStackTrace%28java.lang.StackTraceElement[]%29), [`toString`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Throwable.html#toString%28%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), [`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) # ◇ ProcessHandler [polyglot](index.md) › [org.graalvm.polyglot.io](org/graalvm/polyglot/io/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.io`](org/graalvm/polyglot/io/index.md). Since 19.1.0. ```java public interface ProcessHandler ``` Service-provider for guest languages process builder. This interface allows embedder to intercept subprocess creation done by guest languages. ## Nested types - [`ProcessHandler.ProcessCommand`](org/graalvm/polyglot/io/ProcessHandler.ProcessCommand.md) (class): Subprocess attributes passed to start method. - [`ProcessHandler.Redirect`](org/graalvm/polyglot/io/ProcessHandler.Redirect.md) (class): Represents a source of subprocess input or a destination of subprocess output. ## Methods ### start(ProcessHandler.ProcessCommand) `Process start(ProcessHandler.ProcessCommand command) throws IOException`. Since 19.1.0. A request to start a new subprocess with given attributes. The default implementation uses [`ProcessBuilder`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/ProcessBuilder.html) to create the new subprocess. The subprocess current working directory is set to `ProcessCommand.getDirectory()`. The `ProcessCommand.getDirectory()` value was either explicitely set by the guest language or the `FileSystem`'s current working directory is used. The subprocess environment is set to `ProcessCommand.getEnvironment()`, the initial value of [`ProcessBuilder.environment()`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/ProcessBuilder.html#environment%28%29) is cleaned. The `ProcessCommand.getEnvironment()` contains the environment variables set by guest language and possibly also the JVM process environment depending on value of `Builder.allowEnvironmentAccess(org.graalvm.polyglot.EnvironmentAccess)`. Implementation example: Parameters: `command` `ProcessHandler.ProcessCommand`: the subprocess attributes. Throws: `SecurityException` (unchecked): if the process creation was forbidden by this handler. `IOException`: if the process fails to execute. Cite: `org/graalvm/polyglot/io/ProcessHandler.html#start(org.graalvm.polyglot.io.ProcessHandler.ProcessCommand)` ```java public Process start(ProcessCommand command) throws IOException { ProcessBuilder builder = new ProcessBuilder(command.getCommand()).redirectErrorStream(command.isRedirectErrorStream()).redirectInput( asProcessBuilderRedirect(command.getInputRedirect())).redirectOutput(asProcessBuilderRedirect(command.getOutputRedirect())).redirectError( asProcessBuilderRedirect(command.getErrorRedirect())); Map env = builder.environment(); env.clear(); env.putAll(command.getEnvironment()); String cwd = command.getDirectory(); if (cwd != null) { builder.directory(Paths.get(cwd).toFile()); } return builder.start(); } private static java.lang.ProcessBuilder.Redirect asProcessBuilderRedirect(ProcessHandler.Redirect redirect) { if (redirect == ProcessHandler.Redirect.PIPE) { return java.lang.ProcessBuilder.Redirect.PIPE; } else if (redirect == ProcessHandler.Redirect.INHERIT) { return java.lang.ProcessBuilder.Redirect.INHERIT; } else { throw new IllegalStateException("Unsupported redirect: " + redirect); } } ``` # ◆ ProcessHandler.ProcessCommand [polyglot](index.md) › [org.graalvm.polyglot.io](org/graalvm/polyglot/io/index.md) · Every page: [llms.txt](llms.txt) Class in [`org.graalvm.polyglot.io`](org/graalvm/polyglot/io/index.md). Since 19.1.0. Nested in [`ProcessHandler`](org/graalvm/polyglot/io/ProcessHandler.md). ```java public final class ProcessHandler.ProcessCommand ``` Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `ProcessCommand` Subprocess attributes passed to [`start`](org/graalvm/polyglot/io/ProcessHandler.md#start%28org.graalvm.polyglot.io.ProcessHandler.ProcessCommand%29) method. ## Methods ### getCommand() `public List getCommand()`. Since 19.1.0. Returns the subprocess executable and arguments as an immutable list. Cite: `org/graalvm/polyglot/io/ProcessHandler.ProcessCommand.html#getCommand()` ### getDirectory() `public String getDirectory()`. Since 19.1.0. Returns the subprocess working directory. Cite: `org/graalvm/polyglot/io/ProcessHandler.ProcessCommand.html#getDirectory()` ### getEnvironment() `public Map getEnvironment()`. Since 19.1.0. Returns the subprocess environment as an immutable map. Cite: `org/graalvm/polyglot/io/ProcessHandler.ProcessCommand.html#getEnvironment()` ### isRedirectErrorStream() `public boolean isRedirectErrorStream()`. Since 19.1.0. Return whether the standard error output should be merged into standard output. Cite: `org/graalvm/polyglot/io/ProcessHandler.ProcessCommand.html#isRedirectErrorStream()` ### getInputRedirect() `public ProcessHandler.Redirect getInputRedirect()`. Since 19.1.0. Returns the standard input source. Cite: `org/graalvm/polyglot/io/ProcessHandler.ProcessCommand.html#getInputRedirect()` ### getOutputRedirect() `public ProcessHandler.Redirect getOutputRedirect()`. Since 19.1.0. Returns the standard output destination. Cite: `org/graalvm/polyglot/io/ProcessHandler.ProcessCommand.html#getOutputRedirect()` ### getErrorRedirect() `public ProcessHandler.Redirect getErrorRedirect()`. Since 19.1.0. Returns the standard error output destination. Cite: `org/graalvm/polyglot/io/ProcessHandler.ProcessCommand.html#getErrorRedirect()` ### create(List, String, …) `public static ProcessHandler.ProcessCommand create(List cmd, String cwd, Map environment, boolean redirectErrorStream, ProcessHandler.Redirect inputRedirect, ProcessHandler.Redirect outputRedirect, ProcessHandler.Redirect errorRedirect)`. Since 23.1.0. Creates a ProcessCommand. Not for direct use. Cite: `org/graalvm/polyglot/io/ProcessHandler.ProcessCommand.html#create(java.util.List,java.lang.String,java.util.Map,boolean,org.graalvm.polyglot.io.ProcessHandler.Redirect,org.graalvm.polyglot.io.ProcessHandler.Redirect,org.graalvm.polyglot.io.ProcessHandler.Redirect)` ## 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) # ◆ ProcessHandler.Redirect [polyglot](index.md) › [org.graalvm.polyglot.io](org/graalvm/polyglot/io/index.md) · Every page: [llms.txt](llms.txt) Class in [`org.graalvm.polyglot.io`](org/graalvm/polyglot/io/index.md). Since 19.1.0. Nested in [`ProcessHandler`](org/graalvm/polyglot/io/ProcessHandler.md). ```java public final class ProcessHandler.Redirect ``` Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `Redirect` Represents a source of subprocess input or a destination of subprocess output. ## Fields ### PIPE `public static final ProcessHandler.Redirect PIPE`. Since 19.1.0. Indicates that subprocess I/O will be connected to the current Java process using a pipe. Cite: `org/graalvm/polyglot/io/ProcessHandler.Redirect.html#PIPE` ### INHERIT `public static final ProcessHandler.Redirect INHERIT`. Since 19.1.0. Indicates that subprocess I/O source or destination will be the same as those of the current process. Cite: `org/graalvm/polyglot/io/ProcessHandler.Redirect.html#INHERIT` ## Methods ### getOutputStream() `public OutputStream getOutputStream()`. Since 23.1.0. Returns the output stream to redirect to. Cite: `org/graalvm/polyglot/io/ProcessHandler.Redirect.html#getOutputStream()` ### toString() `public String toString()`. Since 19.1.0. Overrides `toString()`. Cite: `org/graalvm/polyglot/io/ProcessHandler.Redirect.html#toString()` ### hashCode() `public int hashCode()`. Since 19.1.0. Overrides `hashCode()`. Cite: `org/graalvm/polyglot/io/ProcessHandler.Redirect.html#hashCode()` ### equals(Object) `public boolean equals(Object obj)`. Since 19.1.0. Overrides `equals(java.lang.Object)`. Cite: `org/graalvm/polyglot/io/ProcessHandler.Redirect.html#equals(java.lang.Object)` ### createRedirectToStream(OutputStream) `public static ProcessHandler.Redirect createRedirectToStream(OutputStream stream)`. Since 23.1.0. Creates a ProcessCommand. Not for direct use. Cite: `org/graalvm/polyglot/io/ProcessHandler.Redirect.html#createRedirectToStream(java.io.OutputStream)` ## 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.polyglot.management [polyglot](index.md) · Every page: [llms.txt](llms.txt) Package in polyglot. Since 19.0. The management package provides tools that monitor and instrument the behavior of guest language programs. See [graalvm.org](http://www.graalvm.org/docs/graalvm-as-a-platform/embed/) for more examples on how to use this API. **See also** - [`Execution listeners allow to instrument the execution of guest languages.`](org/graalvm/polyglot/management/ExecutionListener.md) ## Classes - [`ExecutionEvent`](org/graalvm/polyglot/management/ExecutionEvent.md): An execution event object passed to an execution listener consumer. - [`ExecutionListener`](org/graalvm/polyglot/management/ExecutionListener.md): Execution listeners allow to instrument the execution of guest languages. # ◆ ExecutionEvent [polyglot](index.md) › [org.graalvm.polyglot.management](org/graalvm/polyglot/management/index.md) · Every page: [llms.txt](llms.txt) Class in [`org.graalvm.polyglot.management`](org/graalvm/polyglot/management/index.md). Since 19.0. ```java public final class ExecutionEvent ``` Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `ExecutionEvent` An execution event object passed to an execution listener consumer. Execution event instances remain valid until the engine is closed. Values and returned exceptions will only remain valid until the context was closed. **See also** - [`For further details.`](org/graalvm/polyglot/management/ExecutionListener.md) ## Methods ### getLocation() `public SourceSection getLocation()`. Since 19.0. Returns the source location of the event that was triggered or `null` if no location source location is available. Cite: `org/graalvm/polyglot/management/ExecutionEvent.html#getLocation()` ### getRootName() `public String getRootName()`. Since 19.0. Returns the root name or `null` if no name is available. The root name may also be available for events caused by expressions and statements. In this case the name of the containing root will be returned. Cite: `org/graalvm/polyglot/management/ExecutionEvent.html#getRootName()` ### getInputValues() `public List getInputValues()`. Since 19.0. Returns the input values provided to execute this source location. This method returns `null` if input value collection is not `enabled`. Input values are available in `OnReturn` events.The returned list may contain `null` values if input values were not evaluated or if an exception occurred executing input values. The returned list is unmodifiable. The returned input values may escape the event consumer and remain valid until the context is closed. Cite: `org/graalvm/polyglot/management/ExecutionEvent.html#getInputValues()` ### getReturnValue() `public Value getReturnValue()`. Since 19.0. Returns the return value of this source location after it was executed. This method returns `null` if return value collection is not `enabled`. Return values are available in `OnReturn` events. The returned value is allowed to escape the event consumer and remain valid until the context is closed. Cite: `org/graalvm/polyglot/management/ExecutionEvent.html#getReturnValue()` ### getException() `public PolyglotException getException()`. Since 19.0. Returns the exception of this source location after it was executed. This method returns `null` if exception collection is not `enabled`. Exceptions are only available in `OnReturn` events if an exception was thrown when the location was executed. The returned value is allowed to escape the event consumer and remains valid until the context is closed. Cite: `org/graalvm/polyglot/management/ExecutionEvent.html#getException()` ### isExpression() `public boolean isExpression()`. Since 19.0. Returns `true` if the source location is marked as expression, else `false`. The collection of expression events may be enabled by calling `ExecutionListener.Builder.expressions(boolean)`. Cite: `org/graalvm/polyglot/management/ExecutionEvent.html#isExpression()` ### isStatement() `public boolean isStatement()`. Since 19.0. Returns `true` if the source location is marked as a statement, else `false`. The collection of statement events may be enabled by calling `ExecutionListener.Builder.statements(boolean)`. Cite: `org/graalvm/polyglot/management/ExecutionEvent.html#isStatement()` ### isRoot() `public boolean isRoot()`. Since 19.0. Returns `true` if the source location is marked as a root of a function, method or closure, else `false`. The collection of root events may be enabled by calling `ExecutionListener.Builder.roots(boolean)`. Cite: `org/graalvm/polyglot/management/ExecutionEvent.html#isRoot()` ### toString() `public String toString()`. Since 19.0. Overrides `toString()`. Cite: `org/graalvm/polyglot/management/ExecutionEvent.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) # ◆ ExecutionListener [polyglot](index.md) › [org.graalvm.polyglot.management](org/graalvm/polyglot/management/index.md) · Every page: [llms.txt](llms.txt) Class in [`org.graalvm.polyglot.management`](org/graalvm/polyglot/management/index.md). Since 19.0. ```java public final class ExecutionListener implements AutoCloseable ``` Inheritance: [`Object`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Object.html) > `ExecutionListener` Implements: [`AutoCloseable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AutoCloseable.html) Execution listeners allow to instrument the execution of guest languages. For example, it is possible to attach an execution listeners that is invoked for every statement of the guest language program, similar to how a debugger would single-step through the program. The following example prints the characters of every executed statement of simple JavaScript loop. ` `` Context context = Context.create("js"); ExecutionListeners listener = ExecutionListeners.newBuilder() .onEnter((e) -> System.out.println( e.getLocation().getCharacters())) .statements(true) .attach(context.getEngine()); context.eval("js", "for (var i = 0; i ``<`` 2; i++);"); listener.close(); `` ` Prints the following result: ```java i = 0 i < 2 i++ i < 2 i++ i < 2 ``` ### Creation and Closing An execution listener builder can be created by first invoking [`newBuilder()`](org/graalvm/polyglot/management/ExecutionListener.md#newBuilder%28%29). At least one event consumer and one filtered source element needs to be enabled. To complete the listener attachment [`Builder.attach(Engine)`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#attach%28org.graalvm.polyglot.Engine%29) needs to be invoked. [`Attach`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#attach%28org.graalvm.polyglot.Engine%29) may be invoked multiple times for one builder. All execution listeners are automatically closed when the engine [`closed`](org/graalvm/polyglot/Engine.md#close%28%29). To close a listener earlier [`close()`](org/graalvm/polyglot/management/ExecutionListener.md#close%28%29) may be invoked. Execution listeners are [`AutoCloseable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AutoCloseable.html) and can therefore be used in try-with-resources blocks. ### Event Consumers The following event consumers can be set for an execution listener: - [`OnEnter`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#onEnter%28java.util.function.Consumer%29): An event that is notified when an execution of an element is entered. This event is consumed before any input values are executed. - [`OnReturn`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#onReturn%28java.util.function.Consumer%29): An event that is notified when an execution of an element was entered and completed. At least one event consumer needs to be set otherwise an [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) will be thrown by the builder when it is [`attached`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#attach%28org.graalvm.polyglot.Engine%29). Event consumers may throw any Java host exception. Such exceptions will be reported to the context as [`PolyglotException`](org/graalvm/polyglot/PolyglotException.md) instances. The thrown exception may be accessed using [`PolyglotException.asHostException()`](org/graalvm/polyglot/PolyglotException.md#asHostException%28%29). ### Event Data For every event that is consumed the [`source location`](org/graalvm/polyglot/management/ExecutionEvent.md#getLocation%28%29) and [`root name`](org/graalvm/polyglot/management/ExecutionEvent.md#getRootName%28%29) data is available. Other event data will return `null` by default. The collection of the following event data may be enabled: - [`Return values`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#collectReturnValue%28boolean%29): Enables access to [`return values`](org/graalvm/polyglot/management/ExecutionEvent.md#getReturnValue%28%29) in [`OnReturn`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#onReturn%28java.util.function.Consumer%29) events. - [`Input values`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#collectInputValues%28boolean%29): Enables access to [`input values`](org/graalvm/polyglot/management/ExecutionEvent.md#getInputValues%28%29) in [`OnReturn`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#onReturn%28java.util.function.Consumer%29) events. - [`Errors`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#collectExceptions%28boolean%29): Enables access to [`errors`](org/graalvm/polyglot/management/ExecutionEvent.md#getException%28%29) in [`OnReturn`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#onReturn%28java.util.function.Consumer%29) events. If additional event data is collected then the peak performance overhead of execution listeners is significant. It is not recommended to collect additional event data when running production workloads. Provided event instances may escape the event consumer and remain usable until the engine is closed. ### Event Filters Execution listeners can be applied to the following source elements: - [`Roots`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#roots%28boolean%29): Filter for marked program locations that represent a root of a function, method or closure. - [`Statements`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#statements%28boolean%29): Filter for marked program locations that represent a statement. - [`Expressions`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#expressions%28boolean%29): Filter for marked program locations that represent an expression. At least one source element needs to be enabled otherwise an [`IllegalArgumentException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalArgumentException.html) will be thrown by the builder when it is [`attached`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#attach%28org.graalvm.polyglot.Engine%29). Not all source elements may be supported by a language. If the language does not support listening to a source element then no events will be triggered. If multiple source elements are enabled, multiple or one event may be reported per source location. If this behavior is not desirable than multiple execution listeners for each source element can be created and attached. By default the execution listener is applied to all [`sources`](org/graalvm/polyglot/Source.md) that were loaded. A [`source filter`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#sourceFilter%28java.util.function.Predicate%29) may be attached to limit the number of sources that will trigger events. ### Performance The peak performance overhead of execution listeners depend on the granularity of the filter. Roots can be collected more efficiently than statement or expression events due to their frequency. If additional event data is collected then the peak performance overhead of execution listeners is significant. It is not recommended to collect additional event data when running production workloads. [`Attaching`](org/graalvm/polyglot/management/ExecutionListener.Builder.md#attach%28org.graalvm.polyglot.Engine%29) and [`closing`](org/graalvm/polyglot/management/ExecutionListener.md#close%28%29) execution listeners are expensive operations and typically require to traverse through all loaded code. Code that was previously optimized will be deoptimized in the process. It is most efficient to attach an execution listener before any code is executed and let execution listeners automatically close with the engine. ### Compatibility Event execution order and granularity of events are language specific and may change without notice. There are no compatibility guarantees for that provided by the polyglot SDK. Certain language implementations may do so. Please see the language implementation documentation for further details. ### Use-cases Execution listeners are designed as simple API for polyglot embedders to capture cross cutting concerns of the execution of programs. For example, it can be used to count all statements executed in order to detect potentially malicious code. It is not designed to be an API for implementing fully fledged tools. The [Truffle instrumentation framework](http://www.graalvm.org/docs/graalvm-as-a-platform/implement-instrument/) should be used for that purpose instead. ## Nested types - [`ExecutionListener.Builder`](org/graalvm/polyglot/management/ExecutionListener.Builder.md) (class): A builder used to construct execution events. ## Methods ### close() `public void close()`. Since 19.0. Closes and detaches this execution listener from the engine. After an execution listener was closed no further events will be reported. `Attaching` and `closing` execution listeners are expensive operations and typically require to traverse through all loaded code. Code that was previously optimized will be deoptimized in the process. It is most efficient to attach an execution listener before any code is executed and let execution listeners automatically close with the engine. Overrides `close()`. See also: `Builder.attach(Engine)`. Cite: `org/graalvm/polyglot/management/ExecutionListener.html#close()` ### toString() `public String toString()`. Since 25.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/management/ExecutionListener.html#toString()` ### newBuilder() `public static ExecutionListener.Builder newBuilder()`. Since 19.0. Creates a builder that can be used to attach execution listeners. The returned Builder instance is not thread-safe. A minimal example on how to build and attach a listener: ` `` ExecutionListeners listener = ExecutionListeners.newBuilder() .onEnter((e) -> ...) .statements(true) .attach(context.getEngine()); `` `. See also: `ExecutionListener`. Cite: `org/graalvm/polyglot/management/ExecutionListener.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) # ◆ ExecutionListener.Builder [polyglot](index.md) › [org.graalvm.polyglot.management](org/graalvm/polyglot/management/index.md) · Every page: [llms.txt](llms.txt) Class in [`org.graalvm.polyglot.management`](org/graalvm/polyglot/management/index.md). Since 19.0. Nested in [`ExecutionListener`](org/graalvm/polyglot/management/ExecutionListener.md). ```java public final class ExecutionListener.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 execution events. Builder instances are not thread-safe and may not be used from multiple threads at the same time. **See also** - [`For further details.`](org/graalvm/polyglot/management/ExecutionEvent.md) ## Methods ### onEnter(Consumer) `public ExecutionListener.Builder onEnter(Consumer listener)`. Since 19.0. Set a listener that is notified when an execution of an element is entered. Cite: `org/graalvm/polyglot/management/ExecutionListener.Builder.html#onEnter(java.util.function.Consumer)` ### onReturn(Consumer) `public ExecutionListener.Builder onReturn(Consumer listener)`. Since 19.0. Set a listener that is notified when an execution of an element was entered and completed. Cite: `org/graalvm/polyglot/management/ExecutionListener.Builder.html#onReturn(java.util.function.Consumer)` ### sourceFilter(Predicate) `public ExecutionListener.Builder sourceFilter(Predicate predicate)`. Since 19.0. Set an addition filter that filters execution events by source. By default all sources are included. Source predicates must be stable, i.e. always return the same result for a source. The filter predicate may be invoked on multiple threads at the same time. Parameters: `predicate` `Predicate`: the source predicate that returns `true` for a source to be included and `false` otherwise. Cite: `org/graalvm/polyglot/management/ExecutionListener.Builder.html#sourceFilter(java.util.function.Predicate)` ### rootNameFilter(Predicate) `public ExecutionListener.Builder rootNameFilter(Predicate predicate)`. Since 19.0. Set an addition filter execution events by root name. By default all root names are included. Root name predicates must be stable and always return the same result for source. The filter predicate may be invoked on multiple threads at the same time. Cite: `org/graalvm/polyglot/management/ExecutionListener.Builder.html#rootNameFilter(java.util.function.Predicate)` ### roots(boolean) `public ExecutionListener.Builder roots(boolean enabled)`. Since 19.0. Include program locations that are marked as root of a function, method or closure. By default no source elements are included. Parameters: `enabled` `boolean`: `true` if enabled, else `false`. See also: `expressions(boolean)`, `statements(boolean)`. Cite: `org/graalvm/polyglot/management/ExecutionListener.Builder.html#roots(boolean)` ### statements(boolean) `public ExecutionListener.Builder statements(boolean enabled)`. Since 19.0. Include program locations that are marked as statements. By default no source elements are included. Parameters: `enabled` `boolean`: `true` if enabled, else `false`. See also: `expressions(boolean)`, `roots(boolean)`. Cite: `org/graalvm/polyglot/management/ExecutionListener.Builder.html#statements(boolean)` ### expressions(boolean) `public ExecutionListener.Builder expressions(boolean enabled)`. Since 19.0. Include program locations that are marked as expressions. By default no source elements are included. Parameters: `enabled` `boolean`: `true` if enabled, else `false`. See also: `statements(boolean)`, `roots(boolean)`. Cite: `org/graalvm/polyglot/management/ExecutionListener.Builder.html#expressions(boolean)` ### collectInputValues(boolean) `public ExecutionListener.Builder collectInputValues(boolean enabled)`. Since 19.0. Collect additional execution event data for input values. The input values may be accessed in `OnReturn` events with `ExecutionEvent.getInputValues()`. If additional event data is collected then the peak performance overhead of execution listeners is significant. It is not recommended to collect additional event data when running production workloads. Parameters: `enabled` `boolean`: `true` if enabled, else `false`. Cite: `org/graalvm/polyglot/management/ExecutionListener.Builder.html#collectInputValues(boolean)` ### collectReturnValue(boolean) `public ExecutionListener.Builder collectReturnValue(boolean enabled)`. Since 19.0. Collect additional execution event data about return values. The return value may be accessed in `OnReturn` events with `ExecutionEvent.getReturnValue()`. If additional event data is collected then the peak performance overhead of execution listeners is significant. It is not recommended to collect additional event data when running production workloads. Parameters: `enabled` `boolean`: `true` if enabled, else `false`. Cite: `org/graalvm/polyglot/management/ExecutionListener.Builder.html#collectReturnValue(boolean)` ### collectExceptions(boolean) `public ExecutionListener.Builder collectExceptions(boolean enabled)`. Since 19.0. Collect additional execution event data about errors. The error may be accessed in `OnReturn` events with `ExecutionEvent.getException()`. If additional event data is collected then the peak performance overhead of execution listeners is significant. It is not recommended to collect additional event data when running production workloads. Parameters: `enabled` `boolean`: `true` if enabled, else `false`. Cite: `org/graalvm/polyglot/management/ExecutionListener.Builder.html#collectExceptions(boolean)` ### toString() `public String toString()`. Since 25.3. Overrides `toString()`. Cite: `org/graalvm/polyglot/management/ExecutionListener.Builder.html#toString()` ### attach(Engine) `public ExecutionListener attach(Engine engine)`. Since 19.0. Creates a new execution listener using the current builder configuration and attaches it to an engine. The same builder configuration may be used to attach multiple listeners. Execution listeners cannot be attached to engines that were statically looked up using ` Context.``getCurrent()``.``getEngine()`` `. For security reasons only the original `creator` of the context or engine is allowed to perform this action. `Attaching` and `closing` execution listeners are expensive operations and typically require to traverse through all loaded code. Code that was previously optimized will be deoptimized in the process. It is most efficient to attach an execution listener before any code is executed and let execution listeners automatically close with the engine. Parameters: `engine` `Engine`: the engine to attach to. Returns `ExecutionListener`: the attached closable execution listener. Throws: `PolyglotException` (unchecked): if one of the provided filter predicate fails. Cite: `org/graalvm/polyglot/management/ExecutionListener.Builder.html#attach(org.graalvm.polyglot.Engine)` ## 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) # ▣ org.graalvm.polyglot.proxy [polyglot](index.md) · Every page: [llms.txt](llms.txt) Package in polyglot. Since 19.0. The GraalVM SDK proxy interfaces allow to mimic guest language objects, arrays, executables, primitives and native objects in Graal languages. Every Graal language will treat instances of proxies like an object 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. See [graalvm.org](http://www.graalvm.org/docs/embed) for more examples on how to use this API. **See also** - [`for more an overview over all available proxy interfaces.`](org/graalvm/polyglot/proxy/Proxy.md) ## Interfaces - [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md): Proxy interfaces allow to mimic guest language objects, arrays, executables, primitives and native objects in Graal languages. - [`ProxyArray`](org/graalvm/polyglot/proxy/ProxyArray.md): Interface to be implemented to mimic guest language arrays. - [`ProxyDate`](org/graalvm/polyglot/proxy/ProxyDate.md): Interface to be implemented to mimic guest language objects that represents dates. - [`ProxyDuration`](org/graalvm/polyglot/proxy/ProxyDuration.md): Interface to be implemented to mimic guest language objects that represents durations. - [`ProxyExecutable`](org/graalvm/polyglot/proxy/ProxyExecutable.md): Interface to be implemented to mimic guest language objects that are executable. - [`ProxyHashMap`](org/graalvm/polyglot/proxy/ProxyHashMap.md): Interface to be implemented to mimic guest language hash maps. - [`ProxyInstant`](org/graalvm/polyglot/proxy/ProxyInstant.md): Interface to be implemented to mimic guest language objects that represents timestamps. - [`ProxyInstantiable`](org/graalvm/polyglot/proxy/ProxyInstantiable.md): Interface to be implemented to mimic guest language objects that are instantiable. - [`ProxyIterable`](org/graalvm/polyglot/proxy/ProxyIterable.md): Interface to be implemented to mimic guest language iterables. - [`ProxyIterator`](org/graalvm/polyglot/proxy/ProxyIterator.md): Interface to be implemented to mimic guest language iterators. - [`ProxyNativeObject`](org/graalvm/polyglot/proxy/ProxyNativeObject.md): Interface to be implemented to mimic native pointers. - [`ProxyObject`](org/graalvm/polyglot/proxy/ProxyObject.md): Interface to be implemented to mimic guest language objects that contain members. - [`ProxyTime`](org/graalvm/polyglot/proxy/ProxyTime.md): Interface to be implemented to mimic guest language objects that represents times. - [`ProxyTimeZone`](org/graalvm/polyglot/proxy/ProxyTimeZone.md): Interface to be implemented to mimic guest language objects that represents timezones. # ◇ Proxy [polyglot](index.md) › [org.graalvm.polyglot.proxy](org/graalvm/polyglot/proxy/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.proxy`](org/graalvm/polyglot/proxy/index.md). Since 19.0. ```java public interface Proxy ``` Proxy interfaces allow to mimic guest language objects, arrays, executables, primitives and native objects in Graal languages. Every Graal language will treat instances of proxies like an object 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. Exceptions thrown by proxies are wrapped with a [`PolyglotException`](org/graalvm/polyglot/PolyglotException.md) when the proxy is invoked in a guest language. It is possible to unwrap the [`PolyglotException`](org/graalvm/polyglot/PolyglotException.md) using [`PolyglotException.asHostException()`](org/graalvm/polyglot/PolyglotException.md#asHostException%28%29). The interfaces [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md), [`ProxyArray`](org/graalvm/polyglot/proxy/ProxyArray.md), [`ProxyExecutable`](org/graalvm/polyglot/proxy/ProxyExecutable.md), [`ProxyInstantiable`](org/graalvm/polyglot/proxy/ProxyInstantiable.md), [`ProxyNativeObject`](org/graalvm/polyglot/proxy/ProxyNativeObject.md), [`ProxyObject`](org/graalvm/polyglot/proxy/ProxyObject.md), [`ProxyIterable`](org/graalvm/polyglot/proxy/ProxyIterable.md), [`ProxyIterator`](org/graalvm/polyglot/proxy/ProxyIterator.md) can be used in combination with any other proxy interfaces. The following proxy interface combinations are exclusive and throw an [`AssertionError`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AssertionError.html) if used together: - [`ProxyDuration`](org/graalvm/polyglot/proxy/ProxyDuration.md) - [`ProxyInstant`](org/graalvm/polyglot/proxy/ProxyInstant.md), [`ProxyDate`](org/graalvm/polyglot/proxy/ProxyDate.md), [`ProxyTime`](org/graalvm/polyglot/proxy/ProxyTime.md) or [`ProxyTimeZone`](org/graalvm/polyglot/proxy/ProxyTimeZone.md). The following proxy interface combinations are invalid and throw an [`AssertionError`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/AssertionError.html) if used: - If [`ProxyTimeZone`](org/graalvm/polyglot/proxy/ProxyTimeZone.md) and [`ProxyDate`](org/graalvm/polyglot/proxy/ProxyDate.md) without [`ProxyTime`](org/graalvm/polyglot/proxy/ProxyTime.md) - If [`ProxyTimeZone`](org/graalvm/polyglot/proxy/ProxyTimeZone.md) and [`ProxyTime`](org/graalvm/polyglot/proxy/ProxyTime.md) without [`ProxyDate`](org/graalvm/polyglot/proxy/ProxyDate.md). **See also** - [`to mimic arrays`](org/graalvm/polyglot/proxy/ProxyArray.md) - [`to mimic objects with members`](org/graalvm/polyglot/proxy/ProxyObject.md) - [`to mimic objects that can be executed`](org/graalvm/polyglot/proxy/ProxyExecutable.md) - [`to mimic native objects`](org/graalvm/polyglot/proxy/ProxyNativeObject.md) - [`to mimic date objects`](org/graalvm/polyglot/proxy/ProxyDate.md) - [`to mimic time objects`](org/graalvm/polyglot/proxy/ProxyTime.md) - [`to mimic timezone objects`](org/graalvm/polyglot/proxy/ProxyTimeZone.md) - [`to mimic duration objects`](org/graalvm/polyglot/proxy/ProxyDuration.md) - [`to mimic timestamp objects`](org/graalvm/polyglot/proxy/ProxyInstant.md) - [`to mimic objects that are instantiable`](org/graalvm/polyglot/proxy/ProxyInstantiable.md) - [`to mimic iterable objects`](org/graalvm/polyglot/proxy/ProxyIterable.md) - [`to mimic iterator objects`](org/graalvm/polyglot/proxy/ProxyIterator.md) - [`to mimic map objects`](org/graalvm/polyglot/proxy/ProxyHashMap.md) # ◇ ProxyArray [polyglot](index.md) › [org.graalvm.polyglot.proxy](org/graalvm/polyglot/proxy/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.proxy`](org/graalvm/polyglot/proxy/index.md). Since 19.0. ```java public interface ProxyArray extends ProxyIterable ``` Extends: [`ProxyIterable`](org/graalvm/polyglot/proxy/ProxyIterable.md) Interface to be implemented to mimic guest language arrays. Arrays are always interpreted as zero-based arrays, independent of whether the Graal language uses one-based arrays. For example an access to array index one in a language with one-based arrays will access the proxy array at index zero. **See also** - [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) ## Methods ### get(long) `Object get(long index)`. Since 19.0. Returns the element at the given index. Throws: `ArrayIndexOutOfBoundsException` (unchecked): if the index is out of bounds. `UnsupportedOperationException` (unchecked): if the operation is not supported. Cite: `org/graalvm/polyglot/proxy/ProxyArray.html#get(long)` ### set(long, Value) `void set(long index, Value value)`. Since 19.0. Sets the element at the given index. Throws: `ArrayIndexOutOfBoundsException` (unchecked): if the index is out of bounds. `UnsupportedOperationException` (unchecked): if the operation is not supported. Cite: `org/graalvm/polyglot/proxy/ProxyArray.html#set(long,org.graalvm.polyglot.Value)` ### remove(long) `default boolean remove(long index)`. Since 19.0. Removes the element at the given index. Returns `boolean`: `true` when the element was removed, `false` when the element didn't exist. Throws: `ArrayIndexOutOfBoundsException` (unchecked): if the index is out of bounds. `UnsupportedOperationException` (unchecked): if the operation is not supported. Cite: `org/graalvm/polyglot/proxy/ProxyArray.html#remove(long)` ### getSize() `long getSize()`. Since 19.0. Returns the reported size of the array. The returned size of an array does not limit a guest language to get and set values using arbitrary indices. The array size is typically used by Graal languages to traverse the array. Cite: `org/graalvm/polyglot/proxy/ProxyArray.html#getSize()` ### getIterator() `default Object getIterator()`. Since 20.1. Returns an iterator. The returned object must be interpreted as an iterator using the semantics of `Context.asValue(Object)` otherwise an [`IllegalStateException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html) is thrown. Examples for valid return values are: `ProxyIterator`; [`Iterator`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Iterator.html), requires `host iterable access`; A guest language object representing an iterator. Overrides `getIterator()`. Cite: `org/graalvm/polyglot/proxy/ProxyArray.html#getIterator()` ### fromArray(Object...) `static ProxyArray fromArray(Object... values)`. Since 19.0. Creates a proxy array backed by a Java Object array. If the set values of the array are host values then they will be `unboxed`. Note this function expects a variable number of arguments of type Object, thus might not work as expected on non-Object array types. For instance, an int array will be stored as the first element of the resulting proxy array. To flatten it out, convert it to an Object array first (e.g. with `Arrays.stream( myIntArray ).boxed().toArray();`). Parameters: `values` `Object...`: the Object[] array or the vararg arguments to be proxied. Cite: `org/graalvm/polyglot/proxy/ProxyArray.html#fromArray(java.lang.Object...)` ### fromList(List) `static ProxyArray fromList(List values)`. Since 19.0. Creates a proxy array backed by a Java List. If the set values of the list are host values then the they will be `unboxed`. Cite: `org/graalvm/polyglot/proxy/ProxyArray.html#fromList(java.util.List)` # ◇ ProxyDate [polyglot](index.md) › [org.graalvm.polyglot.proxy](org/graalvm/polyglot/proxy/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.proxy`](org/graalvm/polyglot/proxy/index.md). Since 19.2.0. ```java public interface ProxyDate extends Proxy ``` Extends: [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) Interface to be implemented to mimic guest language objects that represents dates. **See also** - [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) - [`Value`](org/graalvm/polyglot/Value.md) ## Methods ### asDate() `LocalDate asDate()`. Since 19.2.0. Returns the date information. The returned value must not be `null`. Cite: `org/graalvm/polyglot/proxy/ProxyDate.html#asDate()` ### from(LocalDate) `static ProxyDate from(LocalDate date)`. Since 19.2.0. Creates a proxy date from a local date. Cite: `org/graalvm/polyglot/proxy/ProxyDate.html#from(java.time.LocalDate)` # ◇ ProxyDuration [polyglot](index.md) › [org.graalvm.polyglot.proxy](org/graalvm/polyglot/proxy/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.proxy`](org/graalvm/polyglot/proxy/index.md). Since 19.2.0. ```java public interface ProxyDuration extends Proxy ``` Extends: [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) Interface to be implemented to mimic guest language objects that represents durations. **See also** - [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) - [`Value`](org/graalvm/polyglot/Value.md) ## Methods ### asDuration() `Duration asDuration()`. Since 19.2.0. Returns the duration information. The returned value must not be `null`. Cite: `org/graalvm/polyglot/proxy/ProxyDuration.html#asDuration()` ### from(Duration) `static ProxyDuration from(Duration duration)`. Since 19.2.0. Creates a proxy duration from a duration. Cite: `org/graalvm/polyglot/proxy/ProxyDuration.html#from(java.time.Duration)` # ◇ ProxyExecutable [polyglot](index.md) › [org.graalvm.polyglot.proxy](org/graalvm/polyglot/proxy/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.proxy`](org/graalvm/polyglot/proxy/index.md). Since 19.0. ```java @FunctionalInterface public interface ProxyExecutable extends Proxy ``` Extends: [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) Interface to be implemented to mimic guest language objects that are executable. **See also** - [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) ## Methods ### execute(Value...) `Object execute(Value... arguments)`. Since 19.0. Executes the object with the given arguments and returns its result. Throws: `UnsupportedOperationException` (unchecked): if the proxy cannot be executed with the given arguments. Cite: `org/graalvm/polyglot/proxy/ProxyExecutable.html#execute(org.graalvm.polyglot.Value...)` # ◇ ProxyHashMap [polyglot](index.md) › [org.graalvm.polyglot.proxy](org/graalvm/polyglot/proxy/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.proxy`](org/graalvm/polyglot/proxy/index.md). Since 21.1. ```java public interface ProxyHashMap extends Proxy ``` Extends: [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) Interface to be implemented to mimic guest language hash maps. **See also** - [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) ## Methods ### getHashSize() `long getHashSize()`. Since 21.1. Returns the number of map entries. Cite: `org/graalvm/polyglot/proxy/ProxyHashMap.html#getHashSize()` ### hasHashEntry(Value) `boolean hasHashEntry(Value key)`. Since 21.1. Returns `true` if the proxy object contains a mapping for the specified key, or else `false`. Every key which returns `true` for `hasHashEntry(Value)` must be included in the `iterator` returned by `getHashEntriesIterator()` to allow guest language to enumerate map entries. See also: `getHashEntriesIterator()`. Cite: `org/graalvm/polyglot/proxy/ProxyHashMap.html#hasHashEntry(org.graalvm.polyglot.Value)` ### getHashValue(Value) `Object getHashValue(Value key)`. Since 21.1. Returns the value for the specified key. Throws: `UnsupportedOperationException` (unchecked): if the operation is unsupported. Cite: `org/graalvm/polyglot/proxy/ProxyHashMap.html#getHashValue(org.graalvm.polyglot.Value)` ### putHashEntry(Value, Value) `void putHashEntry(Value key, Value value)`. Since 21.1. Associates the specified value with the specified key. If the mapping for the specified key does not `exist` then a new mapping is defined otherwise, an existing mapping is updated. Throws: `UnsupportedOperationException` (unchecked): if the operation is unsupported. Cite: `org/graalvm/polyglot/proxy/ProxyHashMap.html#putHashEntry(org.graalvm.polyglot.Value,org.graalvm.polyglot.Value)` ### removeHashEntry(Value) `default boolean removeHashEntry(Value key)`. Since 21.1. Removes the mapping for a given key. If the removal of existing mappings is not supported then an [`UnsupportedOperationException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/UnsupportedOperationException.html) is thrown. Returns `boolean`: `true` when the mapping was removed, `false` when the mapping didn't exist. Throws: `UnsupportedOperationException` (unchecked): if the operation is unsupported. Cite: `org/graalvm/polyglot/proxy/ProxyHashMap.html#removeHashEntry(org.graalvm.polyglot.Value)` ### getHashEntriesIterator() `Object getHashEntriesIterator()`. Since 21.1. Returns the hash entries iterator. The returned object must be interpreted as an iterator using the semantics of `Context.asValue(Object)` otherwise an [`IllegalStateException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html) is thrown. The iterator elements must be interpreted as two elements array using the semantics of `Context.asValue(Object)`. Examples for valid return values are: `ProxyIterator`; [`Iterator`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Iterator.html), requires `host iterable access`; A guest language object representing an iterator Examples for valid iterator elements are: `ProxyArray`; [`List`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html), requires `host list access`; `Object[2]`, requires `host array access`; [`Entry`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.Entry.html), requires `host map access`; A guest language object representing an array. See also: `ProxyIterator`. Cite: `org/graalvm/polyglot/proxy/ProxyHashMap.html#getHashEntriesIterator()` ### from(Map) `static ProxyHashMap from(Map values)`. Since 21.1. Creates a proxy hash map backed by a Java [`Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html). The map keys are `as Object unboxed`. If the set values are host values then they will be `unboxed`. Cite: `org/graalvm/polyglot/proxy/ProxyHashMap.html#from(java.util.Map)` # ◇ ProxyInstant [polyglot](index.md) › [org.graalvm.polyglot.proxy](org/graalvm/polyglot/proxy/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.proxy`](org/graalvm/polyglot/proxy/index.md). Since 19.2.0. ```java public interface ProxyInstant extends ProxyDate, ProxyTime, ProxyTimeZone ``` Extends: [`ProxyDate`](org/graalvm/polyglot/proxy/ProxyDate.md), [`ProxyTime`](org/graalvm/polyglot/proxy/ProxyTime.md), [`ProxyTimeZone`](org/graalvm/polyglot/proxy/ProxyTimeZone.md) Interface to be implemented to mimic guest language objects that represents timestamps. This interface also implements [`ProxyDate`](org/graalvm/polyglot/proxy/ProxyDate.md), [`ProxyTime`](org/graalvm/polyglot/proxy/ProxyTime.md) and [`ProxyTimeZone`](org/graalvm/polyglot/proxy/ProxyTimeZone.md). **See also** - [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) - [`Value`](org/graalvm/polyglot/Value.md) ## Methods ### asInstant() `Instant asInstant()`. Since 19.2.0. Returns the instant information. The returned value must not be `null`. The following invariant must always hold for instant proxies: Cite: `org/graalvm/polyglot/proxy/ProxyInstant.html#asInstant()` ```java ProxyInstant proxy = ... ZoneId zone = proxy.getTimeZone(); LocalDate date = proxy.getDate(); LocalTime time = proxy.getTime(); assert ZonedDateTime.of(date, time, zone).equals(proxy.getInstant()); ``` ### asDate() `default LocalDate asDate()`. Since 19.2.0. Returns the date information. The returned value must not be `null`. The invariant specified in `asInstant()` must always hold for proxy instant values. Overrides `asDate()`. See also: `asInstant()`. Cite: `org/graalvm/polyglot/proxy/ProxyInstant.html#asDate()` ### asTime() `default LocalTime asTime()`. Since 19.2.0. Returns the time information. The returned value must not be `null`. The invariant specified in `asInstant()` must always hold for proxy instant values. Overrides `asTime()`. See also: `asInstant()`. Cite: `org/graalvm/polyglot/proxy/ProxyInstant.html#asTime()` ### asTimeZone() `default ZoneId asTimeZone()`. Since 19.2.0. Returns the timezone information. The returned value must not be `null`. The invariant specified in `asInstant()` must always hold for proxy instant values. Overrides `asTimeZone()`. See also: `asInstant()`. Cite: `org/graalvm/polyglot/proxy/ProxyInstant.html#asTimeZone()` ### from(Instant) `static ProxyInstant from(Instant instant)`. Since 19.2.0. Creates a new proxy instant from a Java instant value. Cite: `org/graalvm/polyglot/proxy/ProxyInstant.html#from(java.time.Instant)` # ◇ ProxyInstantiable [polyglot](index.md) › [org.graalvm.polyglot.proxy](org/graalvm/polyglot/proxy/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.proxy`](org/graalvm/polyglot/proxy/index.md). Since 19.0. ```java @FunctionalInterface public interface ProxyInstantiable extends Proxy ``` Extends: [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) Interface to be implemented to mimic guest language objects that are instantiable. **See also** - [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) ## Methods ### newInstance(Value...) `Object newInstance(Value... arguments)`. Since 19.0. Creates a new instance of the object with the given arguments. Throws: `UnsupportedOperationException` (unchecked): if the proxy cannot be instantiated with the given arguments. Cite: `org/graalvm/polyglot/proxy/ProxyInstantiable.html#newInstance(org.graalvm.polyglot.Value...)` # ◇ ProxyIterable [polyglot](index.md) › [org.graalvm.polyglot.proxy](org/graalvm/polyglot/proxy/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.proxy`](org/graalvm/polyglot/proxy/index.md). Since 21.1. ```java public interface ProxyIterable extends Proxy ``` Extends: [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) Interface to be implemented to mimic guest language iterables. **See also** - [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) - [`ProxyIterator`](org/graalvm/polyglot/proxy/ProxyIterator.md) ## Methods ### getIterator() `Object getIterator()`. Since 21.1. Returns an iterator. The returned object must be interpreted as an iterator using the semantics of `Context.asValue(Object)` otherwise an [`IllegalStateException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html) is thrown. Examples for valid return values are: `ProxyIterator`; [`Iterator`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Iterator.html), requires `host iterable access`; A guest language object representing an iterator. See also: `ProxyIterator`. Cite: `org/graalvm/polyglot/proxy/ProxyIterable.html#getIterator()` ### from(Iterable) `static ProxyIterable from(Iterable iterable)`. Since 21.1. Creates a proxy iterable backed by a Java [`Iterable`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Iterable.html). If the values of the iterable are host values then they will be `unboxed`. Cite: `org/graalvm/polyglot/proxy/ProxyIterable.html#from(java.lang.Iterable)` # ◇ ProxyIterator [polyglot](index.md) › [org.graalvm.polyglot.proxy](org/graalvm/polyglot/proxy/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.proxy`](org/graalvm/polyglot/proxy/index.md). Since 21.1. ```java public interface ProxyIterator extends Proxy ``` Extends: [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) Interface to be implemented to mimic guest language iterators. **See also** - [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) - [`ProxyIterable`](org/graalvm/polyglot/proxy/ProxyIterable.md) ## Methods ### hasNext() `boolean hasNext()`. Since 21.1. Returns `true` if the iterator has more elements, else `false`. Multiple calls to the `hasNext()` might lead to different results if the underlying data structure is modified. See also: `getNext()`. Cite: `org/graalvm/polyglot/proxy/ProxyIterator.html#hasNext()` ### getNext() `Object getNext() throws NoSuchElementException, UnsupportedOperationException`. Since 21.1. Returns the next element in the iteration. When the underlying data structure is modified the `getNext()` may throw the [`NoSuchElementException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/NoSuchElementException.html) even when the `hasNext()` returned `true`. Throws: `NoSuchElementException`: if the iteration has no more elements, the `hasNext()` returns `false`. `UnsupportedOperationException`: when the underlying iterator element exists but is not readable. See also: `hasNext()`. Cite: `org/graalvm/polyglot/proxy/ProxyIterator.html#getNext()` ### from(Iterator) `static ProxyIterator from(Iterator iterator)`. Since 21.1. Creates a proxy iterator backed by a Java [`Iterator`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Iterator.html). If the set values are host values then they will be `unboxed`. If the Java [`Iterator`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Iterator.html) throws the [`ConcurrentModificationException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/ConcurrentModificationException.html) the exception is translated into the host exception. Cite: `org/graalvm/polyglot/proxy/ProxyIterator.html#from(java.util.Iterator)` # ◇ ProxyNativeObject [polyglot](index.md) › [org.graalvm.polyglot.proxy](org/graalvm/polyglot/proxy/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.proxy`](org/graalvm/polyglot/proxy/index.md). Since 19.0. ```java public interface ProxyNativeObject extends Proxy ``` Extends: [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) Interface to be implemented to mimic native pointers. **See also** - [`asPointer()`](org/graalvm/polyglot/proxy/ProxyNativeObject.md#asPointer%28%29) ## Methods ### asPointer() `long asPointer()`. Since 19.0. Returns the native pointer value that this object represents. Cite: `org/graalvm/polyglot/proxy/ProxyNativeObject.html#asPointer()` # ◇ ProxyObject [polyglot](index.md) › [org.graalvm.polyglot.proxy](org/graalvm/polyglot/proxy/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.proxy`](org/graalvm/polyglot/proxy/index.md). Since 19.0. ```java public interface ProxyObject extends Proxy ``` Extends: [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) Interface to be implemented to mimic guest language objects that contain members. **See also** - [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) ## Methods ### getMember(String) `Object getMember(String key)`. Since 19.0. Returns the value of the member. Throws: `UnsupportedOperationException` (unchecked): if the operation is unsupported. Cite: `org/graalvm/polyglot/proxy/ProxyObject.html#getMember(java.lang.String)` ### getMemberKeys() `Object getMemberKeys()`. Since 19.0. Returns an array of member keys. The returned array must be interpreted as having array elements using the semantics of `Context.asValue(Object)` and taking host access into consideration. Otherwise, an [`IllegalStateException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/IllegalStateException.html) is thrown. If one of the return values of the array is not a [`String`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html) then a [`ClassCastException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/ClassCastException.html) is thrown. Examples for valid return values are: `null` for no member keys; `ProxyArray` that returns [`String`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html) values for each array element; [`List`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/List.html) with exclusively String elements (`HostAccess` must allowListAccess); [`String[]`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html) (`HostAccess` must allowArrayAccess); A guest language object representing an array of strings. Every member key returned by the `getMemberKeys()` method must return `true` for `hasMember(String)`. See also: `hasMember(String)`, `Context.asValue(Object)`. Cite: `org/graalvm/polyglot/proxy/ProxyObject.html#getMemberKeys()` ### hasMember(String) `boolean hasMember(String key)`. Since 19.0. Returns `true` if the proxy object contains a member with the given key, or else `false`. While not required ever member key which returns `true` for `hasMember(String)` should be returned by `getMemberKeys()` to allow guest members to list member keys. See also: `getMemberKeys()`. Cite: `org/graalvm/polyglot/proxy/ProxyObject.html#hasMember(java.lang.String)` ### putMember(String, Value) `void putMember(String key, Value value)`. Since 19.0. Sets the value associated with a member. If the member does not `exist` then a new member is defined. If the definition of new members is not supported then an [`UnsupportedOperationException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/UnsupportedOperationException.html) is thrown. Throws: `UnsupportedOperationException` (unchecked): if the operation is unsupported. Cite: `org/graalvm/polyglot/proxy/ProxyObject.html#putMember(java.lang.String,org.graalvm.polyglot.Value)` ### removeMember(String) `default boolean removeMember(String key)`. Since 19.0. Removes a member key and its value. If the removal of existing members is not supported then an [`UnsupportedOperationException`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/UnsupportedOperationException.html) is thrown. Returns `boolean`: `true` when the member was removed, `false` when the member didn't exist. Throws: `UnsupportedOperationException` (unchecked): if the operation is unsupported. Cite: `org/graalvm/polyglot/proxy/ProxyObject.html#removeMember(java.lang.String)` ### fromMap(Map) `static ProxyObject fromMap(Map values)`. Since 19.0. Creates a proxy backed by a [`Map`](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Map.html). If the set values of the map are host values then the they will be `unboxed`. Cite: `org/graalvm/polyglot/proxy/ProxyObject.html#fromMap(java.util.Map)` # ◇ ProxyTime [polyglot](index.md) › [org.graalvm.polyglot.proxy](org/graalvm/polyglot/proxy/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.proxy`](org/graalvm/polyglot/proxy/index.md). Since 19.2.0. ```java public interface ProxyTime extends Proxy ``` Extends: [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) Interface to be implemented to mimic guest language objects that represents times. **See also** - [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) - [`Value`](org/graalvm/polyglot/Value.md) ## Methods ### asTime() `LocalTime asTime()`. Since 19.2.0. Returns the time information. The returned value must not be `null`. Cite: `org/graalvm/polyglot/proxy/ProxyTime.html#asTime()` ### from(LocalTime) `static ProxyTime from(LocalTime time)`. Since 19.2.0. Creates a proxy time from a local time. Cite: `org/graalvm/polyglot/proxy/ProxyTime.html#from(java.time.LocalTime)` # ◇ ProxyTimeZone [polyglot](index.md) › [org.graalvm.polyglot.proxy](org/graalvm/polyglot/proxy/index.md) · Every page: [llms.txt](llms.txt) Interface in [`org.graalvm.polyglot.proxy`](org/graalvm/polyglot/proxy/index.md). Since 19.2.0. ```java public interface ProxyTimeZone extends Proxy ``` Extends: [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) Interface to be implemented to mimic guest language objects that represents timezones. **See also** - [`Proxy`](org/graalvm/polyglot/proxy/Proxy.md) - [`Value`](org/graalvm/polyglot/Value.md) ## Methods ### asTimeZone() `ZoneId asTimeZone()`. Since 19.2.0. Returns the timezone information. The returned value must not be `null`. Cite: `org/graalvm/polyglot/proxy/ProxyTimeZone.html#asTimeZone()` ### from(ZoneId) `static ProxyTimeZone from(ZoneId timeZone)`. Since 19.2.0. Creates a proxy timezone from a ZoneId. Cite: `org/graalvm/polyglot/proxy/ProxyTimeZone.html#from(java.time.ZoneId)`