我正在开发一个Eclipse插件。如果类扩展了第三个类,我将使用下面的ASTVisitor实现来替换该类的超类。
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()
只返回类的名称。
有可能找出超类的全名吗?
作为参考,这个答案帮助我创建了这个访问者:How Can a SuperClass name be retrieved from a java file using ASTParser?
发布于 2014-05-20 18:07:40
我可能误解了这个问题但是..。
我的oldType字符串是一个点分隔的完全限定名,而node.getSuperclassType()只返回类的名称。
这是错误的。您的代码如下:
public Type superClass;
<...>
SimpleType oldType = <...>
或Type
,或SimpleType
子类String
。他们不是名字。它们是具有类型信息的完全限定类。他们不测试等于的原因是写在Type.equals
上的Javadoc上:
公共最终布尔值等于(对象obj) 此对象方法的ASTNode实现使用对象标识(==)。使用subtreeMatch比较两个子树是否相等。
后者还指明了在哪里寻找合适的等式测试器。关于节点为什么给出不同的名称-- toString
on Type
说得很清楚
返回仅适用于调试目的的此节点的字符串表示形式。
所以你不能用它来做任何决策。
我想您混合了getName
和toString
来获得这个结果,因为getName
不是为Type
定义的,而是为SimpleType
定义的,尽管这部分代码缺失了,所以我只是在推测。
发布于 2017-03-16 06:07:39
我也面临着同样的问题。
SimpleType
似乎不能通过JDT自动解析为QulifiedType
。因此,我想首先解析导入语句以获得导入的类型。我也在寻找一个更简单的解决方案。
https://stackoverflow.com/questions/23766576
复制相似问题