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);
}
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With