Scripting in Java Tutorial - Scripting in Java Globals








Using Multiple Script Globals Per Nashorn Engine

import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleScriptContext;
/*from  w ww .  j  av  a 2  s .  c om*/
public class Main {
  public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    engine.eval("var msg = 'Hello globals'");
    engine.eval("print(this.msg);");
    ScriptContext ctx = new SimpleScriptContext();
    engine.eval("print(this.msg);", ctx);
  }
}

The code above generates the following result.





Example

The following code shows how to share Script by Copying the Engine Scope Bindings of the Engine's Default Context.

import static javax.script.ScriptContext.ENGINE_SCOPE;
//ww w. j av a2 s  .  co m
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleScriptContext;

public class Main {
  public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    engine.eval("var msg = 'Hello globals'");
    engine.eval("print(this.msg);");
    ScriptContext ctx = new SimpleScriptContext();
    ScriptContext defaultCtx = engine.getContext();
    Bindings engineBindings = defaultCtx.getBindings(ENGINE_SCOPE);
    ctx.setBindings(engineBindings, ENGINE_SCOPE);
    engine.eval("print(this.msg);", ctx);
  }
}

The code above generates the following result.