I have several classes implementing interface Provider<Communication>
and I'm using Guice with a @Named
annotation to bind them as required, e.g.:
@Singleton
public class Verizon implements Provider<Call> {
...
}
@Singleton
public class TMobile implements Provider<Call> {
...
}
bind (new TypeLiteral<Provider<Call>>() {}).annotatedWith(
Names.named("Verizon")).to(Verizon.class);
bind (new TypeLiteral<Provider<Call>>() {}).annotatedWith(
Names.named("TMobile")).to(TMobile.class);
Is there a clean way to implement a factory that takes the name as a parameter, e.g.:
public static <C extends Communication> Provider<C> getCallProvider(C communication) {
String providerName = communication.getProviderName();
return [Guice's matching object for type Provider<?> and @Named = providerName];
}
I've attempted using Injector but Guice won't take a generic as parameter to TypeLiteral:
public <C extends Communication> Provider<C> getCommunicationProvider(C communication) {
return injector.getInstance(Key.get(new TypeLiteral<CommunicationProvider<C>>() {},
Names.named(communication.getProvider().getId())));
}
This throws:
com.google.inject.ConfigurationException: Guice configuration errors:
1) Provider<C> cannot be used as a key; It is not fully specified.