Skip to content

Unwrap polyglot.Value? #922

@melvinm1

Description

@melvinm1

Hello

We want to replace Nashorn with Graal in our application. In one part of our application, we use objects that are returned from JavaScript as keys in a Java WeakHashMap. This was possible in Nashorn, provided that the ScriptObjectMirror objects returned by Nashorn were first "unwrapped" using the ScriptObjectMirror.unwrap method. I haven't been able to accomplish the same thing using Graal. I tried to use polyglot.Value as keys in the WeakHashMap, but that doesn't seem to work as demonstrated by this example:

import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Value;
import java.util.WeakHashMap;

public class Main {
    public static void main(String[] args) {
        WeakHashMap<Object, String> weakMap = new WeakHashMap<>();

        try (Context context = Context.create()) {
            // Define global object "obj" and return a getter function.
            Value getObj = context.eval("js", "let obj = { test: 123 }; (function getObj() { return obj; })");
            
            // Use the object as a key in the WeakMap.
            weakMap.put(getObj.execute(), "test");

            // Check if the key exists in the WeakMap.
            // Prints true.
            System.out.println(weakMap.containsKey(getObj.execute()));

            // Trigger garbage collection.
            System.gc();

            // Check again if the key exists in the WeakMap.
            // Should also print true, but prints false.
            System.out.println(weakMap.containsKey(getObj.execute()));
        }
    }
}

Each call to getObj.execute() seems to be returning different polyglot.Value instances. Is there a way to "unwrap" polyglot.Value, similar to Nashorn's ScriptObjectMirror.unwrap, so that objects returned from JavaScript could be used as keys in a WeakHashMap in Java? Or are there any other ways in which this could be accomplished?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions