How do I access Java object from a script?
Category: javax.script, viewed: 3391 time(s).
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
Can't find what you are looking for? Join our
FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources
Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more;
all available at no cost to you. With more than 600 complimentary offers, you'll find
plenty of titles to suit your professional interests and needs.
Click Here and Sign up today!