JavaParser how to get classname in CompilationUnit

2.2k Views Asked by At

I have a path to a .java class like "./src/module/car.java" and i parse it like this:

File sourceFileCar = new File("./src/module/car.java");
CompilationUnit cuCar = StaticJavaParser.parse(sourceFileCar);

How can I get the class name in the car.java file without knowing it before (cant use cuCar.getClassByName)

1

There are 1 best solutions below

0
On BEST ANSWER

To access the parsed file, you have to create a visitor class which extends the VoidVisitorAdapter class.

public static class ClassNameCollector extends VoidVisitorAdapter<List<String>>{
    @Override
    public void visit(ClassOrInterfaceDeclaration n, List<String> collector) {
        super.visit(n, collector);
        collector.add(n.getNameAsString());
    }
}

After created a class, you have to override visit() method which job is to visit nodes in parsed file. In this case, we use ClassOrInterfaceDeclaration as a method parameter to get the class name and pass List for collecting the name.

In the main class, create a visitor object for using visit() which getting compilation object and list as parameters.

public static void main(String[] args) throws Exception {
    List<String> className = new ArrayList<>();
    // Create Compilation.
    CompilationUnit cu = StaticJavaParser.parse(new File(FILE_PATH));
    // Create Visitor.
    VoidVisitor<List<String>> classNameVisitor = new ClassNameCollector();
    // Visit.
    classNameVisitor.visit(cu,className);
    // Print Class's name
    className.forEach(n->System.out.println("Class name collected: "+n));
}

The result shows below.

Class name collected: InvisibleClass
Class name collected: VisibleClass
Class name collected: ReversePolishNotation

Hope this might solves you question :)