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 anulllike value. Certain languages might use a different name or use multiple values to representnulllike values.Number: This value represents a floating or fixed point number. The number value may be accessed asbyte,short,int,long,asBigInteger()BigInteger},float, ordoublevalue.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,TimeorTimezone: This value represents a date, time or timezone. Multiple types may returntrueat 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 aproxyvalue.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 valueprovidesaniteratorwhich can be used toiteratevalue 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
Nested ClassesModifier and TypeClassDescriptionstatic final classEnum like class representing the supported string encodings. -
Method Summary
Modifier and TypeMethodDescription<T> TMaps a polyglot value to a value with a given Java target type.<T> Tas(TypeLiteral<T> targetType) Maps a polyglot value to a given Java target type literal.booleanReturns abooleanrepresentation of this value if it isboolean.byteasByte()asDate()Returns this value as date if this object represents adate.doubleasDouble()Returns this value as duration if this object represents aduration.floatasFloat()<T> TReturns the original Java host language object.Returns this value as instant if this object represents aninstant.intasInt()longasLong()longReturns the value of the pointer aslongvalue.<T extends Proxy>
TReturns the unboxed instance of theProxy.shortasShort()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 ValueConverts a Java host value to a polyglot value.booleanReturnstrueif the value can beexecuted.booleanReturnstrueif the value can be instantiated.booleancanInvokeMember(String identifier) Returnstrueif the given member exists and can be invoked.booleanCompares the identity of the underlying polyglot objects.Executes this value if itcanbe executed and returns its result.voidexecuteVoid(Object... arguments) Executes this value if itcanbe executed.booleanbooleanbooleanbooleanbooleanbooleanbooleanstatic ValuefromByteBasedString(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 ValuefromByteBasedString(byte[] bytes, Value.StringEncoding encoding) Creates a byte-based string value that can be passed to polyglot languages.static ValuefromNativeString(long basePointer, int byteOffset, int byteLength, Value.StringEncoding encoding, boolean copy) Creates a native string object that can be passed to polyglot languages.static ValuefromNativeString(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.longReturns the array size for values with array elements.longReturns 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.longReturns the number of map entries for values with hash entries.getHashValue(Object key) Returns the value for the specified key ornullif 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 givenidentifierornullif the member does not exist.Returns a set of all member keys.Returns the metaobject that is associated with this value ornullif 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.booleanReturnstrueif this polyglot value has array elements.booleanReturnstrueif the receiver may have buffer elements.booleanReturnstrueif this polyglot value represents a map.booleanhasHashEntry(Object key) Returnstrueif mapping for the specified key exists.inthashCode()Returns the identity hash code of the underlying object.booleanReturnstrueif this polyglot value provides an iterator.booleanReturnstrueif the value represents an iterator which has more elements, elsefalse.booleanReturnstrueif such a member exists for a givenidentifier.booleanReturnstrueif this value generally supports containing members.booleanReturnstrueif the value represents a metaobject and the metaobject has meta parents.invokeMember(String identifier, Object... arguments) Invokes the given member of this value.booleanReturnstrueif this value represents a boolean value.booleanReturns true if the receiver object is a modifiable buffer.booleanisDate()Returnstrueif this object represents a date, elsefalse.booleanReturnstrueif this object represents a duration, elsefalse.booleanReturnstrueif this object represents an exception, elsefalse.booleanReturnstrueif the value originated form the host language Java.booleanReturnstrueif this value represents an instant.booleanReturnstrueif the value represents an iterator object.booleanisMetaInstance(Object instance) Returnstrueif the given instance is an instance of this value, elsefalse.booleanReturnstrueif the value represents a metaobject.booleanReturnstrueif this value is a native pointer.booleanisNull()Returnstrueif this value is anulllike.booleanisNumber()booleanReturnstrueif this value represents aProxy.booleanisString()Returnstrueif this value represents a string.booleanisTime()Returnstrueif this object represents a time, elsefalse.booleanReturnstrueif this object represents a timezone, elsefalse.newInstance(Object... arguments) Instantiates this value if itcanbe instantiated.voidpin()Pins a scoped value such that it can be used beyond the scope of a scoped host method call.voidputHashEntry(Object key, Object value) Associates the specified value with the specified key.voidSets the value of a member using an identifier.voidreadBuffer(long byteOffset, byte[] destination, int destinationOffset, int length) Reads bytes from the receiver object into the specified byte array.bytereadBufferByte(long byteOffset) Reads the byte at the given byte offset from the start of the buffer.doublereadBufferDouble(ByteOrder order, long byteOffset) Reads the double at the given byte offset from the start of the buffer in the given byte order.floatreadBufferFloat(ByteOrder order, long byteOffset) Reads the float at the given byte offset from the start of the buffer in the given byte order.intreadBufferInt(ByteOrder order, long byteOffset) Reads the int at the given byte offset from the start of the buffer in the given byte order.longreadBufferLong(ByteOrder order, long byteOffset) Reads the long at the given byte offset from the start of the buffer in the given byte order.shortreadBufferShort(ByteOrder order, long byteOffset) Reads the short at the given byte offset from the start of the buffer in the given byte order.booleanremoveArrayElement(long index) Removes an array element at a given index.booleanremoveHashEntry(Object key) Removes the mapping for a given key.booleanremoveMember(String identifier) Removes a single member from the object.voidsetArrayElement(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.voidwriteBufferByte(long byteOffset, byte value) Writes the given byte at the given byte offset from the start of the buffer.voidwriteBufferDouble(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.voidwriteBufferFloat(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.voidwriteBufferInt(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.voidwriteBufferLong(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.voidwriteBufferShort(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 ornullif 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
trueforisMetaObject()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()Returnstrueif 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. Returnsfalseby default. Metaobjects are often alsoinstantiable, but not necessarily.Sample interpretations: In Java an instance of the type
Classis 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 nameinstead.- Throws:
UnsupportedOperationException- if and only ifisMetaObject()returnsfalsefor 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()returnsfalsefor the same value.PolyglotException- if a guest language error occurred during execution.- Since:
- 20.1
-
isMetaInstance
Returnstrueif 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()returnsfalsefor the same value.PolyglotException- if a guest language error occurred during execution.- Since:
- 20.1
-
hasMetaParents
public boolean hasMetaParents()Returnstrueif the value represents a metaobject and the metaobject has meta parents. Returnsfalseby default.Sample interpretations: In Java an instance of the type
Classis 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()Returnstrueif 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 elementsor 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 elementsor 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. Returnstrueif 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 elementsor 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()Returnstrueif 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.lengthUnsupportedOperationException- 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 elementsor 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 elementsor 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 elementsor 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 elementsor 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 elementsor 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 elementsor 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()Returnstrueif this value generally supports containing members. To check whether a value has no members useinstead. 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
Returnstrueif such a member exists for a givenidentifier. If the value has nomembersthenhasMember(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 givenidentifierornullif the member does not exist.- Throws:
UnsupportedOperationException- if the valuehas no membersor 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 supportmembersthen an empty unmodifiable set is returned. If the context gets closed while the returned set is still alive, then the set will throw anIllegalStateExceptionif 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. Returnstrueif the member was successfully removed,falseif such a member does not exist.- Throws:
UnsupportedOperationException- if the value does not have anymembersor if the keyexistsbut 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()Returnstrueif the value can beexecuted.- Throws:
IllegalStateException- if the underlying context was closed.- Since:
- 19.0
- See Also:
-
execute
Executes this value if itcanbe 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 itcanbe 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()Returnstrueif 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 itcanbe 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
Returnstrueif the given member exists and can be invoked. Returnsfalseif 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, useinstead.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()Returnstrueif 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 theStringvalue if this valueisa string. This method returnsnullif this value represents anullvalue.- 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 JavaStringis 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- ifencodingisnullIllegalStateException- 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()Returnstrueif 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 abooleanrepresentation of this value if it isboolean.- Throws:
NullPointerException- if this value representsnullClassCastException- 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()Returnstrueif this value represents anumber, elsefalse. The number value may be accessed asbyte,shortintlong,floatordoublevalue.- 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()Returnstrueif this value is anulllike.- Throws:
PolyglotException- if a guest language error occurred during execution.IllegalStateException- if the underlying context was closed.- Since:
- 19.0
-
isNativePointer
public boolean isNativePointer()Returnstrueif 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 aslongvalue.- 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()Returnstrueif 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()Returnstrueif 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 objectson 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 mappingsspecified in theHostAccessconfiguration with precedenceHostAccess.TargetMappingPrecedence.HIGHESTorHostAccess.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 objectthen 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.classstringof 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,FloatandDoubleare allowed if they fit without conversion. If a conversion is necessary then aClassCastExceptionis thrown. Primitive class literals throw aNullPointerExceptionif the value representsnull.is supported if the value is aBoolean.classboolean. Primitiveboolean.classliteral is also supported. The primitive class literal throws aNullPointerExceptionif the value representsnull.is supported if the value is aLocalDate.classdateis supported if the value is aLocalTime.classtimeis supported if the value is aLocalDateTime.classdateandtime.is supported if the value is anInstant.classinstant.is supported if the value is aZonedDateTime.classdate,timeandtimezone.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 mappingsspecified in theHostAccessconfiguration with precedenceHostAccess.TargetMappingPrecedence.LOW. is always supported. See section Object mapping rules.Object.classis supported ifMap.classHostAccess.MutableTargetMapping.MEMBERS_TO_JAVA_MAPrespectivelyHostAccess.MutableTargetMapping.HASH_TO_JAVA_MAPareallowedand the value hashasHashEntries()hash entries},membersorarray elements. The returned map can be safely cast to Map<Object, Object>. For value withmembersthe key type isString. For value witharray elementsthe key type isLong. It is recommended to usetype literalsto specify the expected collection component types. With type literals the value type can be restricted, for example toMap<String, String>. If the rawor an Object component type is used, then the return types of the the list are subject to Object target type mapping rules recursively.Map.classis supported ifList.classHostAccess.MutableTargetMapping.ARRAY_TO_JAVA_LISTisallowedand the value hasarray elementsand it has anarray sizethat is smaller or equal toInteger.MAX_VALUE. The returned list can be safely cast toList<Object>. It is recommended to usetype literalsto 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 rawor an Object component type is used, then the return types of the the list are recursively subject to Object target type mapping rules.List.classis supported if the value hasByteSequence.classbuffer elementsand it has abuffer sizethat is smaller or equal toInteger.MAX_VALUE.byte[].classis supported if the value hasbuffer elementsand it has abuffer sizethat 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_ITERATORisallowedand the value has aniterator. The returned iterable can be safely cast toIterable<Object>. It is recommended to usetype literalsto 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_ITERATORisallowedand the value is aniteratorThe returned iterator can be safely cast toIterator<Object>. It is recommended to usetype literalsto 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 rawor 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.classnextmethod may throw aConcurrentModificationExceptionwhen an underlying iterable has changed orUnsupportedOperationExceptionwhen the iterator's current element is not readable.- Any
functionalinterface ifHostAccess.MutableTargetMapping.EXECUTABLE_TO_JAVA_INTERFACEisallowedand the value can beexecutedorinstantiatedand the interface type isimplementable. Note thatFunctionalInterfaceare implementable by default in with theexplicithost 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 likeFunctionis used, it is recommended to usetype literalsto specify the expected generic method parameter and return type. - Any interface if the value
has membersand the interface type isimplementableandHostAccess.MutableTargetMapping.MEMBERS_TO_JAVA_INTERFACEisallowed. Each interface method maps to onememberof the value. Whenever a method of the interface is executed a member with the method or field name must exist otherwise anUnsupportedOperationExceptionis thrown when the method is executed. If one of the parameters or the return value cannot be mapped to the target type aClassCastExceptionor aNullPointerExceptionis thrown. - JVM only: Any abstract class with an accessible default constructor if the value
has membersand the class isimplementable. Each interface method maps to onememberof the value. Whenever an abstract method of the class is executed a member with the method or field name must exist otherwise anUnsupportedOperationExceptionis thrown when the method is executed. If one of the parameters or the return value cannot be mapped to the target type aClassCastExceptionor aNullPointerExceptionis thrown. - Custom
target type mappingsspecified in theHostAccessconfiguration with precedenceHostAccess.TargetMappingPrecedence.LOWEST.
ClassCastExceptionis 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
Objectis used as a target type:- If the value represents
nullthennullis returned. - If the value is a
host objectthen the value is coerced tohost object value. - If the value is a
stringthen the value is coerced toStringorCharacter. - If the value is a
booleanthen the value is coerced toBoolean. - If the value is a
numberthen the value is coerced toNumber. The specific sub type of theNumberis not specified. Users need to be prepared for any Number subclass includingBigIntegerorBigDecimal. It is recommended to cast toNumberand then convert to a Java primitive like withNumber.longValue(). - If the value has
array elementsand it has anarray sizethat is smaller or equal thanInteger.MAX_VALUEthen 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 implementFunctionif the value can beexecutedorinstantiated. - If the value has
hash entriesthen the result value will implementMap. Thesizeof the returnedMapis equal to thehash entries count. The returned value may also implementFunctionif the value can beexecutedorinstantiated. - If the value
has membersthen the result value will implementMap. If this valuehas membersthen all members are accessible usingStringkeys. Thesizeof the returnedMapis equal to the count of all members. The returned value may also implementFunctionif the value can beexecutedorinstantiated. - If the value has an
hasIterator()iterator} then the result value will implementIterable. The returned value may also implementFunctionif the value can beexecutedorinstantiated. - If the value is an
isIterator()iterator} then the result value will implementIterator. The returned value may also implementFunctionif the value can beexecutedorinstantiated. - If the value can be
executedorinstantiatedthen 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 implementListorMapif the value hasarray elementsormembers, respectively. - Mappings to mutable target types such as
List,Map,IteratorandIterableare 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
Valueinstance is returned.
host objects,String,Number,Booleanandnullvalues have unlimited lifetime. Other values will throw anIllegalStateExceptionfor any operation if their originatingcontextwas closed.If a
Mapelement is modified, aListelement is modified or aFunctionargument 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,CharacterorNumber, then the identity of the polyglot value is not preserved. All other results can be converted back to apolyglot valueusingContext.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 valuefrom 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 codeis used as string representation.- Since:
- 19.0
-
getSourceLocation
Returns the declared source location of the value.- Returns:
- the
SourceSectionor null if unknown - Since:
- 19.0
-
isDate
public boolean isDate()Returnstrueif this object represents a date, elsefalse. If this value is also atimezonethen 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 atimezoneotherwise 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()Returnstrueif this object represents a time, elsefalse. If the value is also atimezonethen 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 atimezoneotherwise 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()Returnstrueif this value represents an instant. If a value is an instant then it is also adate,timeandtimezone. 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,timeandtimezone. 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()Returnstrueif 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 zoneonly. If this rule is violated then anAssertionErroris 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()Returnstrueif 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()Returnstrueif 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 benullif the value was created usingasValue(Object)and no current context wasenteredat the time.The returned context can not be used to
enter,leaveorclosethe context orengine. Invoking such methods will cause anIllegalStateExceptionto be thrown. This ensures that only thecreatorof 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()Returnstrueif 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()Returnstrueif 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()Returnstrueif 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 theNoSuchElementExceptiondespite thehasIteratorNextElement()returnedtrue, or it may throw a language error.- Throws:
UnsupportedOperationException- if the value is not aniteratoror when the underlying iterable element exists but is not readable.NoSuchElementException- if the iteration has no more elements. Even if theNoSuchElementExceptionwas 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()Returnstrueif 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
Returnstrueif mapping for the specified key exists. If the value has nohash entriesthenhasHashEntry(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 ornullif 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 entriesor 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 entriesat 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. Returnstrueif the mapping was successfully removed,falseif 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 entriesor if mapping for specified keyexistsbut 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 aniteratorofarray elements. The first array element is a key, the second array element is an associated value. Even if the value array element ismodifiablewriting 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 thecurrentcontext when created. If there is no context available when the value was constructed then Values constructed with this method may returnnullforgetContext().- 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 methodtrueforisString(). 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 eitherbytesorencodingis 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 fromoffsetencoding- 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
Valueis alive. The returned value is guaranteed to returntrueforisString().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)withcopyset 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
-