Nashorn脚本引擎不会将“com”和“org”对象/命名空间从全局范围共享到引擎范围。因为“com”和“org”是引擎可用的Java包。
在示例中,我将a
和org
变量放入engine2
的全局范围。
a = 3
已共享org = 10
存在于GLOBAL_SCOPE
中,但未与ENGINE_SCOPE
代码:
public static void main(String[] args) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
Bindings bindings = engine.createBindings();
bindings.put("a", 3);
bindings.put("org", 10);
log("bingings-org", bindings.get("org"));
manager.setBindings(bindings);
ScriptEngine engine2 = manager.getEngineByName("JavaScript");
log("global-a", engine2.getBindings(ScriptContext.GLOBAL_SCOPE).get("a"));
log("local-a", engine2.get("a"));
log("global-org", engine2.getBindings(ScriptContext.GLOBAL_SCOPE).get("org"));
log("local-org", engine2.get("org"));
}
答案 0 :(得分:2)
搜索脚本全局变量时,搜索顺序首先是ENGINE_SCOPE,然后是GLOBAL_SCOPE。 Nashorn引擎的ENGINE_SCOPE绑定是包装为javax.script.Bindings对象的ECMAScript“全局”对象。正如您所观察到的,ENGINE_SCOPE具有“org”,“com”等的映射 - 这是Java包前缀对象。因此,这些将隐藏GLOBAL_SCOPE绑定中的任何“org”,“com”等。两种解决方案:
您将“context”变量暴露给脚本。因此,您可以使用相同的方法获取GLOBAL_SCOPE映射。
private static void log(String msg, Object obj) {
System.out.println(msg + " " + obj);
}
public static void main(String[] args) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
Bindings bindings = new SimpleBindings();
bindings.put("a", 3);
bindings.put("org", 10);
log("bingings-org", bindings.get("org"));
manager.setBindings(bindings);
ScriptEngine engine = manager.getEngineByName("JavaScript");
log("global-a", engine.getBindings(ScriptContext.GLOBAL_SCOPE).get("a"));
log("local-a", engine.get("a"));
log("global-org", engine.getBindings(ScriptContext.GLOBAL_SCOPE).get("org"));
log("local-org", engine.get("org"));
// Use "context" to access GLOBAL_SCOPE "org" from script
engine.eval(
"var GLOBAL_SCOPE = javax.script.ScriptContext.GLOBAL_SCOPE;\n" +
"var g = context.getBindings(GLOBAL_SCOPE);\n" +
"print(g.get('org'))");
}
您可以删除ENGINE_SCOPE Bindings中的“org”,“com”等。
private static void log(String msg, Object obj) {
System.out.println(msg + " " + obj);
}
public static void main(String[] args) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
Bindings bindings = new SimpleBindings();
bindings.put("a", 3);
bindings.put("org", 10);
log("bingings-org", bindings.get("org"));
manager.setBindings(bindings);
ScriptEngine engine = manager.getEngineByName("JavaScript");
log("global-a", engine.getBindings(ScriptContext.GLOBAL_SCOPE).get("a"));
log("local-a", engine.get("a"));
log("global-org", engine.getBindings(ScriptContext.GLOBAL_SCOPE).get("org"));
log("local-org", engine.get("org"));
// "org" in ENGINE_SCOPE hides GLOBAL_SCOPE "org".
// delete the "org" in ENGINE_SCOPE
// you could delete "org" from Java code as well using
// "remove" method of Bindings object
engine.eval("delete org");
System.out.println("after deleting ENGINE_SCOPE org");
log("local-org", engine.get("org"));
}