krizajb
krizajb

Reputation: 1814

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?

Upvotes: 1

Views: 211

Answers (1)

Yurii Melnychuk
Yurii Melnychuk

Reputation: 898

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, e.g. (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);
  }
}

Upvotes: 1

Related Questions