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

老子叫甜甜 提交于 2019-12-24 15:07:53

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/19230505/how-to-determine-if-a-class-has-an-annotation-using-jdt-considering-the-type-hi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!