Search code examples
javaabstract-syntax-treeeclipse-jdt

Getting value from Annotation


I am trying to get the value/values specified inside an Annotation.

eg: If @SuppressWarnings("unchecked") is the annotation, i want to to get the value - unchecked.

public boolean visit(SingleMemberAnnotation annotation) {

    // returns the type name of the annotation - SuppressWarnings
    annotation.getTypeName();       

    return true;
}

Didn't see any methods inside the Annotation class to retrieve the same.
Any help/pointers are appreciated


Solution

  • As you are visiting a SingleMemberAnnotation you should look into the SingleMemberAnnotation class rather than Annotation. As you can see it has a getValue method which returns an Expression. This is the simplified case where you only have one expression like in @SuppressWarnings("unchecked").

    For ordinary annotations you will encounter a NormalAnnotation which will have a list of values which you can retrieve using the intuitively named method values().

    So, since these two types of annotation nodes are that different regarding how to retrieve the values, there is no such method in their common Annotation base class. For immutable nodes it would be possible to treat them more abstract representing the single member annotation’s value as a list of size one, however, since these AST nodes are mutable, i.e. the list returned by NormalAnnotation.values() supports adding, it can’t be provided on the base class.