简体   繁体   中英

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, ie, from the MarkerAnnotation, NormalAnnotation and SingleMemberAnnotation. Is there any way to achieve this? What Am I missing here?

Thanks in advance!

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)

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