【问题标题】:Guice generic type injectionGuice 泛型类型注入
【发布时间】:2021-11-05 10:43:59
【问题描述】:

假设我有一个通用类如下:

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);

有可能实现吗?

【问题讨论】:

    标签: java guice


    【解决方案1】:

    不,不可能以您尝试的方式实现这一目标。

    但是您可以将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);
      }
    }
    

    【讨论】:

    • 是的,我实际上有 Set 可停止。谢谢你的建议!
    猜你喜欢
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 2019-03-07
    相关资源
    最近更新 更多