How can I fetch the caller/parent method in which the methods are called?
For eg:
void parentMethod(){
a();
b();
}
I'm able to fetch the details of methods a & b. However, I'm not able to get any details about the caller/parent method i.e. parentMethod().
Is there a way I can get information about the caller method in the ResolvedMethodDeclarations?
Below is my code:
public void visit(MethodCallExpr aMethod, Void arg) {
CombinedTypeSolver solver = typeSolver(srcFolders);
JavaParserFacade j = JavaParserFacade.get(solver);
SymbolReference<ResolvedMethodDeclaration> methodRef = j.solve(aMethod);
super.visit(aMethod, arg);
}
In your visitor method for MethodCallExpr, you don't need to solve the method call expression for a() (or b()) when all you want to know is the context that you are already in (i.e., when you want to know the method that contains the given call expression, which is parentMethod() in your example). In other words, the information you are trying to find doesn't necessitate a symbol solver - you can do it with the JavaParser core API.
All you need to do in your visitor method for MethodCallExpr is to find the closest parent node that is a MethodDeclaration, and that's the method which contains this call. :-)
An easy way to do so would be to use Node#findParent(Class<?>), i.e., you could write something like:
Optional<MethodDeclaration> caller = aMethod.findParent(MethodDeclaration.class)
where aMethod is the method call expression, as you named it in your example code (note that in my opinion, the parameter name aMethod is not well-chosen, because what you're visiting is not "a method", but "a method _call_"). By the way, you could do this to find the containing method of any node (that is indeed contained in a method), not only method call expression nodes. :-)
Thanks. That worked!
@ronak111091 Cool!
One more thing, mind this: not every method call expression is contained in a method. Consider for instance:
class A {
int i = foo();
// ... more code ...
}
Here, the method call foo() is not contained in a method, and, if you do something like
Optional<MethodDeclaration> caller = methodCallExpr.findParent(MethodDeclaration.class)
...where methodCallExpr is the method call expression foo(), you get an empty Optional.