-1

I want to parse the method check() using java parser. With getStatements() method in MethodDeclaration I can get the method. But I want to traverse the code inside the method. Is there any way to do this. I need to count the number of return statement inside this method.

final JavaParser javaParser = new JavaParser();
final CompilationUnit compilationUnit = pr.getResult().get();
final TypeDeclaration resourceClass = compilationUnit.getTypes().get(0);

MethodDeclaration md =  (MethodDeclaration) resourceClass.getMethodsByName("check");

md.getBody().get().getStatements();

private int check(){
    if(x=y)
        return 10;
    else
        return 5;
}
  • The code in your question does not compile, and is not formated well. You should fix this with other questions – Lindstorm Jul 30 '22 at 23:11

1 Answers1

0

You need to define a visitor that counts ReturnStmt instances. One way to do this is the following.

class ReturnStmtCounter extends GenericVisitorWithDefaults<Integer, Void> {
    public int countReturnStmts(Node n) {
        return n.accept(this, null);
    }

    public Integer defaultAction(NodeList<?> n, Void arg) {
        return sumReturnStmts(n, arg);
    }

    public Integer defaultAction(Node n, Void arg) {
        return sumReturnStmts(n.getChildNodes(), arg);
    }

    @Override
    public Integer visit(ReturnStmt returnStmt, Void arg) {
        return 1;
    }

    private int sumReturnStmts(Collection<? extends Node> nodes, Void arg) {
        return nodes.stream().mapToInt(n -> n.accept(this, null)).sum();
    }
}

Notes

  1. The countReturnStmts takes in any type of node that could be in a AST
  2. The algorithm is recursive; you first count the returns statements beneath each child using depth first search, then sum them
  3. If you visit a ReturnStmt instance, you stop and return 1.
Lindstorm
  • 890
  • 2
  • 7
  • 22