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

        // 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 {

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

    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]}`);


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


Maven Central Maven Central


Leave a Reply

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