Search code examples
javaeclipseeclipse-jdt

Eclipse: SourceType to Class (or get current parameters of the Class)


I'm trying to search all the classes in a IJavaProject that extends a certain Interface. This interface is Generic, and I want to get the current type parameters of every implementation.

Now I have the SourceType that represents every implementation, but I can't get the current parameters of this class. Here is an example of my classes:

public class PersonDaoImpl extends AbstractDao<PersonPk, Person> {
    ...
}

My goal is to get the two parameters PersonPk and Person.

If it's possible to convert this SourceType as class, it would be better to manage it.

Thanks!


Solution

  • To get the type arguments of a type's superclass (IType sourceType) use

    String superSignature = sourceType.getSuperclassTypeSignature();
    for (String typeArgument : Signature.getTypeArguments(superSignature))
        System.out.println(Signature.getSignatureSimpleName(typeArgument));
    

    Utility Signature is org.eclipse.jdt.core.Signature.

    To get the next IType from its fully qualified name use:

    IJavaProject project = sourceType.getJavaProject();
    IType type = project.findType(qualifiedTypeName);
    

    If you have an unresolved type signature (starting with Q), then use this to get the qualified name in the first place:

    String[] qualifiedNames = sourceType.resolveType(typeSignature);
    

    See the javadoc for details.

    In the IDE, the classes in your workspace are not loaded as Class into the current JVM (which runs the IDE), because each change of a file in your workspace would require loading a new class into the JVM leading to huge memory problems, so even if this would be possible by some hack, it is strongly discouraged! The existing representations (Java model & AST) should suffice for all your processing needs.