[英]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;
}
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()); }
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.