“ Cannot invoke “javax.script.ScriptEngine.eval(String)” because “engine” is null ”
jdk17下执行以下代码发生报错
String script = " function add (a, b) { " +
" var sum = a + b; " +
//js调用java类
" java.lang.System.out.println(\"Script sum=\" + sum); " +
" return java.lang.Integer.valueOf(sum); " +
"}";
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("Nashorn");
Object pbj = engine.eval(script);
System.out.println(pbj);
Invocable jsInvoke = (Invocable) engine;
Object result = jsInvoke.invokeFunction("add", new Object[]{1, 2});
System.out.println(result);
} catch (ScriptException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
报错原因分析:
Jdk8中内置的JavaScript引擎 nashorn 被移除,导致报错Cannot invoke “javax.script.ScriptEngine.eval(String)” because “engine” is null
脚本引擎执行脚本语句报错,因为执行引擎为空。
查询相关资料Jdk8自带的JavaScript引擎 nashorn 再升级到Jdk9后就被移除了,从而导致报错
解决方法
在pom文件添加JavaScript引擎 nashorn 依赖,重新启动项目即可
<dependency>
<groupId>org.openjdk.nashorn</groupId>
<artifactId>nashorn-core</artifactId>
<version>15.4</version>
</dependency>
参考:
https://www.cnblogs.com/liyhbk/p/17517104.html