Java 8 Javascript Engine backwards compatibility

nikkatsa picture nikkatsa · Mar 19, 2014 · Viewed 11.2k times · Source

I am trying out Java 8 in my project and I am stuck in an error related to my build process.

I am using ANT scripts and at some point i am using some javascript (embeded into ANT) to do some build specific operations. The part of the script that is causing the error looks like below:

<script language="javascript"> 

        <![CDATA[

        importClass(java.io.File);
        importClass(java.io.FileReader);
                    ...
                    ]]>
</script>

The project is building fine with Java 7 or Java 6, but it gives me some errors when i am using Java 8. These errors are related to the upgrade of the JS engine.

In particular i am getting the following exception:

javax.script.ScriptException: ReferenceError: "importClass" is not defined in at line

After some googling i found out that it is related to the below issue in the JDK

[#JDK-8025132]

I tried what is suggested in the comments but without luck.

How can I make Java 8 Nashorn engine to be compatible with the Rhino JS engine?

Answer

wickund picture wickund · Mar 20, 2014

One approach is to include

load("nashorn:mozilla_compat.js");

which supplies importClass.

On the other hand, you can use java.io.File, java.io.FileReader, ... directly without importing.

var File = java.io.File;
var FileReader = java.io.FileReader;

This is backward compatible with Rhino.