简体   繁体   中英

Guice generic type injection

Lets say I have a generic class as follows:

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

The instance of type Stoppable is binded using Multibinder :

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

Is it possible to achieve this?

No, it is not possible to achieve this in a way you are trying to.

But you could pass Class / Type object to Base 's constructor and use it to create needed type literal, eg (I use Set as key since you mentioned 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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM