Java 全局脚本

2018-03-18 13:42 更新

Java脚本教程 - Java全局脚本


每个Nashorn引擎使用多个脚本全局变量

import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleScriptContext;

public class Main {
  public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    engine.eval("var msg = "Hello globals"");
    engine.eval("print(this.msg);");
    ScriptContext ctx = new SimpleScriptContext();
    engine.eval("print(this.msg);", ctx);
  }
}

上面的代码生成以下结果。


例子

以下代码显示了如何通过复制引擎的默认上下文的引擎范围绑定来共享脚本。

import static javax.script.ScriptContext.ENGINE_SCOPE;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleScriptContext;

public class Main {
  public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    engine.eval("var msg = "Hello globals"");
    engine.eval("print(this.msg);");
    ScriptContext ctx = new SimpleScriptContext();
    ScriptContext defaultCtx = engine.getContext();
    Bindings engineBindings = defaultCtx.getBindings(ENGINE_SCOPE);
    ctx.setBindings(engineBindings, ENGINE_SCOPE);
    engine.eval("print(this.msg);", ctx);
  }
}

上面的代码生成以下结果。



以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号