Automatic factory registration

This is possible, but not easily. It would need to scan all the classes in the classpath to see if they have an annotation or implement the IProduct interface. See How do you find all subclasses of a given class in Java? for answers to such a problem.

I would do keep it simple and just have a list of classes to load, either in the factory itself, or in an external file (properties file, for example).


  1. Have each product register itself, using a static block like this:

     class MyProduct1{
    
         static{
             SomeFactory.register(MyProduct1.getClass());
         }
         ..
         ..
     }
    
  2. An external property file can keep track of all Products.

  3. Your main method can parse this list of Products and do a Class.forName("..").

This way you wouldnt need to code any specific product, just the property file keeps changing. Ah! yes adding security registration would also be a plus point.

Note: I'm just proposing an idea, I'vent tried it myself :)

Tags:

Java

Factory