2016-04-24 45 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