[英]How do i get the Superclasses node in Eclipse jdt ui?
我在这里有一个代码:
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中为此创建一个快速修复程序。 但我无法获得Class TestOverride的B类的超类节点。
我尝试了以下代码
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);
}
您将不得不使用bindings
。 为了使绑定可用,这意味着resolveBinding()
不返回null
, 可能我已发布了其他步骤 。
要使用绑定,此访问者应有助于朝正确的方向发展:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.