@Test
public void invokeFunctionInGlobalScopeTest2() throws Exception {
final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// create a new ScriptContext instance
final ScriptContext ctxt = new SimpleScriptContext();
// set it as 'default' ScriptContext
engine.setContext(ctxt);
// create a new Bindings and set as ENGINE_SCOPE
ctxt.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
// define a function called "func"
engine.eval("func = function() { return 42 }");
// move ENGINE_SCOPE Bindings to GLOBAL_SCOPE
ctxt.setBindings(ctxt.getBindings(ScriptContext.ENGINE_SCOPE), ScriptContext.GLOBAL_SCOPE);
// create a new Bindings and set as ENGINE_SCOPE
ctxt.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
// define new function that calls "func" now in GLOBAL_SCOPE
engine.eval("newfunc = function() { return func() }");
// call "newfunc" and check the return value
final Object value = ((Invocable)engine).invokeFunction("newfunc");
assertTrue(((Number)value).intValue() == 42);
}
ScopeTest.java 文件源码
java
阅读 18
收藏 0
点赞 0
评论 0
项目:openjdk-jdk10
作者:
评论列表
文章目录