1

I'm currently trying to implement a Eclipse plugin to calculate some OO metrics for Java application, as DIT (Depth of Inheritance Tree). However, i'm not being able to retrieve informations about a Class inheritance tree (distance between the class until Object). Assuming that a class is a CompilationUnit, I'm trying to getting into the class through the TypeDeclaration to compare if the class, for example, Dog (extends Animal) is a instance of Object. If not, it is done a recursive call to the visit method passing the Animal class as parameter, until the class is Object.

EDIT I managed to recover the superclass using typeDec.getSuperClassType(), however I need to get the TypeDeclaration of this superclass to call the visit method recursively, passing this TypeDeclaration as parameter.

This is the idea of my code:

public class ClassVisitor extends ASTVisitor { 

 depthOfInheritanceTreeIndex = 1;

 public boolean visit(CompilationUnit unit) {
    for (Object type :unit.types()){

        TypeDeclaration typeDec = (TypeDeclaration) type;

        Type superClassType = typeDec.getSuperClassType();

        TypeDeclaration superClazz;
        if (superClassType.equals(Object.class.getSimpleName())){
            return continue;
        }else{
            depthOfInheritanceTreeIndex++;
            superClazz = (TypeDeclaration) superClassType.getParent();
            return super.visit(superClazz);
        }
    }
    return false;
 }
}

Do you guys has any ideas in what i'm doing wrong or how to do that? Any help will be apprecieated!

4

2 回答 2

3

您最好的选择是避免使用 AST API 并改用 Java 模型 API。AST 旨在操作和分析 Java 源代码,而模型 API 旨在分析和操作 Java 程序的结构。

API 植根于IJavaElement接口。您将需要执行以下操作:

IFile myJavaFile = <get the file>
ICompilationUnit unit = JavaCore.createFromFile(myJavaFile);
IType[] types = unit.getAllTypes();
for (IType type : types) {
  ITypeHierarchy th= type.newTypeHierarchy(null);
  // do something with the hierarchy
}

与基于 AST 生成层次结构相比,这将为您提供更大的灵活性。但是有一些警告:

  1. 这可能需要很长时间来计算(尤其是对于大型层次结构)
  2. 出于这个原因,如果可能,您可能只想使用超类型层次结构,这样计算起来要快得多。
于 2013-07-01T22:10:34.647 回答
2

您可以使用typeDec.resolveBinding().getSuperclass()将超类作为ITypeBinding. 从那里您可以通过递归调用向上移动继承树,getSuperClass()直到它返回nullor unit.getAST().resolveWellKnownType("java.lang.Object")

于 2014-01-03T11:42:11.650 回答