4

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?

2
  • Hi Pradeep, Did you got it. Can you please tell me how you got class name. Thanks! Sangeeta Commented Jul 28, 2014 at 7:11
  • @Sangeeta Yes I got, I asked this bit long time, I need to checkback my old code. Will let you know Commented Jul 28, 2014 at 8:13

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.