簡介 Nashorn
Nashorn 一個 javascript 引擎。
從JDK 1.8開始,Nashorn取代Rhino(JDK 1.6, JDK1.7)成為Java的嵌入式JavaScript引擎。Nashorn完全支持ECMAScript 5.1規範以及一些擴展。
它使用基於JSR 292的新語言特性,其中包含在JDK 7中引入的 invokedynamic,將JavaScript編譯成Java字節碼。
與先前的Rhino實現相比,這帶來了2到10倍的性能提升。
使用方式
1. 編寫JavaScript腳本
列:JavaScript方法使用Java對象執行方法獲取返回值。
function scriptFunction(obj){ var a = 1; var b = 2; return obj.sum(a,b); } scriptFunction(obj);//調用該方法
該腳本變量定義為 String script1;
2. 創建JavaScript容器用戶存儲腳本 ScirptContainer.java
public class ScirptContainer { public static ScriptEngine engine;//腳本引擎 static { ScriptEngineManager manager = new ScriptEngineManager();//腳本引擎管理 engine = manager.getEngineByName("nashorn");//獲取nashorn腳本引擎 engine.getContext().getWriter();//獲取正文並且寫入 } private ConcurrentHashMapscripts = new ConcurrentHashMap<>();//腳本存儲容器 public CompiledScript getCompiledScript(String script) throws ScriptException{ //判斷腳本是否為空 if(script == null || "".equals(script)){ throw new ScriptException("JavaScript empty"); } //獲取腳本Hash int hashCode = script.hashCode(); //從容器中獲取腳本 CompiledScript compiledScript = scripts.get(hashCode); if(compiledScript == null){ //容器中無腳本創建腳本對象 Compilable compilable = (Compilable) engine; //編譯JavaScript腳本 compiledScript = compilable.compile(script); //腳本對象存入容器中 scripts.put(hashCode, compiledScript); } return compiledScript; } }
3. Java執行JavaScript腳本
public class ScriptHandler { //創建容器對象 private ScirptContainer scirptContainer = new ScirptContainer(); //需要執行的對象 String js1 = "function scriptFunction(obj){ var a = 1; var b = 2; return obj.sum(a,b); } scriptFunction(obj);"; @Test public void test() throws ScriptException{ //獲取腳本對象 CompiledScript c1 = scirptContainer.getCompiledScript(js1); //創建參數綁定 Bindings bindings = scirptContainer.engine.createBindings(); //obj參數綁定SumTest類 bindings.put("obj", new SumTest()); //執行JavaScript腳本並且打印返回值 System.out.println(c1.eval(bindings)); } }
注意事項:
腳本中scriptFunction(obj);是必須存在,否則不會執行方法.
腳本中可以創建Java對象,需要全類名如var map = new java.util.HashMap();
[retouched ] Java中使用JavaScript腳本的方法步驟已經有434次圍觀