How do I access Java object from a script?

This example demonstrate how you can access Java object from a script. We 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.example.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.Date;

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.
        //
        String script =
                "var index; " +
                "var colors = colorArray; " +
                " " +
                "for (index in colors) { " +
                "    println(colors[index]); " +
                "}" +
                "println('----------'); " +
                "println('Today is ' + date); ";

        //
        // Obtain a ScriptEngine instance.
        //
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByExtension("js");

        //
        // Place the colors array into the engine using colorArray key.
        // After setting the array into the engine our script will be
        // able to read it.
        //
        engine.put("colorArray", colors);
        engine.put("date", now);

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

Our code will print as follow:

White
Black
Red
Green
Blue
----------
Today is Mon Jul 13 23:12:19 SGT 2009

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply