编程语言
首页 > 编程语言> > 无法使用NashornscriptEngine在Java 8上执行es6

无法使用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

我认为我的scriptEngine正在将脚本读取为ES6.

我在这里做错了什么?

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

解决方法:

Nashorn @ Java8_u40仅支持有限的ES6功能. ES5比ES6多.查看JEP 292: Implement Selected ECMAScript 6 Features in Nashorn

箭头功能是Java 9更新版本的时间表.

标签:java-8,nashorn,scriptengine,java
来源: https://codeday.me/bug/20191025/1929863.html