How do I import Java package in script?

Here you can see how to import a Java class so that you can use the class, creates an instance of it in the scripting environment. We want to print out the current date on the console. For this we need to import the Date class that’s packaged under the java.util package.

In the script we can import the java.util package using the following script let Date = Java.type("java.util.Date").

package org.kodejava.script;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.function.Predicate;

public class ImportPackageExample {
    public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByExtension("js");
        Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        bindings.put("polyglot.js.allowHostAccess", true);
        bindings.put("polyglot.js.allowHostClassLookup", (Predicate<String>) s -> true);

        try {
            engine.eval(getScript());
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }

    private static String getScript() {
        return """                               
                let Date = Java.type("java.util.Date");
                let today = new Date();
                print(`Today is ${today.toString()}`);
                print(`today is ${today.getClass().getName()}`);
                """;
    }
}

This program prints the following line:

Today is Sun Oct 10 15:15:13 CST 2021
today is java.util.Date

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.graalvm.js</groupId>
        <artifactId>js</artifactId>
        <version>22.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.graalvm.js</groupId>
        <artifactId>js-scriptengine</artifactId>
        <version>22.3.2</version>
    </dependency>
</dependencies>

Maven Central Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.