JDK8系列之JavaScript引擎Nashorn
Posted smileNicky
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDK8系列之JavaScript引擎Nashorn相关的知识,希望对你有一定的参考价值。
从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
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脚本
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);
以上是关于JDK8系列之JavaScript引擎Nashorn的主要内容,如果未能解决你的问题,请参考以下文章