简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM