script
Access Java Object from a script
In this example we shall show you how to access a Java Object from a script. We are using the ScriptEngine interface that provides methods for the basic scripting functionality. To access a Java Object from a script one should perform the following steps:
getEngineByExtension(String extension) API method to look up and create a ScriptEngine for the js extension.put(String key, Object value) API method of ScriptEngine to set a key/value pair in the state of the ScriptEngine that may either create a Java Language Binding to be used in the execution of scripts or be used in some other way, depending on whether the key is reserved. The value set here is a list of String car brands, with the key "brandArray".eval(String script) method to execute the script,as described in the code snippet below.
package com.javacodegeeks.snippets.core;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class AccessJavaObjectFromScript {
public static void main(String[] args) {
// Create an array of car brands
String[] brands = {"Audi", "Mercedes", "Renault", "Ford", "Seat"};
// Script that reads the values of the array that contains string of car brands.
String script =
"var index; " +
"var brands = brandsArray; " +
" " +
"for (index in brands) { " +
" println(brands[index]); " +
"}" ;
// Obtain a ScriptEngine instance.
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByExtension("js");
// Place the brands array into the engine using brandsArray key.
engine.put("brandsArray", brands);
try {
engine.eval(script);
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
Output:
Audi
Mercedes
Renault
Ford
Seat
This was an example of how to access a Java Object from a script in Java.
