case nelson
case nelson

Reputation: 3677

Guice Provide instance based on Class name read from file

In my project I have a configuration file that lists the concrete implementation of an interface.

How do I configure my Guice module so that I can get an instance of the concrete class from the Type whenever the interface is injected?

interface A{}

class AImpl implements A{ @Inject public A(.....)}

class B {
  @Inject
  public B(A a) {}
}


class MyModule extends AbstractModule {
  ...
  @Provides
  public A getA(@ConfiguredClass String classname) {
     Class<A> aClass = (Class<A>) Class.forName(classname);
     // ???
     // this needs to be instantiated by Guice to fulfill AImpl's dependencies
     return aClass.newInstance();
  }
}

config:
class: my.package.AImpl

Upvotes: 1

Views: 2805

Answers (1)

John Ericksen
John Ericksen

Reputation: 11113

You could read in the configuration file during startup, convert it to a Map<Class, Class> and feed the mapping into the module and configure all the bindings like so:

public class MyModule extends AbstractMdoule{

    //interface -> concrete
    Map<Class, Class> implementsMap;
    ...
    public void configure() {
        for (Map.Entry<Class, Class> implEntry : implementsMap.entrySet()) {
            bind(implEntry.getKey()).to(implEntry.getValue());
        }
    }
}

Upvotes: 2

Related Questions