Java Reference
In-Depth Information
// Prepare the script
String script = "var sum = n1 + n2;" +
"print(msg + " +
"' n1=' + n1 + ', n2=' + n2 + " +
"', sum=' + sum);";
// Add n2 to the engine scope of the default context of the
// engine
engine.put("n2", 200);
engine.put("msg", "Using the default context:");
engine.eval(script);
// Use a Bindings to execute the script
Bindings bindings = engine.createBindings();
bindings.put("n2", 300);
bindings.put("msg", "Using a Bindings:");
engine.eval(script, bindings);
// Use a ScriptContext to execute the script
ScriptContext ctx = new SimpleScriptContext();
Bindings ctxGlobalBindings = engine.createBindings();
ctx.setBindings(ctxGlobalBindings, GLOBAL_SCOPE);
ctx.setAttribute("n1", 400, GLOBAL_SCOPE);
ctx.setAttribute("n2", 500, ENGINE_SCOPE);
ctx.setAttribute("msg", "Using a ScriptContext:",
ENGINE_SCOPE);
engine.eval(script, ctx);
// Execute the script again using the default context to
// prove that the default context is unaffected.
engine.eval(script);
}
}
Using the default context: n1=100, n2=200, sum=300
Using a Bindings: n1=100, n2=300, sum=400
Using a ScriptContext: n1=400, n2=500, sum=900
Using the default context: n1=100, n2=200, sum=300
Search WWH ::




Custom Search