How do I access Java object from a script?

This example demonstrate how you can access Java object from a script. We start by creating the ScriptEngine object. Then we obtain the Bindings object from the engine and set the polyglot.js.allowHostAccess options to true. We do this using the Bindings‘s put(String name, Object value) method.

After that we can put Java object into the script engine by calling the ScriptEngine‘s put(String key, Object value) method. This value can later be read or access by our script. For example, we pass an array of string and a date object for our script to display.

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.Date;
import java.util.function.Predicate;

public class AccessJavaObjectFromScript {
    public static void main(String[] args) {
        // Creating an array of five colors
        String[] colors = {"White", "Black", "Red", "Green", "Blue"};
        Date now = new Date();

        // Below is our script to read the values of Java array that
        // contains string of colors and also read the date object.
        String script = """
                let index;
                let colors = colorArray;

                for (index in colors) {
                    print(colors[index]);
                }

                print('----------');
                print('Today is ' + date.toString());
                """;

        // Obtain a ScriptEngine instance.
        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);

        // Place the colors array into the engine using colorArray key. And
        // the date object using the date key.
        engine.put("colorArray", colors);
        engine.put("date", now);

        try {
            engine.eval(script);
            engine.eval("print(date instanceof Java.type('java.util.Date'))");
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}

Our code will print as follows:

White
Black
Red
Green
Blue
----------
Today is Sun Oct 10 09:32:06 CST 2021
true

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

2 Comments

Leave a Reply

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