2

我需要使用 Java 和 Rhino 在 Javascript 文件中搜索所有出现的特定 Javascript 函数。我已经成功地使用访问者模式浏览了所有出现的函数调用(参见下面的代码),但我无法检索被调用函数的名称。哪种方法是正确的?

package it.dss.javascriptParser;


import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

import org.mozilla.javascript.Parser;
import org.mozilla.javascript.ast.AstNode;
import org.mozilla.javascript.ast.FunctionCall;
import org.mozilla.javascript.ast.NodeVisitor;

public class JavascriptParser {

public static void main(String[] args) throws IOException {
    class Printer implements NodeVisitor {

        public boolean visit(AstNode node) {
            if (node instanceof FunctionCall) {
                              // How do I get the name of the function being called?

            }
            return true;
        }
    }

    String file = "/dss2.js";
    Reader reader = new FileReader(file);
    try {
        AstNode node = new Parser().parse(reader, file, 1);
        node.visit(new Printer());
    } finally {
        reader.close();
    }
}
}
4

2 回答 2

3

FunctionCall 类只代表函数的调用,它的目标是函数名(org.mozilla.javascript.ast.Name)。

要获取调用函数的名称,请使用:

AstNode target = ((FunctionCall) node).getTarget();
Name name = (Name) target;
System.out.println(name.getIdentifier());
于 2013-02-08T15:49:00.560 回答
2

FunctionCall您可以通过执行以下操作检索函数名称:

((FunctionCall) node).getTarget().getEnclosingFunction().getFunctionName();

注意:匿名函数将返回null.

给定函数名称和访问者模式,您可以轻松找出任何命名函数的出现。

于 2013-02-08T15:26:33.527 回答