Guice泛型-如何使它不那么丑陋?

Finbarr:

我有一个接口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...

我会以错误的方式处理吗?

达伦·吉尔罗伊(Darren Gilroy):

代替

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章