user12705369
user12705369

Reputation:

Listing all the subclasses of a specific class in Java

How do I list down all the subclasses of a specific class or all the implementers of a specific interface in Java? Using Eclipse, I am able to do so but I want to know how to perform this programmatically? If you have any suggestions, please do put them.

Upvotes: 3

Views: 826

Answers (2)

Sree Kumar
Sree Kumar

Reputation: 2245

As per me, this requires the following steps in the least:

  1. For the current classloader, iterate over the classpath to get the list of folders and JARs (This, I know how to only for URLClassLoader and its subtypes, which is URLClassLoader.getURLs())
  2. Visit/read each folder or JAR in the list from (1) to know the classes in it and load each class (there could be an issue here with the classloader, but you may get it through for most cases)
  3. Reflect and find out the implemented interfaces (if you are looking for children of interfaces) or superclass (if a class). This has to be done iteratively till you reach java.lang.Object or the target interface or class.

Repeat the above steps for the parent classloader if the parent interface or class was loaded by them (say, java.util.List).

All said and done, please be ready for a memory and CPU heavy processing. :)

Eclipse, I think indexes the hierarchy progressively. That is why, most of the times it shows the results fast. I am not sure of it, but it may be worth exploring Eclipse if it provides a way to access its type hierarchy list at runtime (through plugin implementations).

Upvotes: 0

N. berouain
N. berouain

Reputation: 1311

take a look at reflection, Basic usage of this:

Reflections reflections = new Reflections("com.package");    
Set<Class<? extends InterfaceExample>> classes = reflections.getSubTypesOf(InterfaceExample.class);

Upvotes: 4

Related Questions