I have to move a project from Java 8 to Java 17.
I could solve most issues, but it contains a method, in which I use the ScriptEngineManager to evaluate a mathematical term.
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine e = mgr.getEngineByName("JavaScript");
String t = "5*7";
if (isMathTerm(t)) {
System.out.println(e.eval(t).toString());
}
In Java 8 it works as required, but in Java 17 e is always null.
According to google, the JavaScript Engine is no longer supported in Java 17.
Due to project constraints, I am not allowed to use third party libraries.
Is there a proper way to handle this in Java 17?
Java 15 removed Nashorn JavaScript Engine
So you need to use different script engine, as GraalVM
switch to the GraalVM JavaScript engine. First, add the required dependencies to your project.
<dependency> <groupId>org.graalvm.js</groupId> <artifactId>js</artifactId> <version>22.0.0</version> </dependency> <dependency> <groupId>org.graalvm.js</groupId> <artifactId>js-scriptengine</artifactId> <version>22.0.0</version> </dependency>
Then change the engine name to graal.js.
// Graal ScriptEngine graalEngine = new ScriptEngineManager().getEngineByName("graal.js"); graalEngine.eval("print('Hello World!');");
You can check which engines available using
new ScriptEngineManager().getEngineFactories();
Or add different script engines to your project as velocity, jexl, groovy,...