基本界面:
public interface Registry<E> {
E method();
}
接口实现:
RegistryImpl<E> implements Registry<E> {
@Inject
RegistryImpl(...) {
}
@Override
public E method() {
(...)
}
}
用于绑定数据对象A的注册表:
@BindingAnnotation
@Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface CustomDataObjectARegistry {
}
用于绑定数据对象B的注册表:
@BindingAnnotation
@Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME)
@interface CustomDataObjectBRegistry {
}
我想将CustomDataObjectARegistry绑定到RegistryImpl<DataObjectA>
,并且将CustomDataObjectBRegistry绑定到RegistryImpl<DataObjectB>
,但是还无法弄清楚语法。
bind(CustomDataObjectARegistry.class).to(new TypeLiteral<RegistryImpl<DataObjectA>>() {})
给我一个“无法解决的方法。”
答案 0 :(得分:0)
我想您要做的是:
bind(new TypeLiteral<Registry<DataObjectA>>() {}).to(new TypeLiteral<RegistryImpl<DataObjectA>>() {})
bind(new TypeLiteral<Registry<DataObjectB>>() {}).to(new TypeLiteral<RegistryImpl<DataObjectB>>() {})
//and then inject with generics:
Registry<DataObjectA> registryA;
Registry<DataObjectB> registryB;
或:
bind(Registry.class).annotatedWith(CustomDataObjectARegistry.class).to(new TypeLiteral<RegistryImpl<DataObjectA>>() {})
bind(Registry.class).annotatedWith(CustomDataObjectBRegistry.class).to(new TypeLiteral<RegistryImpl<DataObjectB>>() {})
//and then inject with annotations:
@CustomDataObjectARegistry Registry registryA;
@CustomDataObjectBRegistry Registry registryB;
基本上,您可以使用完整的通用签名进行区分,也可以使用批注,但您不必同时使用两者。我建议通过泛型来区分。