无法使用 NashornscriptEngine 在 Java 8 上执行 es6



我正在尝试在java 8(1.8.0_102)中执行javascript(ES6)函数。

这是精简的片段javascript。

 const myfunc = (args) => {
   if (!(args.name || args.zip))
return
  const result = {...args}
  const { name, zip, date } = result
...
}

这是我的java代码

public static Object processArbitraryJavaScript(String params)
    {
        String[] options = new String[] {"--language=es6"};
        NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
        NashornScriptEngine engine = (NashornScriptEngine) factory.getScriptEngine(options);
        Object result = null;
        try
        {
            engine.eval(new FileReader("sample.js"));
            Invocable inv = (Invocable) engine;
            result = inv.invokeFunction("myfunc", params);
        }
        catch (ScriptException scriptException )
        {
            LOGGER.error(
                    "ScriptException encountered trying to write arbitrary JavaScript"
                            + scriptException.toString());
        }
        catch (NoSuchMethodException e) {
            LOGGER.error(
                    "No such Method");
        }
        return result;
    }

我写了一个通过参数的单元测试。 当我执行测试时,我得到这个异常

ScriptException encountered trying to write arbitrary JavaScriptjavax.script.ScriptException: <eval>:2:5 Expected : but found (
  if (!(args.name || args.zip))
     ^ in <eval> at line number 2 at column number 5

我在javascript中注释掉了if语句,但在代码中看到更多的错误。

 ScriptException encountered trying to write arbitrary JavaScriptjavax.script.ScriptException: <eval>:5:8 Expected : but found result
  const result = {...args}
        ^ in <eval> at line number 5 at column number 8

再往下,我看到这个错误

ScriptException encountered trying to write arbitrary JavaScriptjavax.script.ScriptException: <eval>:6:6 Expected: but found {
  const { name, zip, date } = result
      ^ in <eval> at line number 6 at column number 6

我认为我的脚本引擎正在将脚本读取为 ES6。

我在这里做错了什么?

(顺便说一句,脚本在 JS 中工作正常)。

Nashorn @Java8_u40+ 仅支持有限数量的 ES6 功能。它比ES6更像ES5+。参见 JEP 292:在 Nashorn 中实现选定的 ECMAScript 6 特性

箭头函数是 Java 9 更新发行版的计划。

根据文档,我们可以通过提供jvm option: ["-Dnashorn.args=--language=es6"]

指https://developer.oracle.com/databases/nashorn-javascript-part2.html

这也适用于JDK 8,尽管功能将受到限制

最新更新