Search code examples
javaguice

Guice Bind Generic Types


is there a way to bind generic types of the next sort:

public interface A<T extends Number> {
  void print(T t);
}

public class B implements A<Integer> {
  @Override
  public void print(Integer i) {
    System.out.println(i);
  }
}

public class C implements A<Double> {
  @Override
  public void print(Double d) {
    System.out.println(d);
  }
}

how can I exactly bind the above interface and its implementations (using TypeLiteral?) so that I could create a typed instance by some condition?

class Main {
  public static void main(String[] args) {
    A a1 = Guice.createInjector(new MyModule()).getInstance( ??? );
    a1.print(1); //will print 1

    A a2 = Guice.createInjector(new MyModule()).getInstance( ??? );
    a2.print(1.0); //will print 1.0
  }

}

how does MyModule suppose to look like?


Solution

  • What you are missing is,

    Injector  injector = Guice.createInjector(new MyModule());
    A a1 = injector.getInstance(Key.get(new TypeLiteral<A<Integer>>() {}));
    

    And your MyModule

    public static class MyModule extends AbstractModule {
        @Override
        protected void configure() {
            bind(new TypeLiteral<A<Integer>>() {}).toInstance(new B());
        }
    }