2016-04-24 44 views
6

我这里有一个代码:如何获取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 TestOverride的类B的超类节点。

我尝试下面的代码

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

在这里我得到了父类,因为只有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); 
} 
+0

你真正需要的'TestOverride'节点,如果你只需要插入'返回super.foo();'打电话? – sevenforce

回答

3

您将有bindings工作。要有绑定可用,这意味着resolveBinding()不返回nullpossibly 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); 
    } 
} 
+0

感谢您的回答。但是,我应该如何从中获得节点。 – Midhun

+0

@Midhun如果你的意思是超类节点'TestOverride',我不确定你需要那个节点。 – sevenforce

+0

我需要它来获得它的声明方法,因为我是一个初学者,我不知道是否有任何其他方式获得它。 – Midhun