在Guice注入一个通用工厂 [英] Injecting a generic factory in Guice

查看:135
本文介绍了在Guice注入一个通用工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是给出一个 Foo< T> Bar< T> 。工厂不在乎什么 T 是:对于任何类型 T ,它可以使一个 Foo< T> 中的< T> 。

The following code is an example of a factory that produces a Bar<T> given a Foo<T>. The factory doesn't care what T is: for any type T, it can make a Bar<T> from a Foo<T>.

import com.google.inject.*;
import com.google.inject.assistedinject.*;

class Foo<T> {
  public void flip(T x) { System.out.println("flip: " + x); }
}

interface Bar<T> {
  void flipflop(T x);
}

class BarImpl<T> implements Bar<T> {
  Foo<T> foo;

  @Inject
  BarImpl(Foo<T> foo) { this.foo = foo; }

  public void flipflop(T x) { foo.flip(x); System.out.println("flop: " + x); }
}

interface BarFactory {
  <T> Bar<T> create(Foo<T> f);
}

class Module extends AbstractModule {
  public void configure() {
    bind(BarFactory.class)
      .toProvider( 
          FactoryProvider.newFactory( BarFactory.class, BarImpl.class ) 
                   );
  }
}

public class GenericInject {
  public static void main(String[] args) {
    Injector injector = Guice.createInjector(new Module());

    Foo<Integer> foo = new Foo<Integer>();
    Bar<Integer> bar = injector.getInstance(BarFactory.class).create(foo);
    bar.flipflop(0);
  }
}

当我运行代码时,我收到以下错误从Guice:

When I run the code, I get the following errors from Guice:

1) No implementation for BarFactory was bound.
  at Module.configure(GenericInject.java:38)

2) Bar<T> cannot be used as a key; It is not fully specified.

我们可以在Guice文档中找到泛型的唯一参考资料,说使用 TypeLiteral 。但是我没有字面类型,我有一个与工厂无关的通用占位符。任何提示?

The only reference I can find to generics in the Guice documentation says to use a TypeLiteral. But I don't have a literal type, I have a generic placeholder that isn't relevant to the factory at all. Any tips?

推荐答案

一个选项是手写BarFactory样板:

One option is to just write the BarFactory boilerplate by hand:

class BarImplFactory implements BarFactory {
  public <T> Bar<T> create(Foo<T> f) {
    return new BarImpl(f);
  }
}

绑定成为

bind(BarFactory.class).to(BarImplFactory.class);

这篇关于在Guice注入一个通用工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆