2013-08-19 34 views
2

我想爲注入的字段使用類的泛型參數,但是guice會抱怨未綁定的鍵。是否有可能在Test2中注入該字段?Google Guice - 使用泛型作爲注入字段的參數

例子:

public static class Test1<T1> { 
    } 

    public static class Test2<T2> { 
     @Inject 
     public Test1<T2> test; 
    } 

    public static void main(String[] args) throws Exception { 
     Injector injector = Jsr250.createInjector(Stage.PRODUCTION, new TestModule()); 
     Test2<String> test = injector.getInstance(Key.get(new TypeLiteral<Test2<String>>(){})); 
    } 

    private static class TestModule extends AbstractModule { 
     @Override 
     protected void configure() { 
      bind(new TypeLiteral<Test1<String>>(){}).toInstance(new Test1<String>()); 
      bind(new TypeLiteral<Test2<String>>(){}).toInstance(new Test2<String>()); 
     } 
    } 

回答

0

好了,這是矯枉過正Java泛型。即使沒有注射,您的代碼也無法使用,因爲Test1<T2>無法匹配Test1<String>。你應該考慮不同的方法,嘗試使用Annotation binding,如:

public static class Test2 { 
     @Inject @Named("T2") 
     public Test1<someGenericInterface> test; 
    } 

bind(new TypeLiteral<Test1<someGenericInterface>>(){}).annotatedWith(Names.named("T2")).toInstance(new Test1<T2>()); //T2 implements someGenericInterface 
bind(new TypeLiteral<Test1<someGenericInterface>>(){}).annotatedWith(Names.named("T1")).toInstance(new Test1<T1>()); //T1 implements someGenericInterface 

或實現特定供應商Provider bindings或使用MapBinder