nixfuerdiecharts
nixfuerdiecharts

Reputation: 383

JavaParser how to get classname in CompilationUnit

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)

Upvotes: 4

Views: 2696

Answers (2)

Allohvk
Allohvk

Reputation: 1374

Expanding on Slaw and Sauer comments:

//Primary Name
if (cuCar.getPrimaryTypeName().isPresent()) {
    System.out.println("\nClass Name: " + cuCar.getPrimaryTypeName().get());
}

//All class names (since a Java file can have multiple classes)
System.out.println(cuCar.getTypes().size());
for (TypeDeclaration<?>  name_class : cuCar.getTypes()) {
    System.out.println(name_class.getName());
}

Upvotes: 1

Peeradon
Peeradon

Reputation: 44

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 :)

Upvotes: 2

Related Questions