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 {
        } catch (ScriptException e) {

Our code will print as follow:

Today is Fri Dec 21 23:03:39 WITA 2018

Leave a Reply

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