如何在Java 15及更高版本中使用Nashorn? [英] How to use Nashorn in Java 15 and later?

查看:344
本文介绍了如何在Java 15及更高版本中使用Nashorn?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非模块化的现有Spring Boot应用程序,并且使用Nashorn.该应用程序在Java 14上运行良好.

I have an existing Spring Boot application that is non-modular and uses Nashorn. The application works well on Java 14.

添加适用于Java 15的新Nashorn的Maven坐标后,启动脚本引擎时应用程序失败.

After adding the Maven coordinates of the new Nashorn available for Java 15, the application fails while starting the script engine.

public static void main(String[] args) throws ScriptException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("nashorn"); 
    engine.eval("print('Hello, World!');");
} 

错误消息:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "javax.script.ScriptEngine.eval(String)" because "engine" is null
    at xxxxx.yyyy.service.JavaScriptServiceImpl.main(JavaScriptServiceImpl.java:52)

使用Nashorn是否需要对整个项目进行模块化?

Is it required to modularize the whole project to make use of Nashorn?

推荐答案

根据 JEP 372 ,Nashorn已从JDK 15中删除,但是您可以从 https://search.maven.org/artifact/org.openjdk.nashorn/nashorn-core/15.0/jar

According to JEP 372, Nashorn had been removed from JDK 15 but you can get latest nashorn from https://search.maven.org/artifact/org.openjdk.nashorn/nashorn-core/15.0/jar

对于Maven,将以下依赖项包含在您的 pom.xml

For Maven, include the below dependency into your pom.xml

<dependency>
  <groupId>org.openjdk.nashorn</groupId>
  <artifactId>nashorn-core</artifactId>
  <version>15.0</version>
</dependency>

对于Gradle,在您的 build.gradle

For Gradle, include dependency below into your build.gradle

implementation 'org.openjdk.nashorn:nashorn-core:15.0'

不幸的是,独立Nashorn 仅可用作JPMS模块.因此,您可能需要遵循 https://stackoverflow.com/a/46289257 中所述的解决方案,以使其与非-模块化应用.

Unfortunately, Standalone Nashorn is only usable as a JPMS module. So you might need to follow the solution stated in https://stackoverflow.com/a/46289257 to make it work with a non-modular application.

从给定的类 xxxxx.yyyy.service.JavaScriptServiceImpl 中,基于@JornVernee和@AttilaSzegedi的反馈,命令行应类似于

From the given class xxxxx.yyyy.service.JavaScriptServiceImpl and based on feedback from @JornVernee and @AttilaSzegedi, the command line should look like

jdk-15.0.1/bin/java -classpath /home/nashorn-helloworld/target/classes --module-path /home/org/openjdk/nashorn/nashorn-core/15.0:/home/org/ow2/asm/asm/7.3.1:/home/org/ow2/asm/asm-analysis/7.3.1:/home/org/ow2/asm/asm-commons/7.3.1:/home/org/ow2/asm/asm-tree/7.3.1/home/org/ow2/asm/asm-util/7.3.1 --add-modules org.openjdk.nashorn xxxxx.yyyy.service.JavaScriptServiceImpl

这篇关于如何在Java 15及更高版本中使用Nashorn?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆