pro*_*eek 2 java eclipse eclipse-plugin eclipse-jdt
在此代码中,prosseek.B #bar()方法调用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();
}
}
Run Code Online (Sandbox Code Playgroud)
我需要检测bar()中调用的foo()的类型.我使用ASTVisitor来检测MethodInvocation代码(a.foo()),但我不知道我该怎么办才能从中获取SuperA类型.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我从JDT基础知识教程中得到了提示.

我尝试了以下代码:
IBinding binding = methodInvocation.resolveTypeBinding();
IType type = (IType)binding.getJavaElement();
if (type == null)
return false;
Run Code Online (Sandbox Code Playgroud)
但是,对于binding.getJavaElement()的返回值,我得到null;
您可能需要从Expression中获取类型,而不是采用MethodInvocation的类型.我没有测试过这个,但这可能会有所帮助.
public boolean visit(MethodInvocation node) {
Expression exp = node.getExpression();
ITypeBinding typeBinding = node.getExpression().resolveTypeBinding();
System.out.println("Type: " + typeBinding.toString());
}
Run Code Online (Sandbox Code Playgroud)