Guice泛型 - 我怎样才能让它变得不那么难看?

Fin*_*arr 8 java generics coding-style guice

我有一个接口Producer<T>和一个FooProducer实现的具体Producer<Foo>.在guice中绑定这个看起来像罪恶一样丑陋:

bind(new TypeLiteral<Producer<Foo>>() {}).to(FooProducer.class);
Run Code Online (Sandbox Code Playgroud)

我有很多这样的绑定.我尝试过以下方法:

static <T> TypeLiteral<Producer<T>> producer() {
    return new TypeLiteral<Producer<T>>(){};
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式拨打电话:

bind(ContainingClass.<Foo>producer()).to(FooProducer.class);
Run Code Online (Sandbox Code Playgroud)

但它给出了一个错误Producer<T> is not specific enough....

我是以错误的方式解决这个问题吗?

Dar*_*roy 8

代替

bind(new TypeLiteral<Producer<Foo>>() {}).to(FooProducer.class);
Run Code Online (Sandbox Code Playgroud)

尝试一种方便的方法

static <T> Key<Producer<T>> producerOf(Class<T> type) {
  return (Key<Producer<T>>)Key.get(Types.newParameterizedType(Producer.class,type));
}
Run Code Online (Sandbox Code Playgroud)

然后在你的模块中

bind(producerOf(Foo.class)).to(FooProducer.class);
Run Code Online (Sandbox Code Playgroud)

那个未经检查的演员应该是安全的.密钥是com.google.inject.Key,而类型是com.google.inject.util.Types.

祝好运

  • 这可以在这个简单的情况下工作,但如果你想要,那就不要说,`生产者<List <Foo >>`.总的来说,这似乎是浪费精力,特别是当你必须为你想要使用的每个参数化类型制作一个这样的方法时,但是无论是什么漂浮在OP的船上我猜. (3认同)

Jes*_*son 7

您可以通过键入new Key<Producer<Foo>>(){}而不是键入来保存8个字符new TypeLiteral<Producer<Foo>>(){}.或者使用等效的@Provides方法:

@Provides
public Producer<Foo> provideFooProducer(FooProducer fooProducer) {
  return fooProducer;
}
Run Code Online (Sandbox Code Playgroud)