简体   繁体   中英

Running ECMAScript 5 compliant javascript on Java 7

I would like to run javascript using the embedded javascript engine of Java 7. The code which I am trying to run is ECMAScript 5 compliant, which should not be a problem since the embedded Rhino's version is 1.7 release 3 which supports it. Yet, running the following snippet doesn't work:

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    engine.eval("var char = 'a';");

It fails with the error missing variable name which indicates that char is a reserved keyword. However, the char is no longer reserved in ECMAScript 5, so I am completely confused. The question is which javascript version is supposed to work with the embedded Rhino in java 7?

I am using java 1.7.0_80 , the language version reported by the engine is 1.8 and the engine version is 1.7 release 3 PRERELEASE .

As @RealSkeptic pointed out, the embedded script engine of OpenJDK 7 ( Rhino 1.7 r4 ) has no problem running the above javascript snippet. It seems that Rhino 1.7 r3 can not run it, so running it using Oracle Java 7 needs the external Rhino of 1.7 r4 (or above) which can be downloaded from here . Just for completeness, the java equivalent of the code in the question based on Rhino's own API looks like this:

import org.mozilla.javascript.Context;
import org.mozilla.javascript.ScriptableObject;

public class Rhino {

    public static void main(String[] args) throws Exception {
        Context context = Context.enter();
        try {
            ScriptableObject scope = context.initStandardObjects();
            context.evaluateString(scope, "var char = 'a'", "test", 1, null);
        } finally {
             Context.exit();
        }
   }

}

Note that the import declarations are important since the same classes are available bundled in the JDK within a different package:

import sun.org.mozilla.javascript.internal.Context;
import sun.org.mozilla.javascript.internal.ScriptableObject;

Importing them yields in using the embedded engine with Rhino's API which will not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM