http://mail.openjdk.java.net/pipermail/nashorn-dev/2015-May/004572.html
import javax.script.*;
import jdk.nashorn.api.scripting.*;
public class Main {
ScriptEngineFactory factory = new NashornScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine();
Bindings globalBindings = new SimpleBindings();
Bindings engineBindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
ScriptContext context = new SimpleScriptContext();
public static void main(String[] ar) throws Exception {
Main main = new Main();
main.context.setBindings(main.globalBindings, ScriptContext.GLOBAL_SCOPE);
main.context.setBindings(main.engineBindings, ScriptContext.ENGINE_SCOPE);
main.engineBindings.put("program", main);
main.globalBindings.put("text", "initial text");
main.engine.eval(
" print(text); " +
" program.someMethod(); " +
" print(text);", main.context);
/* Expected output:
initial text
another text
initial text
Output seen:
initial text
another text
another text
*/
}
public void someMethod() throws Exception {
// a context with a new global bindings, same engine bindings
ScriptContext context = new SimpleScriptContext();
Bindings globalBindings = new SimpleBindings();
context.setBindings(globalBindings, ScriptContext.GLOBAL_SCOPE);
context.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE);
globalBindings.put("text", "another text");
engine.eval("print(text)", context);
}
}