1

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()”)

Tony P
  • 211
  • 5
  • 12

1 Answers1

2

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"

Samuel
  • 16,923
  • 6
  • 62
  • 75
  • There are many ways to solve this problem but that should work. Of course we do not know which method named xyz we are calling, just that we are calland a method named xyz – Federico Tomassetti Oct 20 '17 at 20:39