As mentioned in another answer, this is not possible using purely reflection.
Unless you can customize your classes to specifically handle this case, you'd need to dive into either iterating over classes from the class loader, or using a custom class loader that adds the information into an internal data structure so that when it is requested later you don't have to reiterate over all classes.
Assuming you're not interested in diving into class loader code (it sounds like you are not), the next best way of doing this is adding static code to your classes that gets run at class loading time. For example:
public class Animal {
protected static List subclasses = new ArrayList();
//...
}
public class Cat extends Animal {
static {
subclasses.add(Cat.class);
}
//...
}
This would be essentially what you would do with a custom class loader, where this code would live in the class loader instead of the class.
Repeat this pattern for all subclasses. Then when you want to create instances, you have class references inside the subclasses
list, which you would instantiate with Class.newInstance
(or another suitable reflection method if your constructors have arguments).
array/list
of subclass (Lets say Cat) and store all the subclass objects(it would be a Cat ,Dog or anyother subclass) incats list/array
– TruckleinstanceOf
on every index – Truckle