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 Fri Dec 21 23:03:39 WITA 2018
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020