考虑类型层次结构,如何确定类是否具有使用JDT的注释 [英] How to determine if a class has an annotation using JDT, considering the type hierarchy
问题描述
有一个简单的方法来检查ICompilationUnit中使用Eclipse JDT的批注是否存在?我尝试下面的代码,但是我必须为超级班做同样的事情。
IResource resource = ...;
ICompilationUnit cu =(ICompilationUnit)JavaCore.create(resource);
//仅考虑编译单元的第一个类
IType firstClass = cu.getTypes()[0];
//首先检查注释是否被其全部id
加注如果(firstClass.getAnnotation(java.lang.Deprecated)。exists()){
return真正;
}
//然后,尝试通过简单的名称查找注释,并确认全名是否在导入
if(firstClass.getAnnotation(Deprecated) .exists()&&&$ //
cu.getImport(java.lang.Deprecated)。exists()){
return true;
}
我知道有可能解决与ASTParser的绑定,找到一个方法来检查注释是否存在。
有没有简单的API做这样的事情?
是的,你可以使用ASTVisitor并覆盖你的方法需要。由于有注释类型:MarkerAnnotation,NormalAnnotation等。
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){
....
}
Btw,请关注下面的diff:
import java。 lang.Deprecated;
...
@Depracted
和
@ java.lang.Deprecated
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?
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 carefull about the diff below:
import java.lang.Deprecated;
...
@Depracted
and
@java.lang.Deprecated
这篇关于考虑类型层次结构,如何确定类是否具有使用JDT的注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!