Running ECMAScript 5 compatible javascript in Java 7

I would like to run javascript using the built-in javascript engine of Java 7. The code I'm trying to run is compatible with ECMAScript 5, which should not be a problem, since the built-in version of Rhino 1.7 release 3 that supports it. However, starting the following snippet does not work:

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

Error with an error missing variable namethat indicates that it charis a reserved keyword. However, it is charno longer reserved in ECMAScript 5, so I'm completely confused. The question is, which version of javascript should work with embedded Rhino in java 7?

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

+4
source share
1 answer

As @RealSkeptic noted, the built-in script mechanism of OpenJDK 7 ( Rhino 1.7 r4) has no problems with the javascript fragment running above. It seems that Rhino 1.7 r3it cannot start it, so its launch using Oracle Java 7 requires external Rhino 1.7 r4(or higher), which can be downloaded from here . For completeness only, the java equivalent of the code in the question, based on the Rhino native 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 import declarations are important, because the same classes are available in the JDK in a different package:

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

Importing them leads to using the built-in engine with the Rhino API, which will not work.

+1

Source: https://habr.com/ru/post/1612211/


All Articles