我正在开发 Eclipse 插件。我正在使用 ASTVisitor 的以下实现,以便在该类扩展第三个类时替换该类的父类(super class)。
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
public class SuperClassVisitor extends ASTVisitor{
public Type superClass;
public String newSuperClass;
private String oldSuperClass;
public SuperClassVisitor(String newType, String oldType) {
this.newSuperClass = newType;
this.oldSuperClass = oldType;
}
public boolean visit(TypeDeclaration node) {
superClass = node.getSuperclassType();
if (newSuperClass != null) {
Name oldName = node.getAST().newName(oldSuperClass);
SimpleType oldType = node.getAST().newSimpleType(oldName);
Name newName = node.getAST().newName(newSuperClass);
SimpleType newType = node.getAST().newSimpleType(newName);
if (superClass != null && superClass.equals(oldType)) {
node.setSuperclassType(newType);
}
}
return true;
}
}
我正在访问我项目中的每个类。基本上,在扩展 oldType
的类中,我想将其更改为 newType
。但是,条件 superClass.equals(oldType)
永远不会为真,因为我的 oldType
字符串是点分隔的完全限定名称,而 node.getSuperclassType()
只返回类的名称。
是否可以找出父类(super class)的全名?
作为引用,这个回答帮助我创建了这个访问者: How Can a SuperClass name be retrieved from a java file using ASTParser?
最佳答案
我可能误解了这个问题,但是......
my oldType string is a dot-separated fully qualified name, while node.getSuperclassType() returns just the name of the class.
这是错误的。您的代码如下:
public Type superClass;
<...>
SimpleType oldType = <...>
也不是 Type
,也不是 SimpleType
子类 String
。他们不是名字。它们是具有类型信息的完全限定类。他们不测试 equals 的原因写在 Type.equals
的 Javadoc 上:
public final boolean equals(Object obj)
The ASTNode implementation of this Object method uses object identity (==). Use subtreeMatch to compare two subtrees for equality.
后者还给出了在哪里寻找合适的相等性测试器的指示。至于为什么节点给出不同的名称 - type
上的 toString
说得很清楚
Returns a string representation of this node suitable for debugging purposes only.
因此您不能将其用于任何决策。
我想你混合了 getName
和 toString
来得到那个结果,因为 getName
没有为 Type
定义并且被定义对于 SimpleType
,虽然缺少那部分代码,所以我只是推测。
关于java - JDT如何知道父类(super class)的全名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23766576/