我的代码在这里:
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。但我无法获得类B的超类节点,即Class TestOverride。
我尝试了以下代码
if(selectedNode instanceof MethodDeclaration) {
ASTNode type = selectedNode.getParent();
if(type instanceof TypeDeclaration) {
ASTNode parentClass = ((TypeDeclaration) type).getSuperclassType();
}
}
在这里我只将parentClass作为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 :(得分:4)
您必须使用bindings
。要使绑定可用,这意味着resolveBinding()
不返回null
,我发布的possibly 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);
}
}