Search code examples
javaeclipseeclipse-jdt

How to efficiently find all subtypes of an IType


I am currently working on custom refactoring tools based on JDT. At one point I would like to find all subtypes of a type, much like the "Type Hierarchy" view in eclipse does. I wrote a recursiv function going through th hierarchie using a SearchEngine. This works, but is realy slow for deep hierarchies. Is there a more efficient API I could use?

private Set<IType> searchForSubTypesOf(IType type, IProgressMonitor monitor) throws CoreException {
    final Set<IType> result = new HashSet<IType>();

    SearchPattern pattern = SearchPattern.createPattern(type, IJavaSearchConstants.REFERENCES, SearchPattern.R_EXACT_MATCH);
    SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() };
    IJavaSearchScope scope = SearchEngine.createHierarchyScope(inputType);
    SearchRequestor requestor = new SearchRequestor() {
        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            if (match.getAccuracy() == SearchMatch.A_ACCURATE && match.getElement() instanceof IType) {
                IType subType = (IType)match.getElement();
                result.add(subType);
                // Recursive search for the type found
                Set<IType> subTypes = searchForSubTypesOf(subType, new NullProgressMonitor());
                result.addAll(subTypes);
            }
        }
    };

    new SearchEngine().search(pattern, participants, scope, requestor, monitor);
    return result;
}

Solution

  • After lots of code reading I had one of these great moments where I finally found the API I was looking for!

    My function above boilds down to this:

    public static IType[] getAllSubtypesOf(IType type, IProgressMonitor monitor) throws CoreException {
        return type.newTypeHierarchy(monitor).getAllSubtypes(type);
    }