JDT - AstParser - Get the list of methods which were called for a specific object

1.1k views Asked by At

For example, I have the code like

SomeObject1 obj1 = new SomeObject1();
SomeObject2 obj2 = new SomeObject2();
...
obj1.foo();
obj1.boo();
...
obj2.foo2();
obj2.boo2();

And I want to get the next output:

Type: SomeObject1

Name: obj1

Called methods: foo, boo

==========

Type: SomeObject2

Name: obj2

Called methods: foo2, boo2

thanks

UPD: I have made a code

public boolean visit(VariableDeclarationFragment v)
{
    System.out.println("Declaration of " + v.getName().resolveBinding().getKey());
    return true;
}

public boolean visit(MethodInvocation inv)
{               
    Expression e = inv.getExpression();

    if(e instanceof Name)
    {
        Name n = (Name) e;
        System.out.println("Calling the method \"" + inv.getName().getFullyQualifiedName() + "\" for " + n.resolveBinding().getKey());
    }
    return true;
}

Declaration of Ltest/C:\Test\src\Test~Test;.abc)I

Declaration of Ltest/C:\Test\src\Test~Test;.method()V#a

Declaration of Ltest/C:\Test\src\Test~Test;.method()V#url

Calling the method "replace" for Ltest/C:\Test\src\Test~Test;.method()V#url

For the test code:

package test;

public class Test
{
    private int abc;
    public void method()
    {
        int a;
        String url = "ftp://fdh/sdcard/dfsgh";
        url.replace("'", ".");
    }
}

The last two keys are equal, that means I have found the appropriate declaration. And it's easy to get types of variables, I won't post this

1

There are 1 answers

8
Sharon Ben Asher On BEST ANSWER

According to this example, you need, (besides an AstParser and the CompilationUnit it creates), a ASTVisitor. then you can have it visit a VariableDeclarationFragment for the declaration of the objects and a MethodInvocation for. well, method invocations.