代码之家  ›  专栏  ›  技术社区  ›  Igor

guice绑定泛型类型

  •  3
  • Igor  · 技术社区  · 6 年前

    是否有方法绑定下一类的泛型类型:

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

    如何准确绑定上述接口及其实现(使用 TypeLiteral ?)以便我可以通过某种条件创建类型化实例?

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

    怎样做 MyModule 假设看起来像?

    2 回复  |  直到 6 年前
        1
  •  3
  •   Ryan Leach    6 年前

    你缺少的是,

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

    还有你的mymodule

    public static class MyModule extends AbstractModule {
        @Override
        protected void configure() {
            bind(new TypeLiteral<A<Integer>>() {}).toInstance(new B());
        }
    }
    
        2
  •  3
  •   Olivier Grégoire    6 年前

    您可以创建提供程序方法,而不必使用 TypeLiteral<A<Integer>> 在定义中。

    class MyModule extends AbstractModule {
      @Provides
      @Singleton
      A<Integer> provideAOfInteger() {
        return new B();
      }
    }
    

    您还可以使用隐式绑定来访问 A<Integer> :

    class AOfIntegerHolder {
      @Inject A<Integer> aOfInteger;
    }
    
    Injector injector = Guice.createInjector(new MyModule());
    A<Integer> a1 = injector.getInstance(AOfIntegerHolder.class).aOfInteger;
    

    guice的美妙之处在于,有很多方法可以做你想做的事情,但没有一种方法比另一种更好:它们只是不同而已;)