我有几个实现的类interface Provider<Communication>
,我正在使用带有@Named
注释的 Guice 来根据需要绑定它们,例如:
@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);
有没有一种干净的方法来实现一个将名称作为参数的工厂,例如:
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];
}
我尝试使用 Injector,但 Guice 不会将泛型作为 TypeLiteral 的参数:
public <C extends Communication> Provider<C> getCommunicationProvider(C communication) {
return injector.getInstance(Key.get(new TypeLiteral<CommunicationProvider<C>>() {},
Names.named(communication.getProvider().getId())));
}
这抛出:
com.google.inject.ConfigurationException: Guice configuration errors:
1) Provider<C> cannot be used as a key; It is not fully specified.