Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic factory registration

Tags:

java

factory

i'm just learning java, and i meet some problems. Here we have simple factory pattern:

public class SomeFactory {
    ...
     public static void registerProduct(String name, Class<? extends IProduct > f)
}

public SomeProduct implements IProduct {
   static {
       SomeFactory.register("some product", SomeProduct.class);
   }
   ...
}

All products should register themselves at factory.

But before using this code, all Products classes should be loaded. I can put Class.forName() somewhere, for example in main function. But i want to avoid such sort of manual classes loading. I want just add new IProduct implementations, without updating other parts(such as SomeFactory or Main methods, etc.). But i wonder, is it possible to automatically load some classes(marked with annotation, for example)?

P.S I want to notice, that no other classes will be added at run-time, all IProduct implementations are known before compiling.

UPD#1 Thank for your answering! But is it possible to make auto-generated property-file with IProduct instances? I mean is it possible to make some build-time script(for maven for example) that generates property-file or loader code? Are there such solutions or frameworks?

UPD#2 I finished with using Reflections library that provides run-time information, by scanning classpath at startup.

like image 373
nmikhailov Avatar asked Oct 01 '11 08:10

nmikhailov


2 Answers

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).

like image 99
JB Nizet Avatar answered Nov 02 '22 05:11

JB Nizet


  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 :)

like image 3
Rajeev Sreedharan Avatar answered Nov 02 '22 05:11

Rajeev Sreedharan