How do you find all subclasses of a given class in Java? How do you find all subclasses of a given class in Java? java java

How do you find all subclasses of a given class in Java?


Scanning for classes is not easy with pure Java.

The spring framework offers a class called ClassPathScanningCandidateComponentProvider that can do what you need. The following example would find all subclasses of MyClass in the package org.example.package

ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);provider.addIncludeFilter(new AssignableTypeFilter(MyClass.class));// scan in org.example.packageSet<BeanDefinition> components = provider.findCandidateComponents("org/example/package");for (BeanDefinition component : components){    Class cls = Class.forName(component.getBeanClassName());    // use class cls found}

This method has the additional benefit of using a bytecode analyzer to find the candidates which means it will not load all classes it scans.


There is no other way to do it other than what you described. Think about it - how can anyone know what classes extend ClassX without scanning each class on the classpath?

Eclipse can only tell you about the super and subclasses in what seems to be an "efficient" amount of time because it already has all of the type data loaded at the point where you press the "Display in Type Hierarchy" button (since it is constantly compiling your classes, knows about everything on the classpath, etc).


This is not possible to do using only the built-in Java Reflections API.

A project exists that does the necessary scanning and indexing of your classpath so you can get access this information...

Reflections

A Java runtime metadata analysis, in the spirit of Scannotations

Reflections scans your classpath, indexes the metadata, allows you to query it on runtime and may save and collect that information for many modules within your project.

Using Reflections you can query your metadata for:

  • get all subtypes of some type
  • get all types annotated with some annotation
  • get all types annotated with some annotation, including annotation parameters matching
  • get all methods annotated with some

(disclaimer: I have not used it, but the project's description seems to be an exact fit for your needs.)