reflection - How can I generate a Java factory at compile time? -
i have interface has been implemented maybe 50 times , app keep on evolving new implementations. these implementations should loaded depending on name (which constant available in each implementation).
i want avoid using reflection @ runtime (because reflections lib pulls 3mb of dependencies , need keep jar small possible) , avoid having add entry factory each time implementation added.
so wondering: how can automatically @ compile time ? need build map of implmentation.name => implmentationconstructor
thanks
edit: i'm looking here not have care writing code load classes. mean having factory generated automatically on compile (full code generation) or using kind of serviceloader-like tool supports auto-generating required files , supporting constructors arguments. easiest solution come use reflection in unit tests check implementations accessible through constructor , if not, output in console code needs put in factory are.
the java serviceloader can used manage (and select from) large number of implementations of interface. add file, named interface, contains full qualified name of implementations to:-
meta-inf/services/com.my.interface.myinterface
the serviceloader can load , manage implementations you. in factory method, can select appropriate implementation , return it.
serviceloader<myinterface> impls = serviceloader.load(myinterface.class); for(myinterface impl : impls) { //iterating on each impl }
Comments
Post a Comment