Pradeep Simha
Pradeep Simha

Reputation: 18133

AST Parser get the name of Java class

I am using Eclipse's AST Parser to parse a standalone Java files. This is my below overridden code to get the CompilationUnit (ie Java file) details:

@Override
public boolean visit(CompilationUnit node) {
    System.out.println("Compilation unit: " + node.getPackage().getName());
    System.out.println("Imports: " + node.imports());
    System.out.println("Class Name: " + ??); //How to get this?
    return super.visit(node);
}

As you can see from above code, I am able to get package name, imports etc from CompilationUnit. But the main problem I am facing is, I am not able to get name of the class. I tried printing node.toString() it prints entire source code, I tried with node.getClass(); but it returns me name as CompilationUnit. What I want is name of the class of the file which I am parsing. Is there any in-build methods using I can get this info?

Upvotes: 4

Views: 2033

Answers (1)

rlegendi
rlegendi

Reputation: 10606

In Java, a compilation unit is not equal to a single class.

You can define multiple classes (with package-private access) for example. On the other hand you do not always have a public class within a compilation unit (the restriction is that you may have only one public class, and if you have, its name must be identical to the name of the compilation unit).

I believe you should process with the accept process on your CompilationUnit and write the visit() methods for classes too.

Upvotes: 3

Related Questions