0

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?

0

1 Answer 1

0

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());
    }
});
9
  • Can't test right now, but I believe that your problem may be that the sample code you are trying to parse does not include a type declaration; Eclipse's parser is relatively forgiving, but the exact behaviour is sometime hard to predict when the input is not perfectly valid. Try adding public class xxx { ... } around your sample code.
    – James
    Oct 1, 2018 at 16:01
  • Alternatively, I think that setting the parser's kind to K_CLASS_BODY_DECLARATIONS would make it assume that it is inside a type definition, so you wouldn't need to add the type definition around your sample code.
    – James
    Oct 1, 2018 at 16:04
  • I post Answer with an image .stackoverflow.com/a/52596635/4555727 Oct 1, 2018 at 18:22
  • I don’t understand what you mean by this image... i.stack.imgur.com/MuJCi.png Do you want to also produce an image that looks like the image you provided? Or do you want to produce text where information follow some formal presentation? If so, can you provide an example of what would be a correctly formated tect?
    – James
    Oct 1, 2018 at 18:34
  • sir, How can I contact with you for some Questions related in this topic Oct 1, 2018 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.