0

I am using a library to evaluate a boolean expression as a string. With the library I get the following warning with Java 11:

NashornScriptEngineFactory in jdk.nashorn.api.scripting has been deprecated and marked for removal

However, I am a little unclear about this. I am using the following code and I don't see Nashorn referenced in this code but yet the warning still persists.

ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); Boolean val = (Boolean) engine.eval(ruleString);

My question is does this warning still apply to this piece of code? Also, if it does, is there another alternative that I can use?

Thanks in advance for the help.

Greg Abel
  • 49
  • 1
  • 3
  • Off-topic request for offsite resources; but the answer you seek is [Rhino](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino) (and maybe, someday, [Graal](https://github.com/graalvm/graaljs)). – Elliott Frisch Nov 12 '19 at 21:45
  • Or continue to use the unbundled Nashorn. Or use a different technology for evaluating expressions. – Stephen C Jan 02 '21 at 08:46

2 Answers2

1

Nashorn is the default Javascript engine for Java 8+. So doing this:

ScriptEngine engine = factory.getEngineByName("JavaScript")

Starts the nashorn javascript engine.

So yes, the fact that nashorn is deprecated (by this JEP) does affect this code, however oracle will support java 11 until September 2026 (described here) so you are good on java 11 with patches etc until at least then.

Furthermore, deprecation means "marked for removal at some point in the future", not actually removed from the JDK, so it may sneak into the next LTS JDK as well.

To keep using javascript on the JVM, the options are:

  • go back to Rhino (not very enticing as it's slow - it doesn't use newer byte code instructions like invokedynamic)
  • migrate to GraalVM graaljs. this is probably the best option as you get modern ECMAscript (2019), it's meant to be production ready and builds native binaries for many target platforms.
stringy05
  • 6,511
  • 32
  • 38
0

For simple expressions you could use the Spring Expression Language (SpEL):

https://www.baeldung.com/spring-expression-language

        val car = Car("Honda", "Jazz", year = 2020)
        val context: EvaluationContext = StandardEvaluationContext(car)
        val expression = expressionParser.parseExpression("year - 2000")
        val result = expression.getValue(context) // = 20
Andrejs
  • 26,885
  • 12
  • 107
  • 96