Search code examples
javadependency-injectioninversion-of-control

IoC Deciding specific implemetation at runtime


I would like to implement some inversion of control in my framework.

So I have an interface GenericDatabase that defines the methods that have to be implemented. I do not know in advance which classes will implement this, but I have the methods that will call the interface methods. So at runtime I need to read, from a configuration file, which specific implementation should be used (otherwise, I would have to know all potential implementation classes that a user might use). I have read some Martin Fowler articles but did not clear the issue up.

How can I achieve this?

I guess I am trying something like:

GenericDatabase database = Class.forName("com.example.myCustomDatabase").newInstance();

Also with the handicap that it should be inside the try-with-resources:

try (GenericDatabase database = Class.forName("com.example.myCustomDatabase").newInstance()) {

Solution

  • After some testing, and I might be wrong, I think the right way is:

    try (GenericDatabase database = (GenericDatabase) Class.forName("com.example.myCustomDatabase").newInstance()) {
    

    with:

    public interface GenericDatabase extends AutoCloseable {
    

    where com.example.myCustomDatabase is read from a configuration file.