Chriss
Chriss

Reputation: 5639

How to get the type of an annotation using the JDT AST?

I have an IAnnotation instance, how can I get the fully qualified type name of the annotation, if IAnnotation#getElementName() returns the simple name?

    IAnnotation ruleAnnotation = field.getAnnotation("Rule");
    String fullQualifiedName = ???
    if (fullQualifiedName.equals("org.junit.Rule")){
        ...
    }

I found this answer, but this is a different use case: How to determine if a class has an annotation using JDT, considering the type hierarchy

Upvotes: 1

Views: 603

Answers (1)

Stephan Herrmann
Stephan Herrmann

Reputation: 8178

Assuming you speak about org.eclipse.jdt.core.IField and org.eclipse.jdt.core.IAnnotation (part of the "Java Model" - not AST), you should do s.t. along these lines:

IAnnotation ruleAnnotation = field.getAnnotation("Rule");
IType declaringType = field.getDeclaringType();
String elementName = ruleAnnotation.getElementName();
String[][] fullyQualifiedName = declaringType.resolveType(elementName);

Please consult the javadoc of IType.resolveType(String) for extracting the qualified name from the 2-dim array.

Upvotes: 3

Related Questions