Class Value
host
or guest language. Polyglot
values are bound to a context
. If the context is closed then all value operations
throw an IllegalStateException
.
Polyglot values have one of the following type combinations:
Null
: This value represents anull
like value. Certain languages might use a different name or use multiple values to representnull
like values.Number
: This value represents a floating or fixed point number. The number value may be accessed asbyte
,short
,int
,long
,asBigInteger()
BigInteger},float
, ordouble
value.Boolean
. This value represents a boolean value. The boolean value can be accessed usingasBoolean()
.String
: This value represents a string value. The string value can be accessed usingasString()
.Date
,Time
orTimezone
: This value represents a date, time or timezone. Multiple types may returntrue
at the same time.Duration
: This value represents a duration value. The duration value can be accessed usingasDuration()
.Host Object
: This value represents a value of the host language (Java). The original Java value can be accessed usingasHostObject()
.Proxy Object
: This value represents aproxy
value.Native Pointer
: This value represents a native pointer. The native pointer value can be accessed usingasNativePointer()
.Exception
: This value represents an exception object. The exception can be thrown usingthrowException()
.Meta-Object
: This value represents a metaobject. Access metaobject operations usinggetMetaSimpleName()
,getMetaQualifiedName()
andisMetaInstance(Object)
.Iterator
: This value represents an iterator. The iterator can be iterated usinghasIteratorNextElement()
andgetIteratorNextElement()
.
Array Elements
: This value may contain array elements. The array indices always start with0
, also if the language uses a different style.Members
: 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 usinggetMember(String)
.Executable
: This value can beexecuted
. 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
: This value can beinstantiated
. For example, Java classes are instantiable.Buffer Elements
: This value may contain buffer elements. The buffer indices always start with0
, also if the language uses a different style.Iterable
: This valueprovides
aniterator
which can be used toiterate
value elements. For example, Guest language arrays are iterable.hasHashEntries()
Hash Entries}: This value represents a map.hasMetaParents()
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()
. The identity of value objects is unspecified and should not be relied
upon. For example, multiple calls to getArrayElement(long)
with the same index might
return the same or different instances of Value
. The equality
of
values is based on the identity of the value instance. All values return a human-readable
string
for debugging, formatted by the original language.
Polyglot values may be converted to host objects using as(Class)
. In addition values may
be created from Java values using Context.asValue(Object)
.
Naive and aware dates and times
If a date or time value has a timezone
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 inHostAccess
, 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, such that it is not released automatically.- Since:
- 19.0
- See Also:
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic final class
Enum like class representing the supported string encodings. -
Method Summary
Modifier and TypeMethodDescription<T> T
Maps a polyglot value to a value with a given Java target type.<T> T
as
(TypeLiteral<T> targetType) Maps a polyglot value to a given Java target type literal.boolean
Returns aboolean
representation of this value if it isboolean
.byte
asByte()
asDate()
Returns this value as date if this object represents adate
.double
asDouble()
Returns this value as duration if this object represents aduration
.float
asFloat()
<T> T
Returns the original Java host language object.Returns this value as instant if this object represents aninstant
.int
asInt()
long
asLong()
long
Returns the value of the pointer aslong
value.<T extends Proxy>
TReturns the unboxed instance of theProxy
.short
asShort()
asString()
byte[]
asStringBytes
(Value.StringEncoding encoding) Returns the bytes of a given string value without converting it to a JavaString
.asTime()
Returns this value as time if this object represents atime
.Returns this value as timestamp if this object represents atimezone
.static Value
Converts a Java host value to a polyglot value.boolean
Returnstrue
if the value can beexecuted
.boolean
Returnstrue
if the value can be instantiated.boolean
canInvokeMember
(String identifier) Returnstrue
if the given member exists and can be invoked.boolean
Compares the identity of the underlying polyglot objects.Executes this value if itcan
be executed and returns its result.void
executeVoid
(Object... arguments) Executes this value if itcan
be executed.boolean
boolean
boolean
boolean
boolean
boolean
boolean
static Value
fromByteBasedString
(byte[] bytes, int offset, int length, Value.StringEncoding encoding, boolean copy) Creates a byte-based string value with more granular control over the byte array's usage.static Value
fromByteBasedString
(byte[] bytes, Value.StringEncoding encoding) Creates a byte-based string value that can be passed to polyglot languages.static Value
fromNativeString
(long basePointer, int byteOffset, int byteLength, Value.StringEncoding encoding, boolean copy) Creates a native string object that can be passed to polyglot languages.static Value
fromNativeString
(long basePointer, int byteLength, Value.StringEncoding encoding) Creates a native string object with default safety settings.getArrayElement
(long index) Returns the array element of a given index.long
Returns the array size for values with array elements.long
Returns the buffer size in bytes for values with buffer elements.Returns the context this value was created with.Creates a new hash entries iterator that allows read each map entry.Creates a new hash keys iterator that allows read each map key.long
Returns the number of map entries for values with hash entries.getHashValue
(Object key) Returns the value for the specified key ornull
if the mapping for the specified key does not exist.getHashValueOrDefault
(Object key, Object defaultValue) 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.Creates a new hash values iterator that allows read each map value.Creates a new iterator that allows read each element of a sequence.Returns the next element in the iteration.Returns the member with a givenidentifier
ornull
if the member does not exist.Returns a set of all member keys.Returns the metaobject that is associated with this value ornull
if no metaobject is available.Returns the meta parents of a meta object as an array objecthasArrayElements()
.Returns the qualified name of a metaobject asString
.Returns the simple name of a metaobject asstring
.Returns the declared source location of the value.boolean
Returnstrue
if this polyglot value has array elements.boolean
Returnstrue
if the receiver may have buffer elements.boolean
Returnstrue
if this polyglot value represents a map.boolean
hasHashEntry
(Object key) Returnstrue
if mapping for the specified key exists.int
hashCode()
Returns the identity hash code of the underlying object.boolean
Returnstrue
if this polyglot value provides an iterator.boolean
Returnstrue
if the value represents an iterator which has more elements, elsefalse
.boolean
Returnstrue
if such a member exists for a givenidentifier
.boolean
Returnstrue
if this value generally supports containing members.boolean
Returnstrue
if the value represents a metaobject and the metaobject has meta parents.invokeMember
(String identifier, Object... arguments) Invokes the given member of this value.boolean
Returnstrue
if this value represents a boolean value.boolean
Returns true if the receiver object is a modifiable buffer.boolean
isDate()
Returnstrue
if this object represents a date, elsefalse
.boolean
Returnstrue
if this object represents a duration, elsefalse
.boolean
Returnstrue
if this object represents an exception, elsefalse
.boolean
Returnstrue
if the value originated form the host language Java.boolean
Returnstrue
if this value represents an instant.boolean
Returnstrue
if the value represents an iterator object.boolean
isMetaInstance
(Object instance) Returnstrue
if the given instance is an instance of this value, elsefalse
.boolean
Returnstrue
if the value represents a metaobject.boolean
Returnstrue
if this value is a native pointer.boolean
isNull()
Returnstrue
if this value is anull
like.boolean
isNumber()
boolean
Returnstrue
if this value represents aProxy
.boolean
isString()
Returnstrue
if this value represents a string.boolean
isTime()
Returnstrue
if this object represents a time, elsefalse
.boolean
Returnstrue
if this object represents a timezone, elsefalse
.newInstance
(Object... arguments) Instantiates this value if itcan
be instantiated.void
pin()
Pins a scoped value such that it can be used beyond the scope of a scoped host method call.void
putHashEntry
(Object key, Object value) Associates the specified value with the specified key.void
Sets the value of a member using an identifier.void
readBuffer
(long byteOffset, byte[] destination, int destinationOffset, int length) Reads bytes from the receiver object into the specified byte array.byte
readBufferByte
(long byteOffset) Reads the byte at the given byte offset from the start of the buffer.double
readBufferDouble
(ByteOrder order, long byteOffset) Reads the double at the given byte offset from the start of the buffer in the given byte order.float
readBufferFloat
(ByteOrder order, long byteOffset) Reads the float at the given byte offset from the start of the buffer in the given byte order.int
readBufferInt
(ByteOrder order, long byteOffset) Reads the int at the given byte offset from the start of the buffer in the given byte order.long
readBufferLong
(ByteOrder order, long byteOffset) Reads the long at the given byte offset from the start of the buffer in the given byte order.short
readBufferShort
(ByteOrder order, long byteOffset) Reads the short at the given byte offset from the start of the buffer in the given byte order.boolean
removeArrayElement
(long index) Removes an array element at a given index.boolean
removeHashEntry
(Object key) Removes the mapping for a given key.boolean
removeMember
(String identifier) Removes a single member from the object.void
setArrayElement
(long index, Object value) Sets the value at a given index.Throws this value if this object represents anexception
.toString()
Converts this value to a human readable string.void
writeBufferByte
(long byteOffset, byte value) Writes the given byte at the given byte offset from the start of the buffer.void
writeBufferDouble
(ByteOrder order, long byteOffset, double value) Writes the given double in the given byte order at the given byte offset from the start of the buffer.void
writeBufferFloat
(ByteOrder order, long byteOffset, float value) Writes the given float in the given byte order at the given byte offset from the start of the buffer.void
writeBufferInt
(ByteOrder order, long byteOffset, int value) Writes the given int in the given byte order at the given byte offset from the start of the buffer.void
writeBufferLong
(ByteOrder order, long byteOffset, long value) Writes the given long in the given byte order at the given byte offset from the start of the buffer.void
writeBufferShort
(ByteOrder order, long byteOffset, short value) Writes the given short in the given byte order at the given byte offset from the start of the buffer.
-
Method Details
-
getMetaObject
Returns the metaobject that is associated with this value ornull
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
forisMetaObject()
and provides implementations forgetMetaSimpleName()
,getMetaQualifiedName()
, andisMetaInstance(Object)
.This method does not cause any observable side-effects.
- Throws:
IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 19.0 revised in 20.1
- See Also:
-
isMetaObject
public boolean isMetaObject()Returnstrue
if the value represents a metaobject. Metaobjects may be values that naturally occur in a language or they may be returned bygetMetaObject()
. A metaobject represents a description of the object, reveals its kind and its features. Returnsfalse
by default. Metaobjects are often alsoinstantiable
, but not necessarily.Sample interpretations: In Java an instance of the type
Class
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()
andisMetaInstance(Object)
must be implemented as well.- Throws:
IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 20.1
- See Also:
-
getMetaQualifiedName
Returns the qualified name of a metaobject asString
.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
- if and only ifisMetaObject()
returnsfalse
for the same value.PolyglotException
- if a guest language error occurred during execution.- Since:
- 20.1
-
getMetaSimpleName
Returns the simple name of a metaobject asstring
.Sample interpretations: The simple name of a Java class is the class name.
- Throws:
UnsupportedOperationException
- if and only ifisMetaObject()
returnsfalse
for the same value.PolyglotException
- if a guest language error occurred during execution.- Since:
- 20.1
-
isMetaInstance
Returnstrue
if the given instance is an instance of this value, elsefalse
. The instance value is subject to polyglot value mapping rules as described inContext.asValue(Object)
.Sample interpretations: A Java object is an instance of its returned
class
.- Parameters:
instance
- the instance object to check.- Throws:
UnsupportedOperationException
- if and only ifisMetaObject()
returnsfalse
for the same value.PolyglotException
- if a guest language error occurred during execution.- Since:
- 20.1
-
hasMetaParents
public boolean hasMetaParents()Returnstrue
if the value represents a metaobject and the metaobject has meta parents. Returnsfalse
by default.Sample interpretations: In Java an instance of the type
Class
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
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 22.2
- See Also:
-
getMetaParents
Returns the meta parents of a meta object as an array objecthasArrayElements()
. This method does not cause any observable side-effects. If this method is implemented then alsohasMetaParents()
must be implemented as well.- Throws:
IllegalStateException
- if the context is already closed.UnsupportedOperationException
- if the value does not have anyhasMetaParents()
meta parents.PolyglotException
- if a guest language error occurred during execution.- Since:
- 22.2
- See Also:
-
hasArrayElements
public boolean hasArrayElements()Returnstrue
if this polyglot value has array elements. In this case array elements can be accessed usinggetArrayElement(long)
,setArrayElement(long, Object)
,removeArrayElement(long)
and the array size can be queried usinggetArraySize()
.- Throws:
IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 19.0
-
getArrayElement
Returns the array element of a given index. Polyglot arrays start with index0
, independent of the guest language. The given array index must be greater or equal to 0.- Throws:
ArrayIndexOutOfBoundsException
- if the array index does not exist.UnsupportedOperationException
- if the value does not have anyarray elements
or if the index exists but is not readable.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 19.0
-
setArrayElement
Sets the value at a given index. Polyglot arrays start with index0
, independent of the guest language. The array element value is subject to polyglot value mapping rules as described inContext.asValue(Object)
.- Throws:
ArrayIndexOutOfBoundsException
- if the array index does not exist.ClassCastException
- if the provided value type is not allowed to be written.UnsupportedOperationException
- if the value does not have anyarray elements
or if the index exists but is not modifiable.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 19.0
-
removeArrayElement
public boolean removeArrayElement(long index) Removes an array element at a given index. Returnstrue
if the underlying array element could be removed, otherwisefalse
.- Throws:
ArrayIndexOutOfBoundsException
- if the array index does not exist.UnsupportedOperationException
- if the value does not have anyarray elements
or if the index exists but is not removable.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 19.0
-
getArraySize
public long getArraySize()Returns the array size for values with array elements.- Throws:
UnsupportedOperationException
- if the value does not have anyarray elements
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 19.0
-
hasBufferElements
public boolean hasBufferElements()Returnstrue
if the receiver may have buffer elements. In this case, the buffer size can be queried usinggetBufferSize()
and elements can be read usingreadBufferByte(long)
,readBufferShort(ByteOrder, long)
,readBufferInt(ByteOrder, long)
,readBufferLong(ByteOrder, long)
,readBufferFloat(ByteOrder, long)
andreadBufferDouble(ByteOrder, long)
. IfisBufferWritable()
returnstrue
, then buffer elements can also be written usingwriteBufferByte(long, byte)
,writeBufferShort(ByteOrder, long, short)
,writeBufferInt(ByteOrder, long, int)
,writeBufferLong(ByteOrder, long, long)
,writeBufferFloat(ByteOrder, long, float)
andwriteBufferDouble(ByteOrder, long, double)
.Invoking this method does not cause any observable side-effects.
- Throws:
IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
- See Also:
-
isBufferWritable
Returns true if the receiver object is a modifiable buffer. In this case, elements can be written usingwriteBufferByte(long, byte)
,writeBufferShort(ByteOrder, long, short)
,writeBufferInt(ByteOrder, long, int)
,writeBufferLong(ByteOrder, long, long)
,writeBufferFloat(ByteOrder, long, float)
andwriteBufferDouble(ByteOrder, long, double)
.Invoking this method does not cause any observable side-effects.
- Throws:
UnsupportedOperationException
- if the value does not havebuffer elements
.- Since:
- 21.1
-
getBufferSize
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 havebuffer elements
.- Since:
- 21.1
-
readBufferByte
public byte readBufferByte(long byteOffset) throws UnsupportedOperationException, IndexOutOfBoundsException 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
- the offset, in bytes, from the start of the buffer at which the byte will be read.- Returns:
- the byte at the given byte offset from the start of the buffer.
- Throws:
IndexOutOfBoundsException
- if and only ifbyteOffset < 0 || byteOffset >=
getBufferSize()
.UnsupportedOperationException
- if the value does not havebuffer elements
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
readBuffer
public void readBuffer(long byteOffset, byte[] destination, int destinationOffset, int length) throws UnsupportedOperationException, IndexOutOfBoundsException 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:
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); } }
In case the goal is to read the whole contents into a single byte array, the easiest way is to do that throughByteSequence
:byte[] byteArray = val.as(ByteSequence.class).toByteArray();
- Parameters:
byteOffset
- offset in the buffer to start reading from.destination
- byte array to write the read bytes into.destinationOffset
- offset in the destination array to start writing from.length
- number of bytes to read.- Throws:
IndexOutOfBoundsException
- if and only ifbyteOffset < 0 || length < 0 || byteOffset + length >
getBufferSize()
|| destinationOffset < 0 || destinationOffset + length > destination.length
UnsupportedOperationException
- if the value does not havebuffer elements
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 24.0
-
writeBufferByte
public void writeBufferByte(long byteOffset, byte value) throws UnsupportedOperationException, IndexOutOfBoundsException 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
- the offset, in bytes, from the start of the buffer at which the byte will be written.value
- the byte value to be written.- Throws:
IndexOutOfBoundsException
- if and only ifbyteOffset < 0 || byteOffset >=
getBufferSize()
.UnsupportedOperationException
- if the value does not havebuffer elements
or is notmodifiable
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
readBufferShort
public short readBufferShort(ByteOrder order, long byteOffset) throws UnsupportedOperationException, IndexOutOfBoundsException 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
- the order in which to read the individual bytes of the short.byteOffset
- the offset, in bytes, from the start of the buffer from which the short will be read.- Returns:
- the short at the given byte offset from the start of the buffer.
- Throws:
IndexOutOfBoundsException
- if and only ifbyteOffset < 0 || byteOffset >=
.getBufferSize()
- 1UnsupportedOperationException
- if the value does not havebuffer elements
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
writeBufferShort
public void writeBufferShort(ByteOrder order, long byteOffset, short value) throws UnsupportedOperationException, IndexOutOfBoundsException 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
- the order in which to write the individual bytes of the short.byteOffset
- the offset, in bytes, from the start of the buffer from which the short will be written.value
- the short value to be written.- Throws:
IndexOutOfBoundsException
- if and only ifbyteOffset < 0 || byteOffset >=
.getBufferSize()
- 1UnsupportedOperationException
- if the value does not havebuffer elements
or is notmodifiable
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
readBufferInt
public int readBufferInt(ByteOrder order, long byteOffset) throws UnsupportedOperationException, IndexOutOfBoundsException 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
- the order in which to read the individual bytes of the int.byteOffset
- the offset, in bytes, from the start of the buffer from which the int will be read.- Returns:
- the int at the given byte offset from the start of the buffer.
- Throws:
IndexOutOfBoundsException
- if and only ifbyteOffset < 0 || byteOffset >=
.getBufferSize()
- 3UnsupportedOperationException
- if the value does not havebuffer elements
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
writeBufferInt
public void writeBufferInt(ByteOrder order, long byteOffset, int value) throws UnsupportedOperationException, IndexOutOfBoundsException 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
- the order in which to write the individual bytes of the int.byteOffset
- the offset, in bytes, from the start of the buffer from which the int will be written.value
- the int value to be written.- Throws:
IndexOutOfBoundsException
- if and only ifbyteOffset < 0 || byteOffset >=
.getBufferSize()
- 3UnsupportedOperationException
- if the value does not havebuffer elements
or is notmodifiable
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
readBufferLong
public long readBufferLong(ByteOrder order, long byteOffset) throws UnsupportedOperationException, IndexOutOfBoundsException 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
- the order in which to read the individual bytes of the long.byteOffset
- the offset, in bytes, from the start of the buffer from which the int will be read.- Returns:
- the int at the given byte offset from the start of the buffer.
- Throws:
IndexOutOfBoundsException
- if and only ifbyteOffset < 0 || byteOffset >=
.getBufferSize()
- 7UnsupportedOperationException
- if the value does not havebuffer elements
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
writeBufferLong
public void writeBufferLong(ByteOrder order, long byteOffset, long value) throws UnsupportedOperationException, IndexOutOfBoundsException 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
- the order in which to write the individual bytes of the long.byteOffset
- the offset, in bytes, from the start of the buffer from which the int will be written.value
- the int value to be written.- Throws:
IndexOutOfBoundsException
- if and only ifbyteOffset < 0 || byteOffset >=
.getBufferSize()
- 7UnsupportedOperationException
- if the value does not havebuffer elements
or is notmodifiable
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
readBufferFloat
public float readBufferFloat(ByteOrder order, long byteOffset) throws UnsupportedOperationException, IndexOutOfBoundsException 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
- the order in which to read the individual bytes of the float.byteOffset
- the offset, in bytes, from the start of the buffer from which the float will be read.- Returns:
- the float at the given byte offset from the start of the buffer.
- Throws:
IndexOutOfBoundsException
- if and only ifbyteOffset < 0 || byteOffset >=
.getBufferSize()
- 3UnsupportedOperationException
- if the value does not havebuffer elements
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
writeBufferFloat
public void writeBufferFloat(ByteOrder order, long byteOffset, float value) throws UnsupportedOperationException, IndexOutOfBoundsException 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
- the order in which to read the individual bytes of the float.byteOffset
- the offset, in bytes, from the start of the buffer from which the float will be written.value
- the float value to be written.- Throws:
IndexOutOfBoundsException
- if and only ifbyteOffset < 0 || byteOffset >=
.getBufferSize()
- 3UnsupportedOperationException
- if the value does not havebuffer elements
or is notmodifiable
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
readBufferDouble
public double readBufferDouble(ByteOrder order, long byteOffset) throws UnsupportedOperationException, IndexOutOfBoundsException 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
- the order in which to write the individual bytes of the double.byteOffset
- the offset, in bytes, from the start of the buffer from which the double will be read.- Returns:
- the double at the given byte offset from the start of the buffer.
- Throws:
IndexOutOfBoundsException
- if and only ifbyteOffset < 0 || byteOffset >=
.getBufferSize()
- 7UnsupportedOperationException
- if the value does not havebuffer elements
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
writeBufferDouble
public void writeBufferDouble(ByteOrder order, long byteOffset, double value) throws UnsupportedOperationException, IndexOutOfBoundsException 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
- the order in which to write the individual bytes of the double.byteOffset
- the offset, in bytes, from the start of the buffer from which the double will be written.value
- the double value to be written.- Throws:
IndexOutOfBoundsException
- if and only ifbyteOffset < 0 || byteOffset >=
.getBufferSize()
- 7UnsupportedOperationException
- if the value does not havebuffer elements
or is notmodifiable
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
hasMembers
public boolean hasMembers()Returnstrue
if this value generally supports containing members. To check whether a value has no members use
instead. If polyglot value has members, it may also supportgetMemberKeys()
.isEmpty()
getMember(String)
,putMember(String, Object)
andremoveMember(String)
.- Throws:
IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 19.0
- See Also:
-
hasMember
Returnstrue
if such a member exists for a givenidentifier
. If the value has nomembers
thenhasMember(String)
returnsfalse
.- Throws:
PolyglotException
- if a guest language error occurred during execution.NullPointerException
- if the identifier is null.- Since:
- 19.0
-
getMember
Returns the member with a givenidentifier
ornull
if the member does not exist.- Throws:
UnsupportedOperationException
- if the valuehas no members
or the given identifier exists but is not readable.PolyglotException
- if a guest language error occurred during execution.NullPointerException
- if the identifier is null.- Since:
- 19.0
-
getMemberKeys
Returns a set of all member keys. CallingSet.contains(Object)
with a string key is equivalent to callinghasMember(String)
. Removing an element from the returned set is equivalent to callingremoveMember(String)
. Adding an element to the set is equivalent to calling putMember(key, null). If the value does not supportmembers
then an empty unmodifiable set is returned. If the context gets closed while the returned set is still alive, then the set will throw anIllegalStateException
if any methods except Object methods are invoked.- Throws:
IllegalStateException
- if the context is alreadyclosed
.PolyglotException
- if a guest language error occurred during execution.- Since:
- 19.0
-
putMember
Sets the value of a member using an identifier. The member value is subject to polyglot value mapping rules as described inContext.asValue(Object)
.- Throws:
IllegalStateException
- if the context is alreadyclosed
.UnsupportedOperationException
- if the value does not have anymembers
, the key does not exist and new members cannot be added, or the existing member is not modifiable.IllegalArgumentException
- if the provided value type is not allowed to be written.PolyglotException
- if a guest language error occurred during execution.NullPointerException
- if the identifier is null.- Since:
- 19.0
-
removeMember
Removes a single member from the object. Returnstrue
if the member was successfully removed,false
if such a member does not exist.- Throws:
UnsupportedOperationException
- if the value does not have anymembers
or if the keyexists
but cannot be removed.IllegalStateException
- if the context is alreadyclosed
.PolyglotException
- if a guest language error occurred during execution.NullPointerException
- if the identifier is null.- Since:
- 19.0
-
canExecute
public boolean canExecute()Returnstrue
if the value can beexecuted
.- Throws:
IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
- See Also:
-
execute
Executes this value if itcan
be executed and returns its result. If no result value is expected or needed useexecuteVoid(Object...)
for better performance. All arguments are subject to polyglot value mapping rules as described inContext.asValue(Object)
.- Throws:
IllegalStateException
- if the underlying context was closed.IllegalArgumentException
- if a wrong number of arguments was provided or one of the arguments was not applicable.UnsupportedOperationException
- if this value cannot be executed.PolyglotException
- if a guest language error occurred during execution.NullPointerException
- if the arguments array is null.- Since:
- 19.0
- See Also:
-
executeVoid
Executes this value if itcan
be executed. All arguments are subject to polyglot value mapping rules as described inContext.asValue(Object)
.- Throws:
IllegalStateException
- if the underlying context was closed.IllegalArgumentException
- if a wrong number of arguments was provided or one of the arguments was not applicable.UnsupportedOperationException
- if this value cannot be executed.PolyglotException
- if a guest language error occurred during execution.NullPointerException
- if the arguments array is null.- Since:
- 19.0
- See Also:
-
canInstantiate
public boolean canInstantiate()Returnstrue
if the value can be instantiated. This indicates that thenewInstance(Object...)
can be used with this value. If a value is instantiable it is often also aisMetaObject()
, but this is not a requirement.- Since:
- 19.0
- See Also:
-
newInstance
Instantiates this value if itcan
be instantiated. All arguments are subject to polyglot value mapping rules as described inContext.asValue(Object)
.- Throws:
IllegalStateException
- if the underlying context was closed.IllegalArgumentException
- if a wrong number of arguments was provided or one of the arguments was not applicable.UnsupportedOperationException
- if this value cannot be instantiated.PolyglotException
- if a guest language error occurred during execution.NullPointerException
- if the arguments array is null.- Since:
- 19.0
-
canInvokeMember
Returnstrue
if the given member exists and can be invoked. Returnsfalse
if the member does not exist (hasMember(String)
returnsfalse
), or is not invocable.- Parameters:
identifier
- the member identifier- Throws:
IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred.- Since:
- 19.0
- See Also:
-
invokeMember
Invokes the given member of this value. Unlikeexecute(Object...)
, this is an object oriented execution of a member of an object. To test whether invocation is supported, callcanInvokeMember(String)
. When object oriented semantics are not supported, use
instead.getMember(String)
.execute(Object...)
- Parameters:
identifier
- the member identifier to invokearguments
- the invocation arguments- Throws:
UnsupportedOperationException
- if this member cannot be invoked.PolyglotException
- if a guest language error occurred during invocation.NullPointerException
- if the arguments array is null.- Since:
- 19.0
- See Also:
-
isString
public boolean isString()Returnstrue
if this value represents a string.- Throws:
PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
-
asString
Returns theString
value if this valueis
a string. This method returnsnull
if this value represents anull
value.- Throws:
ClassCastException
- if this value could not be converted to string.UnsupportedOperationException
- if this value does not represent a string.PolyglotException
- if a guest language error occurred during execution.- Since:
- 19.0
-
asStringBytes
Returns the bytes of a given string value without converting it to a JavaString
.This method retrieves the raw bytes of the string in the specified
Value.StringEncoding
, avoiding intermediate conversions to a JavaString
. This is particularly useful for performance-sensitive scenarios where the overhead of creating a JavaString
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
- the desired encoding for the string. Must not benull
. Supported encodings are defined inValue.StringEncoding
.- Returns:
- a byte array containing the string's raw bytes in the specified encoding
- Throws:
NullPointerException
- ifencoding
isnull
IllegalStateException
- if the string value is no longer valid (e.g., the associated context has been closed)- Since:
- 24.2
-
fitsInInt
public boolean fitsInInt()- Throws:
PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
- See Also:
-
asInt
public int asInt()- Throws:
NullPointerException
- if this value representsnull
.ClassCastException
- if this value could not be converted.PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
-
isBoolean
public boolean isBoolean()Returnstrue
if this value represents a boolean value.- Throws:
PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
- See Also:
-
asBoolean
public boolean asBoolean()Returns aboolean
representation of this value if it isboolean
.- Throws:
NullPointerException
- if this value representsnull
ClassCastException
- if this value could not be converted.PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
-
isNumber
public boolean isNumber()Returnstrue
if this value represents anumber
, elsefalse
. The number value may be accessed asbyte
,short
int
long
,float
ordouble
value.- Throws:
PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
-
fitsInLong
public boolean fitsInLong()- Throws:
PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
- See Also:
-
asLong
public long asLong()- Throws:
NullPointerException
- if this value representsnull
.ClassCastException
- if this value could not be converted to long.PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
-
fitsInBigInteger
public boolean fitsInBigInteger()- Throws:
PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 23.0
- See Also:
-
asBigInteger
- Throws:
NullPointerException
- if this value representsnull
.ClassCastException
- if this value could not be converted to BigInteger.PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 23.0
-
fitsInDouble
public boolean fitsInDouble()- Throws:
PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
- See Also:
-
asDouble
public double asDouble()- Throws:
NullPointerException
- if this value representsnull
.ClassCastException
- if this value could not be converted.PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
-
fitsInFloat
public boolean fitsInFloat()- Throws:
PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
- See Also:
-
asFloat
public float asFloat()- Throws:
NullPointerException
- if this value representsnull
.ClassCastException
- if this value could not be converted.PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
-
fitsInByte
public boolean fitsInByte()- Throws:
PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
- See Also:
-
asByte
public byte asByte()- Throws:
NullPointerException
- if this value representsnull
.ClassCastException
- if this value could not be converted.PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
-
fitsInShort
public boolean fitsInShort()- Throws:
PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
- See Also:
-
asShort
public short asShort()- Throws:
NullPointerException
- if this value representsnull
.ClassCastException
- if this value could not be converted.PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
-
isNull
public boolean isNull()Returnstrue
if this value is anull
like.- Throws:
PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
-
isNativePointer
public boolean isNativePointer()Returnstrue
if this value is a native pointer. The value of the pointer can be accessed usingasNativePointer()
.- Throws:
PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
-
asNativePointer
public long asNativePointer()Returns the value of the pointer aslong
value.- Throws:
UnsupportedOperationException
- if the value is not a pointer.PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
-
isHostObject
public boolean isHostObject()Returnstrue
if the value originated form the host language Java. In such a case the value can be accessed usingasHostObject()
.- Throws:
PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
-
asHostObject
public <T> T asHostObject()Returns the original Java host language object.- Throws:
UnsupportedOperationException
- ifisHostObject()
isfalse
.PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
-
isProxyObject
public boolean isProxyObject()Returnstrue
if this value represents aProxy
. The proxy instance can be unboxed usingasProxyObject()
.- Throws:
PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
-
asProxyObject
Returns the unboxed instance of theProxy
. Proxies are not automatically boxed tohost objects
on host language call boundaries (Java methods).- Throws:
UnsupportedOperationException
- if a value is not a proxy object.PolyglotException
- if a guest language error occurred during execution.IllegalStateException
- if the underlying context was closed.- Since:
- 19.0
-
as
public <T> T as(Class<T> targetType) throws ClassCastException, IllegalStateException, PolyglotException 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 theHostAccess
configuration with precedenceHostAccess.TargetMappingPrecedence.HIGHEST
orHostAccess.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.
is always supported and returns this instance.Value
.class- If the value represents a
host object
then all classes implemented or extended by the host object can be used as target type.
is supported if the value is aString
.classstring
.
is supported if the value is aCharacter
.classstring
of length one or if a number can be safely be converted to a character.
is supported if the value is aNumber
.classnumber
.Byte
,Short
,Integer
,Long
,Float
andDouble
are allowed if they fit without conversion. If a conversion is necessary then aClassCastException
is thrown. Primitive class literals throw aNullPointerException
if the value representsnull
.
is supported if the value is aBoolean
.classboolean
. Primitiveboolean.class
literal is also supported. The primitive class literal throws aNullPointerException
if the value representsnull
.
is supported if the value is aLocalDate
.classdate
is supported if the value is aLocalTime
.classtime
is supported if the value is aLocalDateTime
.classdate
andtime
.
is supported if the value is anInstant
.classinstant
.
is supported if the value is aZonedDateTime
.classdate
,time
andtimezone
.
is supported if the value is aZoneId
.classtimezone
.
is supported if the value is aDuration
.classduration
.
is supported if the value is anPolyglotException
.classexception object
.- Any Java type in the type hierarchy of a
host object
. - Custom
target type mappings
specified in theHostAccess
configuration with precedenceHostAccess.TargetMappingPrecedence.LOW
.
is always supported. See section Object mapping rules.Object
.class
is supported ifMap
.classHostAccess.MutableTargetMapping.MEMBERS_TO_JAVA_MAP
respectivelyHostAccess.MutableTargetMapping.HASH_TO_JAVA_MAP
areallowed
and the value hashasHashEntries()
hash entries},members
orarray elements
. The returned map can be safely cast to Map<Object, Object>. For value withmembers
the key type isString
. For value witharray elements
the key type isLong
. It is recommended to usetype literals
to specify the expected collection component types. With type literals the value type can be restricted, for example toMap<String, String>
. If the raw
or an Object component type is used, then the return types of the the list are subject to Object target type mapping rules recursively.Map
.class
is supported ifList
.classHostAccess.MutableTargetMapping.ARRAY_TO_JAVA_LIST
isallowed
and the value hasarray elements
and it has anarray size
that is smaller or equal toInteger.MAX_VALUE
. The returned list can be safely cast toList<Object>
. It is recommended to usetype literals
to specify the expected component type. With type literals the value type can be restricted to any supported target type, for example toList<Integer>
. If the raw
or an Object component type is used, then the return types of the the list are recursively subject to Object target type mapping rules.List
.class
is supported if the value hasByteSequence
.classbuffer elements
and it has abuffer size
that is smaller or equal toInteger.MAX_VALUE
.byte[].class
is supported if the value hasbuffer elements
and it has abuffer size
that is smaller or equal to
. The contents of the buffer will be copied to a new byte array with appropriate size.Integer.MAX_VALUE
- 8- 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.
is supported ifIterable
.classHostAccess.MutableTargetMapping.ITERATOR_TO_JAVA_ITERATOR
isallowed
and the value has aniterator
. The returned iterable can be safely cast toIterable<Object>
. It is recommended to usetype literals
to specify the expected component type. With type literals the value type can be restricted to any supported target type, for example toIterable<Integer>
.
is supported ifIterator
.classHostAccess.MutableTargetMapping.ITERATOR_TO_JAVA_ITERATOR
isallowed
and the value is aniterator
The returned iterator can be safely cast toIterator<Object>
. It is recommended to usetype literals
to specify the expected component type. With type literals the value type can be restricted to any supported target type, for example toIterator<Integer>
. If the raw
or an Object component type is used, then the return types of the the iterator are recursively subject to Object target type mapping rules. The returned iterator'sIterator
.classnext
method may throw aConcurrentModificationException
when an underlying iterable has changed orUnsupportedOperationException
when the iterator's current element is not readable.- Any
functional
interface ifHostAccess.MutableTargetMapping.EXECUTABLE_TO_JAVA_INTERFACE
isallowed
and the value can beexecuted
orinstantiated
and the interface type isimplementable
. Note thatFunctionalInterface
are implementable by default in with theexplicit
host access policy. In case a value can be executed and instantiated then the returned implementation of the interface will beexecuted
. The coercion to the parameter types of functional interface method is converted using the semantics ofas(Class)
. If a standard functional interface likeFunction
is used, it is recommended to usetype literals
to specify the expected generic method parameter and return type. - Any interface if the value
has members
and the interface type isimplementable
andHostAccess.MutableTargetMapping.MEMBERS_TO_JAVA_INTERFACE
isallowed
. Each interface method maps to onemember
of the value. Whenever a method of the interface is executed a member with the method or field name must exist otherwise anUnsupportedOperationException
is thrown when the method is executed. If one of the parameters or the return value cannot be mapped to the target type aClassCastException
or aNullPointerException
is thrown. - JVM only: Any abstract class with an accessible default constructor if the value
has members
and the class isimplementable
. Each interface method maps to onemember
of the value. Whenever an abstract method of the class is executed a member with the method or field name must exist otherwise anUnsupportedOperationException
is thrown when the method is executed. If one of the parameters or the return value cannot be mapped to the target type aClassCastException
or aNullPointerException
is thrown. - Custom
target type mappings
specified in theHostAccess
configuration with precedenceHostAccess.TargetMappingPrecedence.LOWEST
.
ClassCastException
is thrown for other unsupported target types.JavaScript Usage Examples:
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<String, Object>) 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<String> 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;
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
thennull
is returned. - If the value is a
host object
then the value is coerced tohost object value
. - If the value is a
string
then the value is coerced toString
orCharacter
. - If the value is a
boolean
then the value is coerced toBoolean
. - If the value is a
number
then the value is coerced toNumber
. The specific sub type of theNumber
is not specified. Users need to be prepared for any Number subclass includingBigInteger
orBigDecimal
. It is recommended to cast toNumber
and then convert to a Java primitive like withNumber.longValue()
. - If the value has
array elements
and it has anarray size
that is smaller or equal thanInteger.MAX_VALUE
then the result value will implementList
. 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 implementFunction
if the value can beexecuted
orinstantiated
. - If the value has
hash entries
then the result value will implementMap
. Thesize
of the returnedMap
is equal to thehash entries count
. The returned value may also implementFunction
if the value can beexecuted
orinstantiated
. - If the value
has members
then the result value will implementMap
. If this valuehas members
then all members are accessible usingString
keys. Thesize
of the returnedMap
is equal to the count of all members. The returned value may also implementFunction
if the value can beexecuted
orinstantiated
. - If the value has an
hasIterator()
iterator} then the result value will implementIterable
. The returned value may also implementFunction
if the value can beexecuted
orinstantiated
. - If the value is an
isIterator()
iterator} then the result value will implementIterator
. The returned value may also implementFunction
if the value can beexecuted
orinstantiated
. - If the value can be
executed
orinstantiated
then the result value implementsFunction
. By default the argument of the function will be used as single argument to the function when executed. If a value of typeObject[]
is provided then the function will be executed with those arguments. The returned function may also implementList
orMap
if the value hasarray elements
ormembers
, respectively. - Mappings to mutable target types such as
List
,Map
,Iterator
andIterable
are only available if the corresponding mappings are enabled (seeHostAccess.Builder.allowMutableTargetMappings(org.graalvm.polyglot.HostAccess.MutableTargetMapping...)
). - If none of the above rules apply then this
Value
instance is returned.
host objects
,String
,Number
,Boolean
andnull
values have unlimited lifetime. Other values will throw anIllegalStateException
for any operation if their originatingcontext
was closed.If a
Map
element is modified, aList
element is modified or aFunction
argument is provided then these values are interpreted according to thehost to polyglot value mapping rules
.JavaScript Usage Examples:
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<Object, Object>) context.eval("js", "[{}]").as(Object.class)).get(0) instanceof Map; assert context.eval("js", "(function(){})").as(Object.class) instanceof Function;
Object Identity
If polyglot values are mapped as Java primitives such as
Boolean
,null
,String
,Character
orNumber
, then the identity of the polyglot value is not preserved. All other results can be converted back to apolyglot value
usingContext.asValue(Object)
. Mapping Example using JavaScript: This example first creates a new JavaScript object and maps it to aMap
. Using theContext.asValue(Object)
it is possible to recreate thepolyglot value
from the Java map. The JavaScript object identity is preserved in the process.Context context = Context.create(); Map<Object, Object> javaMap = context.eval("js", "{}").as(Map.class); Value polyglotValue = context.asValue(javaMap);
- Parameters:
targetType
- 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
- if the target type is null.- Since:
- 19.0
- See Also:
- Custom
-
as
Maps a polyglot value to a given Java target type literal. For usage instructions seeTypeLiteral
.Usage example:
static final TypeLiteral<List<String>> STRING_LIST = new TypeLiteral<List<String>>() { }; public static void main(String[] args) { Context context = Context.create(); List<String> javaList = context.eval("js", "['foo', 'bar', 'bazz']").as(STRING_LIST); assert javaList.get(0).equals("foo"); }
- Throws:
NullPointerException
- if the target type is null.- Since:
- 19.0
- See Also:
-
toString
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 itsidentity hash code
is used as string representation.- Since:
- 19.0
-
getSourceLocation
Returns the declared source location of the value.- Returns:
- the
SourceSection
or null if unknown - Since:
- 19.0
-
isDate
public boolean isDate()Returnstrue
if this object represents a date, elsefalse
. If this value is also atimezone
then the date is aware, otherwise it is naive.- Throws:
ClassCastException
- if polyglot value could not be mapped to the target type.NullPointerException
- if the target type is null.PolyglotException
- if the conversion triggered a guest language error.IllegalStateException
- if the underlying context is already closed.- Since:
- 19.2.0
- See Also:
-
asDate
Returns this value as date if this object represents adate
. The returned date is either aware if the value has atimezone
otherwise it is naive.- Throws:
ClassCastException
- if polyglot value could not be mapped to the target type.NullPointerException
- if the target type is null.PolyglotException
- if the conversion triggered a guest language error.IllegalStateException
- if the underlying context is already closed.- Since:
- 19.2.0
- See Also:
-
isTime
public boolean isTime()Returnstrue
if this object represents a time, elsefalse
. If the value is also atimezone
then the time is aware, otherwise it is naive.- Throws:
IllegalStateException
- if the underlying context is already closed.- Since:
- 19.2.0
- See Also:
-
asTime
Returns this value as time if this object represents atime
. The returned time is either aware if the value has atimezone
otherwise it is naive.- Throws:
ClassCastException
- if polyglot value could not be mapped to the target type.NullPointerException
- if the target type is null.PolyglotException
- if the conversion triggered a guest language error.IllegalStateException
- if the underlying context is already closed.- Since:
- 19.2.0
- See Also:
-
isInstant
public boolean isInstant()Returnstrue
if this value represents an instant. If a value is an instant then it is also adate
,time
andtimezone
. This method is short-hand for:v.isDate() && v.
isTime
() && v.isTimeZone
()- Throws:
IllegalStateException
- if the underlying context is already closed.- Since:
- 19.2.0
- See Also:
-
asInstant
Returns this value as instant if this object represents aninstant
. If a value is an instant then it is also adate
,time
andtimezone
. 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()
returnstrue
:ZoneId zone = getTimeZone(receiver); LocalDate date = getDate(receiver); LocalTime time = getTime(receiver); assert ZonedDateTime.of(date, time, zone).toInstant().equals(getInstant(receiver));
- Throws:
ClassCastException
- if polyglot value could not be mapped to the target type.NullPointerException
- if the target type is null.PolyglotException
- if the conversion triggered a guest language error.IllegalStateException
- if the underlying context is already closed.- Since:
- 19.2.0
- See Also:
-
isTimeZone
public boolean isTimeZone()Returnstrue
if this object represents a timezone, elsefalse
. The interpretation of timezone objects may vary:- If
isDate()
andisTime()
returntrue
, then the returned date or time information is aware of this timezone. - If
isDate()
andisTime()
returnsfalse
, then it represents just timezone information.
fixed zone
only. If this rule is violated then anAssertionError
is thrown if assertions are enabled.If this method is implemented then also
asTimeZone()
must be implemented.- Throws:
IllegalStateException
- if the underlying context is already closed.- Since:
- 19.2.0
- See Also:
- If
-
asTimeZone
Returns this value as timestamp if this object represents atimezone
.- 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
- if the target type is null.- Since:
- 19.2.0
- See Also:
-
isDuration
public boolean isDuration()Returnstrue
if this object represents a duration, elsefalse
.- Throws:
IllegalStateException
- if the underlying context is already closed.- Since:
- 19.2.0
- See Also:
-
asDuration
Returns this value as duration if this object represents aduration
.- 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
- if the target type is null.- Since:
- 19.2.0
- See Also:
-
isException
public boolean isException()Returnstrue
if this object represents an exception, elsefalse
.- Throws:
IllegalStateException
- if the underlying context is already closed.- Since:
- 19.3
- See Also:
-
throwException
Throws this value if this object represents anexception
.- Throws:
UnsupportedOperationException
- if the value is not an exception.IllegalStateException
- if the underlying context is already closed.- Since:
- 19.3
- See Also:
-
getContext
Returns the context this value was created with. The returned context may benull
if the value was created usingasValue(Object)
and no current context wasentered
at the time.The returned context can not be used to
enter
,leave
orclose
the context orengine
. Invoking such methods will cause anIllegalStateException
to be thrown. This ensures that only thecreator
of a context is allowed to enter, leave or close a context and that a context is not closed while it is still active.- Since:
- 19.3.0
-
equals
Compares the identity of the underlying polyglot objects. This method does not do any structural comparisons.- Since:
- 20.1
-
hashCode
public int hashCode()Returns the identity hash code of the underlying object. This method does not compute the hash code depending on the contents of the value.- Since:
- 20.1
-
hasIterator
public boolean hasIterator()Returnstrue
if this polyglot value provides an iterator. In this case the iterator can be obtained usinggetIterator()
.- Throws:
IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
- See Also:
-
getIterator
Creates a new iterator that allows read each element of a sequence.- Throws:
UnsupportedOperationException
- if the value does not provideiterator
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
- See Also:
-
isIterator
public boolean isIterator()Returnstrue
if the value represents an iterator object. In this case the iterator elements can be accessed usinggetIteratorNextElement()
.- Throws:
IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
- See Also:
-
hasIteratorNextElement
public boolean hasIteratorNextElement()Returnstrue
if the value represents an iterator which has more elements, elsefalse
. Multiple calls to thehasIteratorNextElement()
might lead to different results if the underlying data structure is modified.- Throws:
UnsupportedOperationException
- if the value is not aniterator
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
- See Also:
-
getIteratorNextElement
Returns the next element in the iteration. When the underlying data structure is modified thegetIteratorNextElement()
may throw theNoSuchElementException
despite thehasIteratorNextElement()
returnedtrue
, or it may throw a language error.- Throws:
UnsupportedOperationException
- if the value is not aniterator
or when the underlying iterable element exists but is not readable.NoSuchElementException
- if the iteration has no more elements. Even if theNoSuchElementException
was thrown it might not be thrown again by a next call of thegetIteratorNextElement()
due to a modification of an underlying iterable.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
- See Also:
-
hasHashEntries
public boolean hasHashEntries()Returnstrue
if this polyglot value represents a map. In this case map entries can be accessed usinggetHashValue(Object)
,getHashValueOrDefault(Object, Object)
,putHashEntry(Object, Object)
,removeHashEntry(Object)
,getHashEntriesIterator()
and the map size can be queried usinggetHashSize()
.- Throws:
IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
getHashSize
Returns the number of map entries for values with hash entries.- Throws:
UnsupportedOperationException
- if the value does not have anyhasHashEntries()
hash entries}.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
hasHashEntry
Returnstrue
if mapping for the specified key exists. If the value has nohash entries
thenhasHashEntry(Object)
returnsfalse
. The key is subject to polyglot value mapping rules as described inContext.asValue(Object)
.- Throws:
IllegalStateException
- if the context is alreadyclosed
.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
getHashValue
Returns the value for the specified key ornull
if the mapping for the specified key does not exist. The key is subject to polyglot value mapping rules as described inContext.asValue(Object)
.- Throws:
UnsupportedOperationException
- if the value has nohash entries
or the mapping for given key exists but is not readable.IllegalStateException
- if the context is alreadyclosed
.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
getHashValueOrDefault
public Value getHashValueOrDefault(Object key, Object defaultValue) throws UnsupportedOperationException 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 inContext.asValue(Object)
.- Throws:
UnsupportedOperationException
- if the value has nohash entries
at all.IllegalStateException
- if the context is alreadyclosed
.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
putHashEntry
public void putHashEntry(Object key, Object value) throws IllegalArgumentException, UnsupportedOperationException Associates the specified value with the specified key. Both key and value are subject to polyglot value mapping rules as described inContext.asValue(Object)
.- Throws:
UnsupportedOperationException
- if the value does not have anyhash 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
- if the context is alreadyclosed
.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
removeHashEntry
Removes the mapping for a given key. Returnstrue
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 inContext.asValue(Object)
.- Throws:
UnsupportedOperationException
- if the value does not have anyhash entries
or if mapping for specified keyexists
but cannot be removed.IllegalStateException
- if the context is alreadyclosed
.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
getHashEntriesIterator
Creates a new hash entries iterator that allows read each map entry. The return value is always aniterator
ofarray elements
. The first array element is a key, the second array element is an associated value. Even if the value array element ismodifiable
writing to array may not update the mapping, always useputHashEntry(Object, Object)
to update the mapping.- Throws:
UnsupportedOperationException
- if the value does not have anyhash entries
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
getHashKeysIterator
Creates a new hash keys iterator that allows read each map key. The return value is always aniterator
.- Throws:
UnsupportedOperationException
- if the value does not have anyhash entries
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
getHashValuesIterator
Creates a new hash values iterator that allows read each map value. The return value is always aniterator
.- Throws:
UnsupportedOperationException
- if the value does not have anyhash entries
.IllegalStateException
- if the context is already closed.PolyglotException
- if a guest language error occurred during execution.- Since:
- 21.1
-
asValue
Converts a Java host value to a polyglot value. Returns a value for any host or guest value. If there is a context available useContext.asValue(Object)
for efficiency instead. The value is bound thecurrent
context when created. If there is no context available when the value was constructed then Values constructed with this method may returnnull
forgetContext()
.- Parameters:
o
- the object to convert- Throws:
IllegalStateException
- if no context is currently entered.- Since:
- 19.0
- See Also:
-
pin
public void pin()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 aIllegalStateException
.- Throws:
IllegalStateException
- if the method scope of the value was finished- Since:
- 21.3
- See Also:
-
fromByteBasedString
Creates a byte-based string value that can be passed to polyglot languages.The returned value is guaranteed to return
Performance Note: Copying the byte array can have a performance impact. Use this method when immutability is required, or use the more flexible overloaded methodtrue
forisString()
. The string can later be retrieved as a byte array usingasStringBytes(StringEncoding)
. This method ensures immutability by conservatively copying the byte array before passing it to the underlying implementation.fromByteBasedString(byte[], int, int, StringEncoding, boolean)
to control copying behavior.- Parameters:
bytes
- the byte array representing the stringencoding
- the encoding of the byte array- Returns:
- a polyglot string
Value
- Throws:
NullPointerException
- if eitherbytes
orencoding
is null- Since:
- 24.2
-
fromByteBasedString
public static Value fromByteBasedString(byte[] bytes, int offset, int length, Value.StringEncoding encoding, boolean copy) 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
- the byte array representing the stringoffset
- the starting offset in the byte arraylength
- the number of bytes to include starting fromoffset
encoding
- the encoding of the byte arraycopy
- whether to copy the byte array to ensure immutability- Returns:
- a polyglot string
Value
- Since:
- 24.2
-
fromNativeString
public static Value fromNativeString(long basePointer, int byteOffset, int byteLength, Value.StringEncoding encoding, boolean copy) 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 returntrue
forisString()
.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
- the raw base pointer to the native string in memorybyteLength
- the length of the string in bytesencoding
- the encoding of the native stringcopy
- whether to copy the native string bytes for additional safety- Returns:
- a polyglot string
Value
- Since:
- 24.2
-
fromNativeString
public static Value fromNativeString(long basePointer, int byteLength, Value.StringEncoding encoding) Creates a native string object with default safety settings.This method is equivalent to calling
fromNativeString(long, int, int, StringEncoding, boolean)
withcopy
set totrue
.- Parameters:
basePointer
- the raw base pointer to the native string in memorybyteLength
- the length of the string in bytesencoding
- the encoding of the native string- Returns:
- a polyglot string
Value
- Since:
- 24.2
-