【问题标题】:Get outer class name for an inner class Method Declaration using JDT使用 JDT 获取内部类方法声明的外部类名称
【发布时间】:2015-03-19 14:49:31
【问题描述】:

我可以使用 eclipse JDT 获取 Java 中每个方法声明的类名。因此,对于在内部类中声明的方法,我得到了内部类的名称。

是否可以通过使用 JDT 来获取 内部类中声明的方法外部类名

到目前为止,我可以通过以下代码识别一个类是内部类还是外部类:

public boolean visit(TypeDeclaration td) {
    className = td.getName().getFullyQualifiedName();
    if (!td.isPackageMemberTypeDeclaration()) 
            System.out.println(className+" is inner class")

    return true;
}
  • 我知道内部类名,那么是否可以通过 AST 获得它的外部类名?
  • 有什么方法可以获取 AST 解析器当前正在处理的 .java 文件(在解析完整项目时)?

【问题讨论】:

    标签: java eclipse-plugin eclipse-jdt


    【解决方案1】:
    1. 不确定这是否是理想的方式,但您可以使用下面的 sn-p 获取最顶层的 TypeDeclaration(外部类)。

      public static ASTNode getOuterClass(ASTNode node) {
      
          do {
              node= node.getParent();
          } while (node != null && node.getNodeType() != ASTNode.TYPE_DECLARATION
                  && node.isPackageMemberTypeDeclaration());
      
          return node;
      }
      

      然后可以通过以下方式获取类名:

      ASTNode outerClassNode = getOuterClass(methodDeclarationNode);
      if (outerClassNode != null) { // not the topmost node
           System.out.println(outerClassNode.getName());
      }
      
    2. 通常我将CompilationUnit 作为ASTVisitor 类的构造函数参数传递,并从中获取文件名。

    更新:

    另一种获取声明类详细信息的方法:

    typDeclarationNode.resolveBinding().getDeclaredTypes();
    

    如果它是顶级类,这将返回 null。对于内部类,它将返回外部类。

    【讨论】:

    • 我可能遗漏了一些东西,但你肯定可以使用 typeDeclarationNode.resolveBinding().getDeclaringClass() 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-05
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多