JDK8中新添加了ScriptEngineManager類用於調用腳本文件
ScriptEngineManager類常用方法
getEngineByExtension(String extension)
查找並創建一個ScriptEngine一個給定擴展getEngineByName(String shortName)
查找並為給定的名稱創建一個 ScriptEngine 。put(String key, Object value)
方法在全局范圍中設置指定的鍵/值對。get(String key)
獲取全局范圍中指定鍵的值。
ScriptEngine接口常用方法
eval(Reader reader)
與eval(String)
相同,只是腳本的來源以 Reader形式提供Object eval(String script)
執行指定的腳本。get(String key)
檢索在此引擎狀態下設置的值。put(String key, Object value)
在ScriptEngine的狀態下設置一個鍵/值對,可以創建一個Java語言綁定,以便在執行腳本時使用,或者以某種其他方式使用,具體取決於該鍵是否被保留。
代碼示例
public void hello() throws Exception{
ScriptEngineManager manager = new ScriptEngineManager();
//JavaScript可以簡寫為js
ScriptEngine engine = manager.getEngineByName("JavaScript");
//也可以采用ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
//jdk8對ES6的支持 ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine("--language=es6");
engine.eval("print('hello word!!')");
}
hello.js腳本文件
print(hello);//支持print()打印
public void hello() throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
String script = FileCopyUtils.copyToString(new FileReader("hello.js"));
String hello = "hello word!";
engine.put("hello", hello);
engine.eval(script);
}