Java Reference
In-Depth Information
The default context of each ScriptEngine maintains an engine scope Bindings
separately. To add a key-value pair to the engine scope Bindings of a ScriptEngine , use
its put() method, as shown:
ScriptEngine engine1 = null; // get an engine
// Add an "engineName" key with its value as "Engine-1" to the
// engine scope Bindings of the default context of engine1
engine1.put("engineName", "Engine-1");
The get(String key) method of the ScriptEngine returns the value of the specified
key from its engine scope Bindings . The following statement returns “Engine-1”, which is
the value for the engineName key:
String eName = (String)engine1.get("engineName");
It is a two-step process to get to the key-value pairs of the global scope Bindings in
the default context of a ScriptEngine . First, you need to get the reference of the global
scope Bindings using its getBindings() method, as shown:
Bindings e1Global = engine1.getBindings(ScriptContext.GLOBAL_SCOPE);
Now you can modify the global scope Bindings of the engine using the e1Global
reference. The following statement adds a key-value pair to the e1Global Bindings :
e1Global.put("id", 89999);
Because of the sharing of the global scope Bindings of a ScriptEngine by
all ScriptEngine s, this snippet of code will add the key "id" with its value to the
global scope Bindings of the default context of all ScriptEngine s created by the
same ScriptEngineManager that created engine1 . Modifying the Bindings in a
ScriptEngineManager using code as shown here is not recommended. You should
modify the Bindings using the ScriptEngineManager reference instead, which makes the
logic clearer to the readers of the code.
Listing 3-3 demonstrates the concepts discussed in this section. A
ScriptEngineManager adds two key-value pairs with keys n1 and n2 to its Bindings .
Two ScriptEngines are created; they add a key called engineName to their engine scope
Bindings . When the script is executed, the value of the engineName variable in the script
is used from the engine scope of the ScriptEngine . The values for variables n1 and n2
in the script are retrieved from the global scope Bindings of the ScriptEngine . After
executing the script for the first time, each ScriptEngine adds a key called n2 with a
different value to their engine scope Bindings . When you execute the script for the
second time, the value for the n1 variable is retrieved from the global scope Bindings
of the engine, whereas the value for the variable n2 is retrieved from the engine scope
Bindings as shown in the output.
 
Search WWH ::




Custom Search