graalvmgraaljs

GraalVM Polyglot can't load Java class


Want migrate from Nashorn to GraalVM. Installed Graal VM CE

openjdk version "11.0.5" 2019-10-15
OpenJDK Runtime Environment (build 11.0.5+10-jvmci-19.3-b05-LTS)
OpenJDK 64-Bit GraalVM CE 19.3.0 (build 11.0.5+10-jvmci-19.3-b05-LTS, mixed mode, sharing)

Test app

import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.HostAccess;

public class Main {
    public static void main(String[] args) {
        Context context = Context.newBuilder("js").allowHostAccess(HostAccess.ALL).build();
        context.eval("js", "var FileClass = Java.type(\"java.io.File\");");
    }
}

Exception:

Exception in thread "main" ReferenceError: Java is not defined
    at <js> :program(Unnamed:1:16-19)
    at org.graalvm.sdk/org.graalvm.polyglot.Context.eval(Context.java:370)
    at task.Main.main(Main.java:9)

What's wrong?


Solution

  • As I understood, that is the correct alternative:

    Context context = Context.newBuilder("js")
            .allowHostClassLookup(s -> true)
            .allowHostAccess(HostAccess.ALL)
            .build();
    

    HostAccess.ALL – Predefined host access policy that allows full unrestricted access to public methods or fields of public host classes.

    ...But we also need to change default filter predicate org.graalvm.polyglot.Context#UNSET_HOST_LOOKUP which returns always false:

    allowHostClassLookup – By default and if all access is false, host class lookup is disabled.

    So, just no filtering allowHostClassLookup(s -> true).