Search code examples
javaabstract-syntax-treeeclipse-jdt

Obtaining the fully qualified name from an Annotation using Eclipse JDT AST


I am using the Eclipse JDT to build AST for Java source code, so I can do some code analysis. Currently I would like to obtain the fully qualified name of an annotation. Consider the code below:

import javax.persistence.Entity; 

@Entity
public class Class1

If I visit this Compilation Unit, the @Entity is a MarkerAnnotation. And I can do some analysis on it. However I am unable to obtain the Fully qualified name. I would like to obtain "javax.persistence.Entiy". I have tried several ways, but with no success.

public boolean visit(MarkerAnnotation node) {
        node.getTypeName(); //returns the simple name
        node.getTypeName().getFullyQualifiedName();// I thought this would print javax.persistence.Entiy, 
                                                   // but it only prints "Entity"
        node.resolveTypeBinding().getName(); //Prints "Entity"
        node.resolveTypeBinding().getBinaryName(); // Prints "Entity"
        node.resolveAnnotationBinding().getName(); //Prints "Entity"
        return super.visit(node);
    }

I have also tried to cast MarkerAnnotation to Annotation, but I am still unable to get fully qualified name. During debugging sesssions, I had no success either navigating this node

I was able to get the fully qualified name using the imports() method of the CompilationUnit. I did some String manipulations on them, combining with the annotations simple name. However, I feel this is sort of hacky, and I need to look at every import, even ones that are not related to annotations.

What I would like is to obtain the fully qualified name directly from the node, i.e, from the MarkerAnnotation, NormalAnnotation and SingleMemberAnnotation. Is there any way to achieve this? What Am I missing here?

Thanks in advance!


Solution

  • From the javadoc of Annotation.resolveAnnotationBinding():

    Note that bindings (which includes resolved annotations) are generally unavailable unless requested when the AST is being built.

    So please check how you configure ASTParser, see ASTParser.setResolveBindings(boolean)