Automatic registration factory

I am just learning java and I am encountering some problems. Here we have a 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 must be registered with the factory.

But before using this code, you must download all product classes. I can put Class.forName()somewhere, for example, in the main function. But I want to avoid such loading of manual classes. I want to just add a new one IProduct without updating other parts (e.g. methods SomeFactoryor Mainetc.). But I wonder if it is possible to automatically load some classes (marked, for example, with an annotation)?

PS I want to note that no other classes will be added at runtime, all implementations are IProductknown before compilation.

UPD # 1 ! IProduct? , script (, maven), ? ?

UPD # 2 , , .

+5
2

, . , , IProduct. . Java? ​​.

, factory, (, ).

+5
  • , :

    class MyProduct1{
    
        static{
            SomeFactory.register(this.getClass());
        }
        ..
        ..
    }
    
  • .

  • Class.forName( ".." ).

, - , . ! , .

: , :)

+3

All Articles