i want to parse a project in which some classes have inner classes.how can i extract inner classes name other information using eclips JDT?
2 Answers
You can traverse through the Compilation unit of the Java class and visit the TypeDeclaration AST node. The below code can then be used to check if it is not a top-level class, i.e an inner class.
public boolean visit(TypeDeclaration typeDeclarationStatement) { if (!typeDeclarationStatement.isPackageMemberTypeDeclaration()) { System.out.println(typeDeclarationStatement.getName()); // Get more details from the type declaration. } return true; } For getting anonymous inner classes use the below code too:
public boolean visit(AnonymousClassDeclaration anonyomousClassDeclaration) { System.out.println(anonyomousClassDeclaration.toString()); return true; } Details on Class traversal using JDT can be found from below link:
3 Comments
rosedoli
i used the code below but it does not display all inner classes
Unni Kris
Does the code doesn't display any inner classes, or is it problem with some specific inner class (anonymous/method inner class)?
rosedoli
ASTParser parser = ASTParser.newParser(AST.JLS3); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setSource(fileName.toString().toCharArray()); parser.setResolveBindings(true); parser.setCompilerOptions(options); final CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.accept(new ASTVisitor() { public boolean visit(TypeDeclaration typeDeclarationStatement) { if (!typeDeclarationStatement.isPackageMemberTypeDeclaration()) { System.out.println(typeDeclarationStatement.getName()); } return true; }
If you have an IType instance (type) then you can query the inner classes by
type.getTypes(); which will give you an array of the immediate member types declared by this type.
1 Comment
christoph.keimel
But you have a ICompilationUnit instance? If so, you can get all top-level type declarations of this compilation unit with ICompilationUnit.getTypes()