0

So I have a class A and there are multiple classes that extend from class A. I create an instance of this class, is there a way to get all the other classes that extend A?

Something like:

A a = new A();
a.getAllSubclasses();

Only way I tought of doing this is scanning the entire project for all the classes and storing them in a list and then checking manuall if each class extends from A with instanceOf.

List<Class> classList;
classList.each{
    if(it instanceOf a)
        //do stuff
}

This seems bad especially for a huge project with hundred of classes.

Isvoran Andrei
  • 409
  • 7
  • 16

2 Answers2

1

The simple answer is: yes, the only way to know about "accessible" subclasses of class X ... is to scan the complete class path for all classes, and for each one check whether it is a subclass of X.

And note: of course that only tells you about subclasses in that class path.

In other words: there is always a restriction of scope. If you have two different projects, you can as well have some subclasses of X in both projects, so you would have to scan both these "contexts" to know about them.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

There's a simple library called org.reflections give information about subclasses. Using this library, you need to call reflections.getSubTypesOf(ClassName)). Check Respective code here GitHub Code

Dhanraj
  • 1,162
  • 4
  • 18
  • 45