ivan
ivan

Reputation: 297

ASTParser - MethodInvocation - How to detect a static method call

Example code:

String.valueOf("test");

And visitor for this code:

cu.accept(new ASTVisitor()
{
    public boolean visit(MethodInvocation inv)
    {               
        System.out.println(inv);
        System.out.println(inv.getExpression().getClass());
        return true;
    }
});

Output:

String.valueOf("test")
class org.eclipse.jdt.core.dom.SimpleName

But non-static call will return SimpleName too.

Secondly I tried to get resolveMethodBinding(), but here is no methods which can help me to detect is that a static method or no.

Does someone know to do that? Thanks

Upvotes: 1

Views: 892

Answers (2)

Fabrice TIERCELIN
Fabrice TIERCELIN

Reputation: 983

To distinguish static call (and not static method) like this:

myInteger.toString(); // Non-static call
Integer.toString(myInteger); // Static call
myInteger.toString(myInteger); // Non-static call (called from an object)

You need to build the AST with bindings available and write this:

cu.accept(new ASTVisitor()
{
    public boolean visit(MethodInvocation inv)
    {               
        if (inv.getExpression() instanceof Name
                        && ((Name) inv.getExpression()).resolveBinding().getKind() == IBinding.TYPE)
        {
            // Static call
        }
        else
        {
            // Non-static call
        }
        return true;
    }
});

Upvotes: 0

Daniel Martin
Daniel Martin

Reputation: 23548

You need to build the AST with bindings available, then call:

IMethodBinding binding = inv.resolveMethodBinding();
if (binding.getModifiers() & Modifier.STATIC > 0) {
  // method is static method
} else {
  // method is not static
}

Upvotes: 2

Related Questions