如何在Eclipse jdt ui中获取Superclasses节点?

Mid*_*hun 6 java eclipse eclipse-jdt

我这里有一个代码:

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

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

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

我尝试了以下代码

if(selectedNode instanceof MethodDeclaration) {
    ASTNode type = selectedNode.getParent();
    if(type instanceof TypeDeclaration) {
        ASTNode parentClass = ((TypeDeclaration) type).getSuperclassType();
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,我只将parentClass作为TestOverride.但是当我检查时,这不是TypeDeclaration类型,它也不是SimpleName类型.

我的查询是如何获得类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);
}
Run Code Online (Sandbox Code Playgroud)

sev*_*rce 5

您将不得不与bindings. 要绑定可用,这意味着resolveBinding()不返回 null可能需要我发布的其他步骤

要使用绑定,此访问者应该有助于朝着正确的方向前进:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)