2010-02-24 53 views
1

我为编译单元创建了ASTParser类型的解析器。我想使用这个解析器列出在这个特定的编译单元中存在的函数中的所有变量声明。我应该使用ASTVisitor吗?如果是的话,还有什么其他方式?帮助获取变量声明

回答

2

你可以尝试以下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 
工作区

的AST建成后,可以与顾客穿越它,扩展ASTVisitor,像这样:

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()); 
+0

感谢,多数民众赞成我需要什么 – Steven 2010-02-24 09:21:36