Automatic factory registration

与世无争的帅哥 提交于 2021-01-22 05:12:32

问题


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.


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/7619153/automatic-factory-registration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!