JDK 8 上的 Nashorn 解析器 API

Nashorn Parser API on JDK 8

寻找 Java/JDK API 来解析 JavaScript(包括 Nashorn 扩展)我偶然发现了 this Gist,根据内联评论需要 JDK 9 到 运行。有没有一种可靠的方法可以在 JDK 8 的当前或计划发布的版本上完成相同的工作?

Nashorn 解析器 API ( http://openjdk.java.net/jeps/236 ) 是特定于 jdk9 的 API。在 jdk8 或 jdk8 更新中,支持脚本解析器功能。

加载("nashorn:parser.js");

并从脚本中调用 "parse" 函数。此函数 returns 一个 JSON 对象,表示已解析脚本的 AST。

查看示例:http://hg.openjdk.java.net/jdk8u/jdk8u-dev/nashorn/file/bfea11f8c8f2/samples/astviewer.js

虽然您绝对可以通过 Nashorn 的 Java 脚本使用解析器,但在 Java 中通过 JAVA API

使用它会更好
    import jdk.nashorn.api.scripting.ScriptUtils;
    import jdk.nashorn.internal.runtime.Context;
    import jdk.nashorn.internal.runtime.ECMAException;
    import jdk.nashorn.internal.runtime.ErrorManager;
    import jdk.nashorn.internal.runtime.options.Options;

    // set up the environment
    Options options = new Options("nashorn");
    options.set("anon.functions", true);
    options.set("parse.only", true);
    options.set("scripting", true);

    ErrorManager errors = new ErrorManager();
    Context contextm = new Context(options, errors, Thread.currentThread().getContextClassLoader());
    Context.setGlobal(contextm.createGlobal());


    // then for each bit of parsing
    String parseTree = ScriptUtils.parse(some_code_string, "nashorn", false);