Search code examples
javajavaparser

How to parse inner class from java source code


I use the https://github.com/javaparser/javaparser to parse the java source code

I tried a lot of methods to parse inner class ; like this :

class A {
    int x;
    public void method2() {...}
        class B {
            int number;
            public void methods() {...}
        }
    }

I try to parse class B and it's variables and methods, but I failed.

Is there any example to show how to get the B class?

I can parse class A methods name and content or variables content, like this:

 CompilationUnit cu = JavaParser.parse(in);

 ClassVisitor classVisitor = new ClassVisitor();
 classVisitor.visit(cu, null);

 class ClassVisitor extends VoidVisitorAdapter<Void> {
    @Override
    public void visit(ClassOrInterfaceDeclaration n, Void arg) {
        System.out.println(n.getFields());

        // get class methods
        for(MethodDeclaration method : n.getMethods()) {
            System.out.println("Name :" + method.getName());
            System.out.println("Body :" + method.getBody().get());
           }
        }
    }
}

But I try to parse class B varible and method ,failed!

try the CompilationUnit.getTypes(), like this :

CompilationUnit cu = JavaParser.parse(in);

for(TypeDeclaration<?> type : cu.getTypes()) {
    log.info("Type Name :{}", type.getName());
}

result : n.s.dictionary.parse.JavaCodeParse : Type Name :A

Not resolved to B class


Solution

  • For somebody who need it :

    for(TypeDeclaration type : cu.getTypes()) {
            // first give all this java doc member
            List<BodyDeclaration> members = type.getMembers();
            // check all member content
            for(BodyDeclaration member : members) {
                // if member state equal ClassOrInterfaceDeclaration, and you can identify it which is inner class
                if(member.isClassOrInterfaceDeclaration()) {
                    log.info("class name :{}", member.asClassOrInterfaceDeclaration().getName());
                    // get inner class method
                    for(MethodDeclaration method : member.asClassOrInterfaceDeclaration().getMethods()) {
                        log.info("Method Name :{}", method.getName());
                    }
                    VerifyInnerClassAndParse(member.asClassOrInterfaceDeclaration());
                }
            }
        }
    

    if you hava many inner class, just write recursive method