Like this article? We recommend
Set and Retrieve a Script Engine's State
A script engine has state that can be set by a Java program, accessed and manipulated by a script, and retrieved by the Java program. The program sets this state by invoking ScriptEngine's public void put(String key, Object value) method, where key typically identifies a scripting language variable and value provides the variable's value. Similarly, a Java program invokes ScriptEngine's public Object get(String key) method to retrieve the state value. Listing 3 describes an application that demonstrates these methods.
Listing 3: ScriptDemo3.java
// ScriptDemo3.java import javax.script.*; public class ScriptDemo3 { public static void main (String [] args) throws ScriptException { // Create a ScriptEngineManager that discovers all script engine // factories (and their associated script engines) that are visible to // the current thread's classloader. ScriptEngineManager manager = new ScriptEngineManager (); // Obtain a ScriptEngine that supports the JavaScript short name. ScriptEngine engine = manager.getEngineByName ("JavaScript"); // Initialize the age script variable to 85 (an Integer). engine.put ("age", 85); // Evaluate a script that determines if a person can obtain an amount to // deduct from their taxable income based on age. engine.eval ("var ageAmount = 0.0; if (age >= 65) ageAmount += 6000;"); // Retrieve the ageAmount script variable (a Double) and output its // value. System.out.println ("ageAmount = " + engine.get ("ageAmount")); } }
ScriptDemo3 creates the following output:
ageAmount = 6000.0