我目前正在做一个项目,我需要从给定的 Java 源代码中提取所有方法。我需要在antlr v3中实现它,但我走到了死胡同,因为 api 文档没有说明如何做到这一点。我也搜索了官方书籍,但仍然没有成功。有任何想法吗?
编辑:我发现在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中实现?