Before I describe my problem let my say that I suspect I might simply lack the correct terms to search for, and that’s why my searches here on stackoverflor haven’t been fruitful. So links to answers would also be very much appreciated.
Im trying to make a library that has a Factory, lets call it “MyFactory”. MyFactory has a method that returns objects of the abstract class “MySuper”, but also one that exposes the avilable subclasses to “MySuper”. The library is intended to be expanded on a lot, so subclasses of “MySuper” will be added often, and then library will be recompiled, and dumped into a library folder of the application that uses it.
What I want is to be able to add a subclass of “MySuper” to the library, and have “MyFactory” become aware of it, preferebly without having to do anything else than create a new sublass of “MySuper”..
So far I use reflection to make “MyFactory” create new instances of a “MySuper” type, by giving the class name to a method, like this:
public MySuper getSuperObject(String name) {
return (MySuper) Class.forName("my.package." + name).newInstance(); }
But how can I get the factory to expose alle the “MySuper” classes as f.x. a List of String, so the applications that use the library know what they can call? Can I iterate the content of a package?
I’m open for solutions, the most important part is that in the future it should be very hassle free to add new “MySuper” sub-classes..
Thanks 🙂
UPDATE:
I just want to note that I have found a nice Java library that handles reflection in an easy way, and lets you search for subtypes of a specific class. So my problem can be solved with that library (I have tested it). Here is a link: http://code.google.com/p/reflections/
You are looking for a
Generic Factory Pattern. Something like..You may google for
Generic Factory Patternand you will find lots of examples.