从 IBinding 获取一个 CompilationUnit

Get a CompilationUnit from IBinding

我想为 MethodInvocation:

找到一个声明节点
MethodInvocation methodNode = ...;
IMethodBinding b = methodNode.resolveMethodBinding();
IMethodBinding[] declaredMethods = b.getDeclaringClass().getDeclaredMethods();
for (IMethodBinding method : declaredMethods) {
    if (astRoot.findDeclaringNode(method).getStructuralProperty(MethodDeclaration.NAME_PROPERTY).equals(name))
        //...
}

这对我来说不起作用,因为该方法是在另一个编译单元中声明的,并且 astRoot.findDeclaringNode(...) returns null。 如何从IBinding得到正确的CompilationUnit?

如果您要声明 class,则 IMethodBinding 中的 getDeclaringClass() 方法将 return 对应于 class 的类型绑定。从类型绑定,如果您想要的话,您应该能够通过包片段到达 CU。

我发现 SharedASTProvider#getASTASTParser#setSource 可以与 ITypeRoot 一起工作,后者由 IClassFileICompilationUnit 实现。要从绑定中获取 CompilationUnit,可以使用以下代码段:

IJavaElement je = b.getJavaElement();
while (je != null && !(je instanceof ITypeRoot)) {
    je = je.getParent();
}
if (je != null) {
    ITypeRoot = (ITypeRoot)je;
    //...
}

了解 ITypeRoot 帮助我找到了更好的解决方案,它不涉及 AST,并且在某个 class 文件的源不可用时似乎可以工作。

for (IMethod method : type.findPrimaryType().getMethods()) {
    if (method.getElementName().equals(name)) {
        //....
    }
}