Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching from Rhino to Nashorn

I have a Java 7 project which makes a lot of use of Javascript for scripting various features. Until now I was using Rhino as script engine. I would now like to move to Java 8, which also means that I will replace Rhino by Nashorn.

How compatible is Nashorn to Rhino? Can I use it as a drop-in replacement, or can I expect that some of my scripts will not work anymore and will need to be ported to the new engine? Are there any commonly-used features of Rhino which are not supported by Nashorn?

like image 562
Philipp Avatar asked Mar 19 '14 10:03

Philipp


People also ask

Is Nashorn deprecated?

The Nashorn engine has been deprecated in JDK 11 as part of JEP 335 and and has been removed from JDK15 as part of JEP 372. GraalVM can step in as a replacement for JavaScript code previously executed on the Nashorn engine. GraalVM provides all the features for JavaScript previously provided by Nashorn.

Why Nashorn is deprecated?

With the release of Java 11, Nashorn was deprecated citing challenges to maintenance, and has been removed from JDK 15 onwards. Nashorn development continues on GitHub as a standalone OpenJDK project and the separate release can be used in Java project from Java 11 and up.

When was Nashorn removed Java?

The deprecation-for-removal of Nashorn in JDK 11 was confirmed in June 2018, causing the proposed removal to be flagged at every use of the jdk.


1 Answers

One problem is that Nashorn can no longer by default import whole Java packages into the global scope by using importPackage(com.organization.project.package);

There is, however, a simple workaround: By adding this line to your script, you can enable the old behavior of Rhino:

load("nashorn:mozilla_compat.js"); 

Another problem I ran into is that certain type-conversions when passing data between java and javascript work differently. For example, the object which arrives when you pass a Javascript array to Java can no longer be cast to List, but it can be cast to a Map<String, Object>. As a workaround you can convert the Javascript array to a Java List in the Javascript code using Java.to(array, Java.type("java.util.List"))

like image 78
Philipp Avatar answered Sep 22 '22 21:09

Philipp