-->

如何确定一类具有使用JDT注释,考虑到类型层次(How to determine if a clas

2019-10-18 17:59发布

有一个简单的方法来检查,如果注释出现在使用Eclipse JDT一个ICompilationUnit?

我试着做下面的代码,但我会做同样的事情为超级类。

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;
}

我知道这是可能与ASTParser解决绑定,但我没有找到一个方法来检查的注释存在。 有没有简单的API做这样的事情?

Answer 1:

是的,你可以使用ASTVisitor并覆盖你需要的方法。 因为,有注记类型: MarkerAnnotationNormalAnnotation等。

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..});

例如正常注释:

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

顺便说一句,请注意以下差异:

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

@java.lang.Deprecated


文章来源: How to determine if a class has an annotation using JDT, considering the type hierarchy