![](/img/trans.png)
[英]How to get values from a Java HashMap in javascript function using Rhino
[英]How to find all the occurrences of a Javascript function using Java and Rhino
我需要使用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();
}
}
}
FunctionCall類僅表示函數的調用,其目標是函數名稱(org.mozilla.javascript.ast.Name)。
要獲取被調用函數的名稱,請使用:
AstNode target = ((FunctionCall) node).getTarget();
Name name = (Name) target;
System.out.println(name.getIdentifier());
從FunctionCall
您可以通過執行以下操作檢索函數名稱:
((FunctionCall) node).getTarget().getEnclosingFunction().getFunctionName();
注意:匿名函數將返回null
。
給定函數名稱和訪問者模式,您可以輕松找出任何命名函數的出現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.