如何使用Java ScriptEngine API共享不同ScriptContext的公共绑定?

时间:2016-09-22 12:20:39

标签: java java-8 nashorn scriptengine

我正在使用Nashorn和java 8的ScriptEngine API。我有一个独特的ScriptEngine实例来执行几个不同的脚本。我想为我将要执行的所有脚本删除一些函数(例如print),但为每个脚本指定一个特定的绑定绑定。

我的问题是我不知道是否可以使用ScriptContext创建一种层次结构。

这是我要做的事情的例子:

public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("nashorn");
    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.remove("print");

    // script I will run
    String script1 = "print('Hello world')";
    String script2 = "print(person)";

    // define a different script context
    ScriptContext newContext = new SimpleScriptContext();
    Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);

    // set the variable to a different value in another scope
    engineScope.put("person", "toto");

    // evaluate script but in global context
    // should throw message because print is not declared in the context
    try {
        engine.eval(script1);
    } catch (ScriptException se) {
        System.out.println(se.getMessage()); // out : ReferenceError: "print" is not defined in <eval> at line number 1
    }

    // should throw message because print is not declared in the context
    engine.eval(script2, newContext); // out : toto
}

在这里,探测器是当我执行script2时,我希望该打印已从上下文中删除。

有干净的方法吗?

0 个答案:

没有答案