2

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)

nixfuerdiecharts
  • 313
  • 2
  • 14
  • 1
    Haven't used JavaParser, but [looking at the API](https://www.javadoc.io/static/com.github.javaparser/javaparser-core/3.18.0/com/github/javaparser/ast/CompilationUnit.html) it would seem you want to use `#getType(int)` or `#getTypes()` to get the `TypeDeclaration` which you can then call `#getFullyQualifiedName()` or `#getName()` on, depending on if you want the fully qualified name or simple name, respectively. – Slaw Dec 20 '20 at 06:19
  • You have to use `getTypes()` and iterate over it, because a compilation unit (i.e. source file) can contain multiple top-level types/classes. You probably assume it's only one because the `javac` compiler will only accept one `public` top-level class per compilation unit, but one can have any number of non-public ones. – Joachim Sauer Jan 15 '21 at 09:16

1 Answers1

2

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

Peeradon
  • 44
  • 2