Search code examples
javaparsingabstract-syntax-treeeclipse-jdt

Get Abstract Syntax tree for Java method using JDT Eclipse


I'm working on a project that must use Eclipse JDT for parsing java methods and generating Abstract Syntax tree for them I wrote the following code :

String method ="\n"+
    "   public void sayHello() {\n"+
    "   System.out.println(\"Hello \"+name+\"!\");\n"+
    "   }\n";
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(method.toCharArray());
parser.setResolveBindings(true);
parser.setBindingsRecovery(true);
CompilationUnit unit = (CompilationUnit)parser.createAST(null);

This snippet just creates AST, but I get stuck!! I'd like to visit AST of any java method and print its path. Can I get print AST for java Method?


Solution

  • Eclipse AST (as most AST actually) exploit the visitor pattern extensively.

    So from the point you are, all you have to do is to instantiate a visitor, and make it visit the compilation unit. It will then automatically navigate fields, methods, annotations...

    For your specific need, I think you can start with the following code:

    unit.accept(new ASTVisitor() {
    
        @Override
        public boolean visit(MethodDeclaration node) {
            Type ownerTypeNode = (Type) node.getParent();
            System.out.println("Found method " + node.getName().getFullyQualifiedName() " + " in type " + ownerTypeNode.getName().getFullyQualifiedName());
        }
    });