Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i get the Superclasses node in Eclipse jdt ui?

I have a 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 have mentioned the error. I'm trying to create a quickfix for this in eclipse jdt ui. But i'm unable to get the superclass node of the class B that 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();
    }
}

In here I got parentClass as TestOverride only. But when I checked this is not of the type TypeDeclaration it's not of type SimpleName either.

My query is how I get the class TestOverride node?

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);
}
like image 874
Midhun Avatar asked Apr 24 '16 04:04

Midhun


1 Answers

You will have to work with bindings. To have bindings available, that means resolveBinding() not returning null, possibly additional steps I have posted are necessary.

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

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);
    }
}
like image 91
sevenforce Avatar answered Nov 03 '22 10:11

sevenforce