Search code examples
javaabstract-syntax-treejavaparser

How to parse java method body?


I want to parse java source files (.java) in order to identify methods, in a class, that contain calls to a specific method.

In the below example, I need to know which methods contain a call to xyz(). So, the parser should return method01 and method03

public class A{
    private void method01(){
        //some statements
        xyz();
        //more statements
    }

    private void method02(){
        //some statements
        xyz123();
        //more statements
    }

    private void method03(){
        //some statements
        xyz();
        //more statements
    }
}

I tried using javaparser (com.github.javaparser). I created a vistor and by overriding

public void visit(MethodDeclaration n, Void arg) 

I am able to “visit” all methods in the class.

But I don't know how to parse the body of the visted method. I’m reluctant to use n.getBody().toString().contains(“xyz()”)


Solution

  • By inspecting the Javadoc, it looks like you could do something like this:

    private MethodDeclaration currentMethod = null;
    
    @Override
    public void visit(MethodDeclaration n, Void arg) {
        currentMethod = n;
        super.visit(n, arg);
        currentMethod = null;
    }
    
    @Override
    public void visit(MethodCallExpr n, Void arg) {
        super.visit(n, arg);
        if (currentMethod != null && n.getName().asString().equals("xyz") {
            // Found an invocation of xyz in method this.currentMethod
        }
    }
    

    The code above keeps track of the current method and finds when a method call is visited that matches the name "xyz"