I have a factory class that creates objects of a certain type (say, MyClass).
The factory class belongs to a specific package and I want to dynamically switch between implementations in that package and a newer version, for testing purposes.
Say, for example, that the original package is pack1 and the newer version is pack2, with class names pack1.Factory and pack2.Factory. The selection of pack1 or pack2 would be specified via a simple parameter in a property file. Furthermore, the MyClass type is common for both packages and only plain vanilla Java (i.e., no third-party libraries) should be used.
I am thinking of using Class.forName() for loading either pack1.Factory or pack2.Factory (depending on the property specified) and then invoking all factory methods via reflection.
Is that the best approach?
This is almost a classical usecase for an injection of control. Guice should get you started in no time.
There is a need to have an interface such as
IFactory, with some factory methodcreate. Create two Guice modules — in one bindIFactorytopack1.Factoryand in another topack2.Factory. Of course, both these factories should implementIFactory.Then in the main method process your parameter that determines what factory should be used, and create an injector based on one of the modules respectively.