ENGINE_SCOPE
基本上是当放入绑定的变量仅适用于该特定引擎时,而GLOBAL_SCOPE
当放入绑定的变量可由同一工厂的所有引擎访问时。
是的,你是对的,如果在 中找不到任何变量,ENGINE_SCOPE
它自然会在 中搜索GLOBAL_SCOPE
。
根据JavaDoc
static final int ENGINE_SCOPE
EngineScope 属性在单个 ScriptEngine 的生命周期内是可见的,并且为每个引擎维护一组属性。
static final int GLOBAL_SCOPE
GlobalScope 属性对同一 ScriptEngineFactory 创建的所有引擎可见。
我们可以在 Nashorn 中使用与此类似的脚本上下文来使用多个作用域
context = new SimpleScriptContext(); // Script Context is an interface therefor you need to use an implementation of it
context.setBindings(engine.createBindings(), SCOPE); // Set the bindings of the context, you can then use the context as an argument with the eval method of the script engine. Here engine is again an instance of javax.script.ScriptEngine
Bindings bindings = context.getBindings(SCOPE); // Now use this for "putting" variables into the bindings SCOPE should either be ScriptContext.ENGINE_SCOPE or ScriptContext.GLOBAL_SCOPE
bindings.put("x", "hello world");
// Once done you must set the bindings
context.setBindings(scope, SCOPE);
// This code is just rough, I'm 100% sure there can always be further optimizations to this
// Now finally evaluate your code
engine.eval("Some pice of code..", context);
// Or you can use engine.setContext(YourContext) method in case you'll use your engine as an Invocable
engine.setContext(context);
engine.eval("Some piece of code");
/* Do this because sometimes due to a bug you might not be able to call methods or functions from evaluated script
Knowing about SrciptContext will help you a lot
Note you can have multiple contexts and switch between them like I said
Context parameter is also applicable for eval(Reader);
*/
我希望这有帮助