Java 全局腳本

2018-03-18 13:42 更新

Java腳本教程 - Java全局腳本


每個(gè)Nashorn引擎使用多個(gè)腳本全局變量

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);
  }
}

上面的代碼生成以下結(jié)果。


例子

以下代碼顯示了如何通過(guò)復(fù)制引擎的默認(rèn)上下文的引擎范圍綁定來(lái)共享腳本。

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);
  }
}

上面的代碼生成以下結(jié)果。



以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)