简体   繁体   English

使用JDT获取内部类方法声明的外部类名称

[英]Get outer class name for an inner class Method Declaration using JDT

I can get the class name for each method declaration in Java by using eclipse JDT. 我可以使用Eclipse JDT获得Java中每个方法声明的类名。 So, for a method declared in an inner class, I get the name of the inner class. 因此,对于在内部类中声明的方法,我得到内部类的名称。

Is it possible to get the outer class name for a method declared in an inner class by using JDT. 是否有可能通过使用JDT获得在内部类中声明方法外部类名称

So far, I'm able to identify whether a class is an inner class or outer class by the following code: 到目前为止,我可以通过以下代码确定一个类是内部类还是外部类:

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

    return true;
}
  • As I know the inner class name, so is it possible to get it's outer class name by the AST? 据我所知,内部类名称是否可以通过AST获得外部类名称?
  • Is there any way to get which .java file the AST parser is processing currently (when a full project is being parsed)? 有什么方法可以获取AST解析器当前正在处理哪个.java文件(正在解析完整的项目时)?
  1. Not sure if this is the ideal way, but you can use the below snippet to get the topmost TypeDeclaration (Outer class). 不确定这是否是理想的方法,但是您可以使用下面的代码片段获取最顶层的TypeDeclaration (外部类)。

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

    Then you can get the class name by: 然后可以通过以下方式获取类名称:

     ASTNode outerClassNode = getOuterClass(methodDeclarationNode); if (outerClassNode != null) { // not the topmost node System.out.println(outerClassNode.getName()); } 
  2. Usually I pass the CompilationUnit as a constructor argument for the ASTVisitor class, and get the file name from same. 通常,我将CompilationUnit作为ASTVisitor类的构造函数参数ASTVisitor ,并从ASTVisitor类获取文件名。

UPDATE: 更新:

Another way to get the declaring class details: 另一种获取声明类详细信息的方法:

typDeclarationNode.resolveBinding().getDeclaredTypes();

This will return null, if it is a Top-level class. 如果它是顶级类,则将返回null。 For inner class, it will return the Outer classes. 对于内部类,它将返回外部类。

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

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