我为编译单元创建了一个 ASTParser 类型的解析器。我想使用此解析器列出此特定编译单元中存在的函数中的所有变量声明。我应该使用 ASTVisitor 吗?如果是这样怎么办或者还有其他办法吗?帮助
最佳答案
您可以尝试关注this thread
你应该看看org.eclipse.jdt.core
插件,特别是ASTParser
在那里上课。
只需启动解析器,以下代码就足够了:
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT); // you tell parser, that source is whole java file. parser can also process single statements
parser.setSource(source);
CompilationUnit cu = (CompilationUnit) parser.createAST(null); // CompilationUnit here is of type org.eclipse.jdt.core.dom.CompilationUnit
// source is either char array, like this:
public class A { int i = 9; int j; }".toCharArray()
//org.eclipse.jdt.core.ICompilationUnit type, which represents java source files
在工作区中。
after the AST is built, you can traverse it with visitor, that extends
ASTVisitor
, like this:
cu.accept(new ASTVisitor() {
public boolean visit(SimpleName node) {
System.out.println(node); // print all simple names in compilation unit. in our example it would be A, i, j (class name, and then variables)
return true;
}
});
更多详细信息和代码示例位于 this thread
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(compilationUnit);
parser.setSourceRange(method.getSourceRange().getOffset(), method.getSourceRange().getLength());
parser.setResolveBindings(true);
CompilationUnit cu = (CompilationUnit)parser.createAST(null);
cu.accept(new ASTMethodVisitor());
关于java - 获取变量声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2324642/