java – Guice Bind Generic Types

Is there any way to bind the generic type of the following type:

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 fully bind the above interface and its implementation (using typeliteral?), So that I can create a typed instance through 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 look?

Solution

What you lack 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());
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>