我这里有个密码:
public class TestOverride {
int foo() {
return -1;
}
}
class B extends TestOverride {
@Override
int foo() {
// error - quick fix to add "return super.foo();"
}
}如你所见,我已经提到了这个错误。我正试图在eclipse中为此创建一个快速修复程序。但是我无法得到B类的超类节点,即类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);
}发布于 2016-05-01 08:20:57
您必须使用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);
}
}https://stackoverflow.com/questions/36819240
复制相似问题