Tuesday, April 21, 2015

Using Rhino with Java 8

Java brings Nashorn as new JavaScript implementation for JSR 223 (javax.scripting). While this is certainly great news (Nashorn is way faster than Rhino by directly generating Java code), it comes with some challenges: Nashorn is not 100% compatible with Rhino.

Rhino had some extensions and more or less other interpretations on how to combine the Java world with JavaScript. Therefore you cannot simply replace Rhino by Nashorn. One case (which ruined our day) is that you cannot call static methods on instances. Therefore we had to get Rhino up and running in Java 8 until we have our scripts re-written.

Although there is an extensive documentation available in java.net, it is a bit confusing (some URLs are wrong, some steps are missing). So here are the steps which worked for us:

  1. Download Rhino: https://github.com/downloads/mozilla/rhino/rhino1_7R4.zip 
  2. Download JSR-223: svn checkout svn checkout https://svn.java.net/svn/scripting~svn
    Yes that is a ~ in the URL!
  3. cd scripting~svn/trunk/engines/javascript/lib
  4. Copy the js.jar from rhino1_7R4.zip into this directory (replace the existing js.jar)
  5. cd ../make
  6. ant clean all
  7. Copy ../build/js-engine.jar AND js.jar (of Rhino) into your classpath
  8. Now change:

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");


    to:

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("rhino");

That's all you need to backport Rhino to Java 8. 

Update: Here's another tutorial on this Topic: Java 8 Features Tutorial