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

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -