Guice 泛型类型注入

Guice generic type injection

假设我有一个通用的 class 如下:

public class Base<T extends Stoppable> {

  protected final Injector injector;
  protected T stoppable;

  public Base(Module... module) {
    injector = Guice.createInjector(module);
    Key<T> key = Key.get(new TypeLiteral<T>() {});  <-- T cannot be used as a key; It is not fully specified.
    stoppable = injector.getInstance(key);
  }
}

Stoppable 类型的实例使用 Multibinder 绑定:

Multibinder<Stoppable> taskBinder =
    Multibinder.newSetBinder(binder, Stoppable.class);
taskBinder.addBinding().to(MyClass.class);

有可能实现吗?

不,不可能以您尝试的方式实现。

但是您可以将 Class/Type 对象传递给 Base 的构造函数并使用它来创建所需的类型文字,例如(我使用 Set 作为键,因为你提到了 multibinder):

public class Base<T extends Stoppable> {

  protected final Injector injector;
  protected T stoppable;

  public Base(Class<T> type, Module... module) {
    injector = Guice.createInjector(module);
    var key = Key.get(com.google.inject.util.Types.setOf(type));
    stoppable = injector.getInstance(key);
  }
}