Java SimpleScriptContext set attribute with different isolation levels
import javax.script.Bindings; import javax.script.ScriptContext; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.script.SimpleScriptContext; public class Main { public static void main(String[] args) throws ScriptException { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); manager.put("n1", 100); String script = "var sum = n1 + n2;" + // "print(msg + " + "' n1=' + n1 + ', n2=' + n2 + " + "', sum=' + sum);"; engine.put("n2", 200); engine.put("msg", "Using the default context:"); engine.eval(script);/*w w w . ja v a 2s. c o m*/ Bindings bindings = engine.createBindings(); bindings.put("n2", 300); bindings.put("msg", "Using a Bindings:"); engine.eval(script, bindings); ScriptContext ctx = new SimpleScriptContext(); Bindings ctxGlobalBindings = engine.createBindings(); ctx.setBindings(ctxGlobalBindings, SimpleScriptContext.GLOBAL_SCOPE); ctx.setAttribute("n1", 400, SimpleScriptContext.GLOBAL_SCOPE); ctx.setAttribute("n2", 500, SimpleScriptContext.ENGINE_SCOPE); ctx.setAttribute("msg", "Using a ScriptContext:", SimpleScriptContext.ENGINE_SCOPE); engine.eval(script, ctx); engine.eval(script); } }