开发者

getting variable declarations

开发者 https://www.devze.com 2022-12-20 22:11 出处:网络
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 AST

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 ASTV开发者_JS百科isitor? if so how or is there any other way? help


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

精彩评论

暂无评论...
验证码 换一张
取 消