How can I add a bunch of classes to an ArrayList<MyBaseClass>
and then later retrieve a Class (derived from, but not MyBaseClass
) from the ArrayList
and use it to generate a new object of the actual Class retrieved (i.e. not MyBaseClass
since that is abstract)
All classes that need to be added all derive from the same abstract base Class (MyBaseClass
)
I can't really think of another way to achieve what I want to do, so hopefully this is possible... ?
Here is what I think you're asking for:
But if you find yourself needing to check if an object is the instance of a particular class, you're probably doing something wrong. Try creating an abstract method in
MyBaseClass
that can be implemented by each sub class in its own special way. Then, you can simplify thefor
loop to just this:To prevent the use of reflection, you are probably looking for the Abstract Factory Pattern. Here is a simple example how to implement it using Java 8:
See also How should I select which concrete implementation should be instantiated based on the user choice?