How to get node superclasses in Eclipse jdt ui?

I have the code here:

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

As you can see, I mentioned the error. I am trying to create quickfix for this in eclipse jdt ui. But I cannot get the superclass of node class B, which is Class TestOverride.

I tried the following code

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

Here I got parentClass only as TestOverride. But when I checked, it is not a TypeDeclaration type, it is not a SimpleName type.

My request is how do I get the TestOverride node class?

EDIT

  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); } 
+6
source share
1 answer

You will need to work with bindings . To have bindings, this means that resolveBinding() not returning null , maybe the extra steps that I posted are necessary.

To work with bindings, this visitor should help in the right direction:

 class TypeHierarchyVisitor extends ASTVisitor { public boolean visit(MethodDeclaration node) { // eg foo() IMethodBinding methodBinding = node.resolveBinding(); // eg class B ITypeBinding classBinding = methodBinding.getDeclaringClass(); // eg 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); } } 
+3
source

All Articles