java - 使用 Rhino 的 Javascript 解析器,如何获取注释?

标签 java javascript parsing comments rhino

我有一些 javascript 文件并使用 Rhino 的 javascript 解析器解析它。

但是我看不到评论。

如何获取评论?

这是我的部分代码。

运行这段代码,“comment”变量为空。 此外,在运行“astRoot.toSource();”时,它只显示 javascript 代码。不包括评论。它消失了!

[java代码]

public void parser() {
    AstRoot astRoot = new Parser().parse(this.jsString, this.uri, 1);

    List<AstNode> statList = astRoot.getStatements();
    for(Iterator<AstNode> iter = statList.iterator(); iter.hasNext();) {
        FunctionNode fNode = (FunctionNode)iter.next();

        System.out.println("*** function Name : " + fNode.getName() + ", paramCount : " + fNode.getParamCount() + ", depth : " + fNode.depth());

        AstNode bNode = fNode.getBody();
        Block block = (Block)bNode;
        visitBody(block);
    }

    System.out.println(astRoot.toSource());
    SortedSet<Comment> comment = astRoot.getComments();
    if(comment == null)
        System.out.println("comment is null");
}

最佳答案

配置您的 CompilerEnvirons并使用 AstRoot.visitAll(NodeVisitor) :

import java.io.*;
import org.mozilla.javascript.CompilerEnvirons;
import org.mozilla.javascript.Parser;
import org.mozilla.javascript.ast.*;

public class PrintNodes {
  public static void main(String[] args) throws IOException {
    class Printer implements NodeVisitor {
      @Override public boolean visit(AstNode node) {
        String indent = "%1$Xs".replace("X", String.valueOf(node.depth() + 1));
        System.out.format(indent, "").println(node.getClass());
        return true;
      }
    }
    String file = "foo.js";
    Reader reader = new FileReader(file);
    try {
      CompilerEnvirons env = new CompilerEnvirons();
      env.setRecordingLocalJsDocComments(true);
      env.setAllowSharpComments(true);
      env.setRecordingComments(true);
      AstRoot node = new Parser(env).parse(reader, file, 1);
      node.visitAll(new Printer());
    } finally {
      reader.close();
    }
  }
}

Java 6;犀牛 1.7R4

关于java - 使用 Rhino 的 Javascript 解析器,如何获取注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15658569/

相关文章:

java - Android 表单验证 - 如何防止空字段在按下按钮时导致应用程序崩溃?

java - Java 中的二进制搜索错误

java - Spring Caching - 如何管理不同范围的缓存?

javascript - ESC POS 蓝牙打印机清除缓冲区

javascript - 为什么我不能通过只传递它的变量名来运行这个回调,但我可以将它包装在一个函数中?

python - 解析雅虎财经 python httperror 502

java - Spring MVC表单提交: view to controller pass not put form attribute

java - 平面文件解析: when some fields contain the delimiter

具有控制流枚举的 Java 解析器

javascript - 使用 jquery 或 javascript 按钮单击计时器 5 秒