随笔 - 148  文章 - 3  评论 - 2  阅读 - 11万

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 包。

 

posted on   bruce_he  阅读(3352)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示