I have to implement a logic whereby given a child class, I need to access its parent class and all other child class of that parent class, if any. I did not find any API in Java Reflection which allows us to access all child classes of a parent class. Is there any way to do it?
For example:
class B extends class A
class C extends class A
Now using class B, I can find the superclass by calling getSuperClass()
. But is there any way to find all the child classes once I have the parent class i.e. class B and class C??
If this wasn't homework (where 3rd party librares are probably not allowed), I would have suggested Google Reflections' Reflections#getSubTypesOf()
.
Set<Class<? extends A>> subTypes = reflections.getSubTypesOf(A.class);
You can do this less or more yourself by scanning the classpath yourself, starting with ClassLoader#getResources()
wherein you pass ""
as name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With