15

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?

Brian Goetz
  • 90,105
  • 23
  • 150
  • 161
JustMe
  • 366
  • 1
  • 4
  • 14

1 Answers1

20

The Nashorn JavaScript Engine has been removed from Java. Deprecated in Java 11, removed in Java 15.

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,...

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • Thanks, but unfortunately due to project constrains, I am not allowed to use third party libraries. If it is not in the standard jdk, i cannot use it. – JustMe Mar 15 '22 at 11:59
  • 1
    @JustMe can you execute expression on your database? if not check `Boann` answer in https://stackoverflow.com/questions/3422673/how-to-evaluate-a-math-expression-given-in-string-form – Ori Marko Mar 15 '22 at 12:04
  • @JustMe silly but it happens. In that case use another scripting language (not sure which are still supported, if any) or write your own (not trivial, but in a place where you're not allowed to use anything written by others, such is life). – jwenting May 12 '23 at 06:41
  • Can you offload it to a separate process? i.e. in a different docker container. I am thinking of doing something similar myself in order to isolate the main container from the scripting cointainer. – Archimedes Trajano Jul 18 '23 at 23:41