Java Reference
In-Depth Information
The three sets of the eval() method let you execute scripts using different isolation
levels:
The first set lets you share the default context by all scripts
The second set lets scripts use different engine scope
Bindings
and share the global scope Bindings
The third set lets scripts execute in an isolated
ScriptContext
Listing 3-4 shows how scripts are executed in different isolation levels using the
different version of the eval() method. The program uses three variables called msg ,
n1 , and n2 . It displays the value stored in the msg variable. The values of n1 and n2 are
added and the sum is displayed. The script prints what values of n1 and n2 were used in
computing the sum. The value of n1 is stored in the Bindings of ScriptEngineManager
that is shared by the default context of all ScriptEngine s. The value of n2 is stored in the
engine scope of the default context and the custom contexts. The script is executed twice
using the default context of the engine, once in the beginning and once in the end, to
prove that using a custom Bindings or a ScriptContext in the eval() method does not
affect the Bindings in the default context of the ScriptEngine . The program declares a
throws clause in its main() method to keep the code shorter.
Listing 3-4. Using Different Isolation Levels for Executing Scripts
// CustomContext.java
package com.jdojo.script;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleScriptContext;
import static javax.script.SimpleScriptContext.ENGINE_SCOPE;
import static javax.script.SimpleScriptContext.GLOBAL_SCOPE;
public class CustomContext {
public static void main(String[] args) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// Add n1 to Bindings of the manager, which will be shared
// by all engines as their global scope Bindings
manager.put("n1", 100);
Search WWH ::




Custom Search