Do GraalVM JavaScript's JS-to-Java object conversions contain type information?

702 views Asked by At

To mimic on GraalVM JavaScript some of Node's functions under util.types, I turned to Java functions that I can access through Java.type or the Java package global variables. GraalVM's has internal functions like JSProxy.isJSProxy and JSSet.isJSSet that do this. I made them accessible by marking them as a exported, recompiled, and tested them (I accessed them with, e.g., Java.type("com.oracle.truffle.js.builtins.runtime.JSProxy").isJSProxy).

As I found out, GraalVM JavaScript's internal functions are useless to me. For example, JSProxy.isJSProxy only returns true if it is passed an instance of JSProxyObject. Oracle's documentation says that

JavaScript objects are exposed to Java code as instances of com.oracle.truffle.api.interop.java.TruffleMap. This class implements Java’s Map interface.

TruffleMap doesn't appear in the source code of GraalVM JavaScript and only appears once in the source code of GraalVM, so it's likely deprecated, but that's besides the point because the representation method is probably the same.

Whatever the external Java-side representation of JS objects is right now, does it contain information about what the object's type on the JavaScript side is? Can I determine if it's a JS proxy? Can I determine if it's a Set object? (And so on for native JavaScript object types.)

1

There are 1 answers

2
BoriS On

To be honest your question is quite confusing to me, but are you just looking for the instanceof operator?

import org.graalvm.polyglot.*;
import org.graalvm.polyglot.proxy.*;

public class Test {
    public static class MyClass {
        public int id = 42;
    }

    public static void main(String[] args) {
       try (Context context = Context.newBuilder().allowAllAccess(true).build()) {
            context.getBindings("js").putMember("javaObj", new MyClass());
            boolean valid = context
              .eval("js", "javaObj instanceof Java.type('Test$MyClass')")
              .asBoolean();
            assert valid;
        }
    }
}