首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Eclipse中获得超类节点?

如何在Eclipse中获得超类节点?
EN

Stack Overflow用户
提问于 2016-04-24 04:18:15
回答 1查看 466关注 0票数 6

我这里有个密码:

代码语言:javascript
复制
public class TestOverride {
    int foo() {
        return -1;
    }
}

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

如你所见,我已经提到了这个错误。我正试图在eclipse中为此创建一个快速修复程序。但是我无法得到B类的超类节点,即类TestOverride。

我尝试了以下代码

代码语言:javascript
复制
if(selectedNode instanceof MethodDeclaration) {
    ASTNode type = selectedNode.getParent();
    if(type instanceof TypeDeclaration) {
        ASTNode parentClass = ((TypeDeclaration) type).getSuperclassType();
    }
}

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

我的查询是如何得到类TestOverride节点的?

编辑

代码语言:javascript
复制
  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);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-01 08:20:57

您必须使用bindings。要使绑定可用,这意味着resolveBinding()不返回null,我发布的possibly additional steps是必要的。

要处理绑定,这个访问者应该有助于正确的方向:

代码语言:javascript
复制
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);
    }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36819240

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档