How do I modify Java object in script?

This example show how to modify Java object from scripting environment. Below we manipulate a collection of string data. To pass data into the scripting engine we use a key-value binding to the script engine.

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.List;
import java.util.ArrayList;

public class ModifiedJavaObjectFromScript {
    public static void main(String[] args) {
        // Creating an array of five colors
        List<String> colors = new ArrayList<>();
        colors.add("White");
        colors.add("Black");
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");

        // 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);

        // Place the colors list into the engine using colorList key.
        // After passing the list into the engine our script will be
        // able to read it.
        engine.put("colorList", colors);

        try {
            engine.eval(getScript());

            // Redisplay the modified version of colors.
            for (String color : colors) {
                System.out.println("In Java: " + color);
            }
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }

    private static String getScript() {
        // Below is our script to read the values of Java List that
        // contains string of colors. We also add some other colors
        // to the list object in the script environment.
        return """
                let index;
                let colors = colorList.toArray();

                for (index in colors) {
                    print(`In script: ${colors[index]}`);
                }

                colorList.add("Yellow");
                colorList.add("Purple");
                colorList.add("Orange");
                """;
    }
}

The output of the code snippet above is:

In script: White
In script: Black
In script: Red
In script: Green
In script: Blue
In Java: White
In Java: Black
In Java: Red
In Java: Green
In Java: Blue
In Java: Yellow
In Java: Purple
In Java: Orange

Maven Dependencies

<dependencies>
    <dependency>
        <!--https://search.maven.org/remotecontent?filepath=org/graalvm/js/js/21.2.0/js-21.2.0.jar-->
        <groupId>org.graalvm.js</groupId>
        <artifactId>js</artifactId>
        <version>21.2.0</version>
    </dependency>
    <dependency>
        <!--https://search.maven.org/remotecontent?filepath=org/graalvm/js/js-scriptengine/21.2.0/js-scriptengine-21.2.0.jar-->
        <groupId>org.graalvm.js</groupId>
        <artifactId>js-scriptengine</artifactId>
        <version>21.2.0</version>
    </dependency>
</dependencies>

Maven Central Maven Central

Leave a Reply

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