我目前正在開發一個項目,並且我到了需要從給定的Java源代碼中提取所有方法的地步。我需要在antlr v3中實現它,但由於api文檔沒有闡明如何做到這一點,所以我陷入了死衚衕。我也搜遍了官方書,但仍然沒有成功。有任何想法嗎?Antlr v3:在解析樹中打印給定節點的子樹
編輯: 我發現,在ANTLR V4,因爲這是可以做到:
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
ANTLRInputStream input = new ANTLRInputStream(System.in);
JavaLexer lexer = new JavaLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
JavaParser parser = new JavaParser(tokens);
ParseTree tree = parser.compilationUnit();
ParseTreeWalker walker = new ParseTreeWalker();
MethodPrinter printer = new MethodPrinter();
walker.walk(printer, tree);
for (String method : printer.methods)
System.out.println(method);
}
}
其中Method printer
作爲實施:
import org.antlr.v4.runtime.tree.TerminalNode;
import java.util.ArrayList;
public class MethodPrinter extends JavaBaseListener {
boolean inMethod;
String currentMethod;
ArrayList<String> methods;
public MethodPrinter() {
inMethod = false;
methods = new ArrayList<String>();
}
public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) {
inMethod = true;
currentMethod = "";
}
public void exitMethodDeclaration(JavaParser.MethodDeclarationContext ctx) {
inMethod = false;
methods.add(currentMethod);
}
public void visitTerminal(TerminalNode node) {
if (inMethod)
currentMethod += node.getText() + " ";
}
}
這可怎麼在實施antlr v3?
你可以給你想要的輸出的例子嗎? –