2010-02-24 52 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