Search code examples
javaeclipseeclipse-jdt

How to determine if a class has an annotation using JDT, considering the type hierarchy


There is a simple way to check if an annotation is present in a ICompilationUnit using Eclipse JDT?

I tried to do the code below, but I will have to do the same thing for the super classes.

IResource resource = ...;

ICompilationUnit cu = (ICompilationUnit) JavaCore.create(resource);

// consider only the first class of the compilation unit
IType firstClass = cu.getTypes()[0];

// first check if the annotation is pressent by its full id
if (firstClass.getAnnotation("java.lang.Deprecated").exists()) {
    return true;
}

// then, try to find the annotation by the simple name and confirms if the full name is in the imports 
if (firstClass.getAnnotation("Deprecated").exists() && //
    cu.getImport("java.lang.Deprecated").exists()) {
    return true;
}

I know it is possible to resolve bindings with the ASTParser, but I didn't find a way to check if an annotation is present. Is there any simple API to do such thing?


Solution

  • Yes, you can use ASTVisitor and override the methods you need. Since, there are types of annotation: MarkerAnnotation, NormalAnnotation, etc.

    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setSource(charArray);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    
    final CompilationUnit cu = (CompilationUnit) 
    parser.createAST(null);
    cu.accept(new ASTVisitor(){..methods..});
    

    For example normal annotation:

    @Override
    public boolean visit(NormalAnnotation node) {
        ...
    }
    

    Btw, be careful about the diff below:

    import java.lang.Deprecated;
    ...
    @Deprecated
    

    and

    @java.lang.Deprecated