Apache NetBeans
Apache NetBeans
Latest release

Apache NetBeans 23

Download

How can I scan a classpath to find all classes of a particular type?

Prerequisites

  • find the ClassPath on which the subtypes should be found. Use e.g. ClassPath.getClassPath(<file>, ClassPath.SOURCE)

  • if the supertype is given as a FQN, convert to ElementHandle<TypeElement> via ElementHandle.create inside a Task or CancellableTask.

Finding all subtypes of given type

All subtypes of a given type on a given ClassPath can be found using ClassIndex. As ClassIndex contains only direct subtypes, the indirect subtypes need to be found on the client side:

private Set<ElementHandle<TypeElement>> findAllSubTypes(ClassPath on, ElementHandle<TypeElement> of) {
    ClasspathInfo cpInfo = ClasspathInfo.create(ClassPath.EMPTY, ClassPath.EMPTY, on);

    List<ElementHandle<TypeElement>> todo = new LinkedList<ElementHandle<TypeElement>>(of);
    Set<ElementHandle<TypeElement>> result = new HashSet<ElementHandle<TypeElement>>();

    while (!todo.isEmpty()) {
        //TODO: if cancellable, check for cancel here

        ElementHandle<TypeElement> curr = todo.remove(0);

        result.add(curr);

        Set<ElementHandle<TypeElement>> typeElements = cpInfo.getClassIndex().getElements(eh, EnumSet.of(ClassIndex.SearchKind.IMPLEMENTORS), EnumSet.of(ClassIndex.SearchScope.SOURCE));

        if (typeElements != null) { //can be null for cancellable tasks
            todo.addAll(typeElements);
        }
    }

    return result;
}

Getting FileObjects corresponding to ElementHandles

The FileObject corresponding to a given ElementHandle<TypeElement> can be found using SourceUtils.getFile.