prosseek
prosseek

Reputation: 190799

How to get the enclosing method node with JDT?

When I have a method foo() that calls bar(), how can I get the foo() AST node from MethodInvocation node (or whatever statements/expressions in the method)? For example, I need to know the IMethod foo from b.bar().

public void foo()
{
    b.bar();
}

Upvotes: 4

Views: 1066

Answers (3)

prosseek
prosseek

Reputation: 190799

The other trick might be letting the visitor store the caller information before visiting the MethodInvocation node:

ASTVisitor visitor = new ASTVisitor() {
    public boolean visit(MethodDeclaration node) {
        String caller = node.getName().toString();
        System.out.println("CALLER: " + caller);

        return true;
    }
    public boolean visit(MethodInvocation node) {
        String methodName = node.getName().toString();
        System.out.println("INVOKE: " + methodName);

With AnotherClass Type:

public class AnotherClass {

    public int getValue()
    {
        return 10;
    }

    public int moved(int x, int y)
    {
        if (x > 30)
            return getValue();
        else
            return getValue();
    }
}

I could get the information:

TYPE(CLASS): AnotherClass
CALLER: getValue
CALLER: moved
INVOKE: getValue
INVOKE: getValue

Upvotes: 0

Deepak Azad
Deepak Azad

Reputation: 7923

In JDT/UI we have a helper method to do this. Take a look at org.eclipse.jdt.internal.corext.dom.ASTNodes.getParent(ASTNode, int)

Upvotes: 3

prosseek
prosseek

Reputation: 190799

I came up with this code, but I expect there are better ways to get the result.

public static IMethod getMethodThatInvokesThisMethod(MethodInvocation node) {
    ASTNode parentNode = node.getParent();
    while (parentNode.getNodeType() != ASTNode.METHOD_DECLARATION) {
        parentNode = parentNode.getParent();
    }

    MethodDeclaration md = (MethodDeclaration) parentNode;
    IBinding binding = md.resolveBinding();
    return (IMethod)binding.getJavaElement();
}

Upvotes: 3

Related Questions