In this code, prosseek.B#bar() method invokes prosseek.SuperA#foo().
package prosseek;
public class SuperA {
int i = 0;
public void foo()
{
System.out.println(i);
}
}
public class B {
public void bar()
{
SuperA a = new SuperA();
a.foo();
}
}
I need to detect the type of foo() invoked in bar().
I use ASTVisitor to detect the MethodInvocation code (a.foo()), but I'm not sure what should I do in order to get the SuperA
type from it.
ICompilationUnit icu = type.getCompilationUnit();
final ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(icu);
parser.setResolveBindings(true); // we need bindings later on
CompilationUnit unit = (CompilationUnit) parser.createAST(null);
unit.accept(new ASTVisitor() {
public boolean visit(MethodInvocation methodInvocation)
{
// ???
return false;
}
}
I got the hint from JDT fundamentals tutorial.
I tried the following code:
IBinding binding = methodInvocation.resolveTypeBinding();
IType type = (IType)binding.getJavaElement();
if (type == null)
return false;
However, I got null for the return value of binding.getJavaElement();
Instead of taking the type of the MethodInvocation, may be you need to take the type from the Expression. I have not tested this, but this might help.
public boolean visit(MethodInvocation node) {
Expression exp = node.getExpression();
ITypeBinding typeBinding = node.getExpression().resolveTypeBinding();
System.out.println("Type: " + typeBinding.toString());
}