找出JDT中调用方法的类型

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;

Unn*_*ris 6

您可能需要从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)

  • 方法调用包含两个节点:可选表达式和名称.表达式是表示调用该方法的类的表达式,而name表示方法名称.因此,为了获得正在使用的类的类型,我们需要检查表达式的类型绑定.希望这说清楚. (2认同)