从JDK1.8开始,Java采用Nashorn作为嵌入式 JavaScript 引擎。JDK1.6和JDK1.7采用Rhino。Nashorn 支持 ECMAScript 5.1 规范,使用基于 JSR 292 的新语言特性,其中包含在 JDK 7 中引入的 invokedynamic,将 JavaScript 编译成 Java 字节码。
下面给出一些例子加深理解,一个最简单的例子,调用1 2
,计算输出打印
package com.example.jdkexample.core.nashorn;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class NashornJavaScriptExample {
public static void main(String[] args) throws ScriptException {
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = engineManager.getEngineByName("JavaScript");
String foo = "1 2";
System.out.println(scriptEngine.eval(foo));
}
}
可以利用ScriptEngine对js进行执行,然后通过Hutool转为javabean
代码语言:javascript复制private static void testJson() throws ScriptException {
String script = "var json ={"name":"admin" , "mobiTel":"123"};"
"var result ={};result.name=json.name;result.mobiTel=json.mobiTel;JSON.stringify(result);";
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = engineManager.getEngineByName("JavaScript");
Object obj = scriptEngine.eval(script);
User user = JSONUtil.toBean(obj.toString() , User.class);
System.out.println(user.toString());
}
读取js文件,然后执行js脚本
代码语言:javascript复制private static void testJsFile() {
try (Reader reader= new FileReader(new File(ScriptEngineExample.class.getClassLoader().getResource("test.js").getFile()))){
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = engineManager.getEngineByName("JavaScript");
scriptEngine.eval(reader);
} catch (FileNotFoundException e) {
log.error("FileNotFoundException:{}" , e);
} catch (IOException e) {
log.error("IOException:{}" , e);
} catch (ScriptException e){
log.error("ScriptException:{}" , e);
}
}
给出一串js,invokeFunction
调用js里的函数
private static void testInvokeFunction() throws ScriptException, NoSuchMethodException {
String script = "var json ={"name":"admin" , "mobiTel":"123"};"
"function jsonStringify(){ var result ={};result.name=json.name;result.mobiTel=json.mobiTel;print(JSON.stringify(result));}";
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = engineManager.getEngineByName("JavaScript");
scriptEngine.eval(script);
Invocable invocable = (Invocable) scriptEngine;
invocable.invokeFunction("jsonStringify");
}
使用Bindings
传参
private static void testBinding() throws ScriptException, NoSuchMethodException {
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = engineManager.getEngineByName("JavaScript");
Bindings bindings = new SimpleBindings();
bindings.put("username","admin");
scriptEngine.eval("print('hello , ' username);" , bindings);
}