Switching from Rhino to Nashorn

Philipp picture Philipp · Mar 19, 2014 · Viewed 21.6k times · Source

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?

Answer

Philipp picture Philipp · Mar 19, 2014

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"))