Java 17 中使用 ScriptEngine 解析 JavaScript 脚本

Java JavaScript About 1,164 words

ScriptEngine

ScriptEngine位于javax.script包下,Java 17中依然可用(移除的是Nashorn模块)。

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine e = mgr.getEngineByName("JavaScript");

String t = "5*7";
System.out.println(e.eval(t).toString());

Nashorn

Nashorn模块在Java 11中被标记为过时,在Java 15中被移除。

查看可用脚本引擎

备注:GraalVM默认只有占位的Placeholder引擎(仅占位,无任何作用)。

new ScriptEngineManager().getEngineFactories();

graal.js

添加依赖

js这个依赖大小为23MBjs-scriptengine大小为600KB

<dependency>
  <groupId>org.graalvm.js</groupId>
  <artifactId>js</artifactId>
  <version>22.3.0</version>
</dependency>

<dependency>
  <groupId>org.graalvm.js</groupId>
  <artifactId>js-scriptengine</artifactId>
  <version>22.3.0</version>
</dependency>

代码

// Graal
ScriptEngine graalEngine = new ScriptEngineManager().getEngineByName("graal.js");
graalEngine.eval("print('Hello World!');");

替代品

迁移到 GraalVM JavaScript

https://docs.oracle.com/en/graalvm/enterprise/22/docs/reference-manual/js/NashornMigrationGuide

OpenJDK Nashorn 定制版本

https://github.com/openjdk/nashorn

AviatorScript

https://github.com/killme2008/aviatorscript

Views: 2,899 · Posted: 2023-06-22

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Today On History
Browsing Refresh