1

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?

rosedoli
  • 39
  • 6

2 Answers2

4

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:

Community
  • 1
  • 1
Unni Kris
  • 3,081
  • 4
  • 35
  • 57
  • i used the code below but it does not display all inner classes – rosedoli Apr 04 '13 at 05:38
  • Does the code doesn't display any inner classes, or is it problem with some specific inner class (anonymous/method inner class)? – Unni Kris Apr 04 '13 at 05:40
  • 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; } – rosedoli Apr 04 '13 at 05:42
1

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.

christoph.keimel
  • 1,240
  • 10
  • 24
  • But you have a ICompilationUnit instance? If so, you can get all top-level type declarations of this compilation unit with ICompilationUnit.getTypes() – christoph.keimel Apr 04 '13 at 13:10