我有一个接口Producer<T>
和一个具体FooProducer
实现Producer<Foo>
。固执地将其束缚为罪恶是丑陋的:
bind(new TypeLiteral<Producer<Foo>>() {}).to(FooProducer.class);
我有很多这样的绑定。我尝试了以下方法:
static <T> TypeLiteral<Producer<T>> producer() {
return new TypeLiteral<Producer<T>>(){};
}
通过这种方式进行的呼叫:
bind(ContainingClass.<Foo>producer()).to(FooProducer.class);
但这会导致错误Producer<T> is not specific enough...
。
我会以错误的方式处理吗?
代替
bind(new TypeLiteral<Producer<Foo>>() {}).to(FooProducer.class);
尝试像
static <T> Key<Producer<T>> producerOf(Class<T> type) {
return (Key<Producer<T>>)Key.get(Types.newParameterizedType(Producer.class,type));
}
然后在你的模块中
bind(producerOf(Foo.class)).to(FooProducer.class);
那未经检查的演员应该是安全的。键是com.google.inject.Key,类型是com.google.inject.util.Types。
祝好运
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句