views:

25

answers:

1

hi, i created a parser of ASTParser type for a compilationunit. I want to use this parser to list all the variable declarations in the functions present in this particular compilationunit.Should i use ASTVisitor? if so how or is there any other way? help

+1  A: 

You can try following this thread

you should have a look at org.eclipse.jdt.core plugin and specially ASTParser class there.
Just to launch the parser, the following code would be enough:

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

in workspace.

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;
  }
});

More details and code sample in 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());
VonC
thanks thats what i needed
Steven