user2749903
user2749903

Reputation: 1305

GraalJs - call constructor of java object

I want to use graal js to provide some scripting extension to my application

How can i initialize a new java object on the javascript side?

Context ctx = Context ctx = Context.newBuilder().allowHostAccess(HostAccess.ALL).allowAllAccess(true).build().create();
Value binding = ctx.getBindings("js");
binding.putMember("ArrayList", ArrayList.class);
ctx.eval("js","let list = new ArrayList();list.add(\"1\")");
List list = binding.getMember("list").as(List.class);
assert list.size() == 1;

following code throws exception

Exception in thread "main" TypeError: instantiate on JavaClass[java.util.ArrayList] failed due to: Message not supported.
    at <js> :program(Unnamed:1:13-27)
    at org.graalvm.polyglot.Context.eval(Context.java:371)

Running graalvm-ce-java11 19.3.2

Upvotes: 1

Views: 1585

Answers (2)

Sebastian_K
Sebastian_K

Reputation: 19

You could also use the sj4js library. There you can define constructors which seamlessly blend into JS.

// we create a new JS engine and add
// TestClass as a constructor. This constructor is added to globalThis such that it
// can be called as a costructor.
try (JScriptEngine engine = new JScriptEngine(new JsGlobalThis(),"gt")) {
    engine.addConstructor(new TestClass("empty"));
            
    /* call your js code here */
}

Your JS code than looks like this you would expect it.

// we create a new variable from the constructor
var tc = new TestClass("test");

console.log(tc.name)
// test

Upvotes: 0

BoriS
BoriS

Reputation: 982

You need to use Java.type.

Here is an example taken from https://www.graalvm.org/docs/reference-manual/polyglot/

var array = new (Java.type("int[]"))(4);
array[2] = 42;
console.log(array[2])

Here is a fully runnable example tested with GraalVM 20.0.0

import org.graalvm.polyglot.*;

class M {
    public static void main(String[] args) {
        try (Context context = Context.newBuilder().allowAllAccess(true).build()) {
            java.util.ArrayList v = context.eval("js",
            "var ArrayList = Java.type('java.util.ArrayList');" +
            "var list = new ArrayList();" + 
            "list.add(1); list").asHostObject();
            System.out.println(v.get(0));
            assert v.get(0).equals(1);
        }
    }
}

Run with

graalvm-ce-java8-20.0.0/bin/javac M.java 
graalvm-ce-java8-20.0.0/bin/java -ea M

To get 1 as output.

Upvotes: 1

Related Questions