我如何在 Eclipse jdt ui 中获取超类节点?

How do i get the Superclasses node in Eclipse jdt ui?

我这里有一个代码:

public class TestOverride {
    int foo() {
        return -1;
    }
}

class B extends TestOverride {
    @Override
    int foo() {
        // error - quick fix to add "return super.foo();"   
    }
}

如您所见,我已经提到了错误。我试图在 eclipse jdt ui 中为此创建一个 quickfix。但是我无法获得 class B 的超级 class 节点,即 Class TestOverride.

我尝试了以下代码

if(selectedNode instanceof MethodDeclaration) {
    ASTNode type = selectedNode.getParent();
    if(type instanceof TypeDeclaration) {
        ASTNode parentClass = ((TypeDeclaration) type).getSuperclassType();
    }
}

在这里我得到了 parentClass 作为 TestOverride 而已。但是当我检查这不是 TypeDeclaration 类型时,它也不是 SimpleName 类型。

我的问题是如何获得 class TestOverride 节点?

编辑

  for (IMethodBinding parentMethodBinding :superClassBinding.getDeclaredMethods()){
     if (methodBinding.overrides(parentMethodBinding)){
        ReturnStatement rs = ast.newReturnStatement();
        SuperMethodInvocation smi = ast.newSuperMethodInvocation();
        rs.setExpression(smi);
        Block oldBody = methodDecl.getBody();
        ListRewrite listRewrite = rewriter.getListRewrite(oldBody, Block.STATEMENTS_PROPERTY);
        listRewrite.insertFirst(rs, null);
}

你必须使用 bindings. To have bindings available, that means resolveBinding() not returning null, possibly additional steps 我已经发布的是必要的。

要使用绑定,这位访问者应该有助于找到正确的方向:

class TypeHierarchyVisitor extends ASTVisitor {
    public boolean visit(MethodDeclaration node) {
        // e.g. foo()
        IMethodBinding methodBinding = node.resolveBinding();

        // e.g. class B
        ITypeBinding classBinding = methodBinding.getDeclaringClass();

        // e.g. class TestOverride
        ITypeBinding superclassBinding = classBinding.getSuperclass();
        if (superclassBinding != null) {
            for (IMethodBinding parentBinding: superclassBinding.getDeclaredMethods()) {
                if (methodBinding.overrides(parentBinding)) {
                    // now you know `node` overrides a method and
                    // you can add the `super` statement
                }
            }
        }
        return super.visit(node);
    }
}