简体   繁体   English

使用 Eclipse JDT AST 从 Annotation 获取完全限定名称

[英]Obtaining the fully qualified name from an Annotation using Eclipse JDT AST

I am using the Eclipse JDT to build AST for Java source code, so I can do some code analysis.我正在使用 Eclipse JDT 为 Java 源代码构建 AST,所以我可以做一些代码分析。 Currently I would like to obtain the fully qualified name of an annotation.目前我想获取注释的完全限定名称。 Consider the code below:考虑下面的代码:

import javax.persistence.Entity; 

@Entity
public class Class1

If I visit this Compilation Unit, the @Entity is a MarkerAnnotation.如果我访问这个编译单元,@Entity 是一个 MarkerAnnotation。 And I can do some analysis on it.我可以对此做一些分析。 However I am unable to obtain the Fully qualified name.但是我无法获得完全限定的名称。 I would like to obtain "javax.persistence.Entiy".我想获得“javax.persistence.Entiy”。 I have tried several ways, but with no success.我尝试了几种方法,但没有成功。

public boolean visit(MarkerAnnotation node) {
        node.getTypeName(); //returns the simple name
        node.getTypeName().getFullyQualifiedName();// I thought this would print javax.persistence.Entiy, 
                                                   // but it only prints "Entity"
        node.resolveTypeBinding().getName(); //Prints "Entity"
        node.resolveTypeBinding().getBinaryName(); // Prints "Entity"
        node.resolveAnnotationBinding().getName(); //Prints "Entity"
        return super.visit(node);
    }

I have also tried to cast MarkerAnnotation to Annotation, but I am still unable to get fully qualified name.我也尝试将 MarkerAnnotation 转换为 Annotation,但我仍然无法获得完全限定的名称。 During debugging sesssions, I had no success either navigating this node在调试会话期间,我导航此节点都没有成功

I was able to get the fully qualified name using the imports() method of the CompilationUnit.我能够使用 CompilationUnit 的 imports() 方法获得完全限定的名称。 I did some String manipulations on them, combining with the annotations simple name.我对它们进行了一些字符串操作,并结合了注释简单名称。 However, I feel this is sort of hacky, and I need to look at every import, even ones that are not related to annotations.但是,我觉得这有点 hacky,我需要查看每个导入,即使是与注释无关的导入。

What I would like is to obtain the fully qualified name directly from the node, ie, from the MarkerAnnotation, NormalAnnotation and SingleMemberAnnotation.我想要的是直接从节点获取完全限定名称,即从 MarkerAnnotation、NormalAnnotation 和 SingleMemberAnnotation。 Is there any way to achieve this?有什么办法可以做到这一点? What Am I missing here?我在这里想念什么?

Thanks in advance!提前致谢!

From the javadoc of Annotation.resolveAnnotationBinding() :来自Annotation.resolveAnnotationBinding()的javadoc:

Note that bindings (which includes resolved annotations) are generally unavailable unless requested when the AST is being built.请注意,除非在构建 AST 时请求,否则绑定(包括已解析的注释)通常不可用。

So please check how you configure ASTParser , see ASTParser.setResolveBindings(boolean)所以请检查您如何配置ASTParser ,请参阅ASTParser.setResolveBindings(boolean)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM