Java examples for Scripting:Run Script
Using Different Isolation Levels for Executing Scripts
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 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", 2); engine.put("msg", "Using the default context:"); engine.eval(script);//from w ww.j ava 2s . c om 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, GLOBAL_SCOPE); ctx.setAttribute("n1", 4, GLOBAL_SCOPE); ctx.setAttribute("n2", 5, ENGINE_SCOPE); ctx.setAttribute("msg", "Using a ScriptContext:", ENGINE_SCOPE); engine.eval(script, ctx); engine.eval(script); } }