Java 17 版本运行 javascript
使用 Java 运行 JavaScript 脚本
当前版本:
JDK:17
测试程序:
public class EngineTest { public static void main(String[] args) throws ScriptException, NoSuchMethodException { var manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("javascript"); System.out.println(engine); System.out.println("test javascript"); String scriptString = "var date = new Date();" + "date.getHours();"; Double hour = (Double)engine.eval(scriptString); System.out.println(hour); engine.eval("n = 1728"); Object result = engine.eval("n + 1"); System.out.println(result); engine.eval("function Greeter(how) { this.how = how}"); engine.eval("Greeter.prototype.welcome = function(whom) {return this.how + ',' + whom +'!'}"); Object obj = engine.eval("new Greeter('Yo')"); result = ((Invocable) engine).invokeMethod(obj, "welcome", "World"); System.out.println(result.toString()); } }
1. 调试:
IdeaJ 直接运行,报错
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "javax.script.ScriptEngine.eval(String)" because "engine" is null at scriptEngine.EngineTest.main(EngineTest.java:18)
分析原因:
Java 15 及以后版本,移除了 nashorn,导致没有 engine
解决办法:
手动向 Module 中加载 nashorn
下载 nashorn,链接:https://mvnrepository.com/artifact/org.openjdk.nashorn/nashorn-core/15.4
向 Module 中加载,如下图所示
2. 继续调试
IdeaJ报错信息如下:
Exception in thread "main" java.lang.NoClassDefFoundError: org/objectweb/asm/Type at org.openjdk.nashorn.internal.codegen.types.Type.getInternalName(Type.java:405) at org.openjdk.nashorn.internal.codegen.CompilerConstants.className(CompilerConstants.java:286) at org.openjdk.nashorn.internal.codegen.CompilerConstants.staticCallNoLookup(CompilerConstants.java:425) at org.openjdk.nashorn.internal.codegen.types.BooleanType.<clinit>(BooleanType.java:47)
分析原因:
缺少相关类 asm 类,同第一步,下载 asm(注意版本,不要下载 3.x 版本,将与 JDK无法兼容),链接 https://mvnrepository.com/artifact/org.ow2.asm/asm/9.5
同样的调试,根据错误,分析原因,得出,还需要加载:
asm-util,下载链接:https://mvnrepository.com/artifact/org.ow2.asm/asm-util/9.5
至此,脚本正常运行,并生成结果
org.openjdk.nashorn.api.scripting.NashornScriptEngine@78186a70 test javascript 10.0 1729.0 Yo,World!
总结:
因为 JDK 15 以后移除了 nashorn,所以在 JDK 17 中要运行 javascript,需要加载下面三个 jar 包。