简体   繁体   English

如何使用Java和Rhino查找所有出现的Javascript函数

[英]How to find all the occurrences of a Javascript function using Java and Rhino

I need to search for all the occurrences of a particular Javascript function in a Javascript file using Java and Rhino. 我需要使用Java和Rhino搜索Javascript文件中所有特定Javascript函数的出现。 I have succeeded in browsing all the occurrences of function calls using the Visitor pattern (see code below), but I have not been able to retrieve the name of the function been called. 我已经使用“访问者”模式成功浏览了所有发生的函数调用(请参见下面的代码),但是我无法检索被调用函数的名称。 Which is the correct way to do it? 哪个是正确的方法?

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();
    }
}
}

FunctionCall class represents just invocation of function, its target is function name (org.mozilla.javascript.ast.Name). FunctionCall类仅表示函数的调用,其目标是函数名称(org.mozilla.javascript.ast.Name)。

To get name of invoked function use: 要获取被调用函数的名称,请使用:

AstNode target = ((FunctionCall) node).getTarget();
Name name = (Name) target;
System.out.println(name.getIdentifier());

From the FunctionCall you can retrieve the function name by doing the following: FunctionCall您可以通过执行以下操作检索函数名称:

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

Note: Anonymous functions will return null . 注意:匿名函数将返回null

Given the function name and the visitor pattern you can easily find out the occurrences of any named function. 给定函数名称和访问者模式,您可以轻松找出任何命名函数的出现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM