2012-04-18 86 views
2

時,此工作:吉斯,注射TypeLiteral <T>使用@AssistedInject

public static class SomeGenericType<T> { 
    private TypeLiteral<T> type; 

    @Inject 
    public SomeGenericType(TypeLiteral<T> type) { 
     this.type = type; 
    } 

    public Class<? super T> getType() { 
     return type.getRawType(); 
    } 
} 

吉斯自動注入的TypeLiteral代表字符串,當我做:

@Inject SomeGenericType<String> foo; 

但隨着輔助進樣想同樣的事情時:

public static interface FooFactory<T> { 
    Foo<T> create(String name); 
} 

public static class Foo<T> { 

    @AssistedInject 
    public Foo(TypeLiteral<T> type, @Assisted String name) { 
     .... 

我的模塊看起來像這樣:

public static class TestMod extends AbstractModule { 
    @Override 
    protected void configure() { 
     install(new FactoryModuleBuilder().build(new TypeLiteral<FooFactory<String>>(){})); 
    } 
} 

我得到一個異常,同時安裝模塊:

TypeLiteral<T> cannot be used as a Key, it is not fully specified. 

這肯定是我正在試圖注入這就是問題所在,因爲一般工廠做,當我刪除它做工精細的TypeLiteral 。

所以,我可能只是推出我自己的工廠,但我很好奇這是否應該工作?是否使用FactoryModuleBuilder稍有不同?

回答

4

你如何訪問FooFactory的實例?我內置下面的代碼的變化和它的工作對我來說:

public class AnotherGuiceTest { 
    public static void main(String[] args) { 
     Injector i = Guice.createInjector(new TestMod()); 
     FooFactory<String> ff = i.getInstance(Key.get(new TypeLiteral<FooFactory<String>>() {})); 
     ff.create("myname"); 
    } 
} 

interface FooFactory<T> { 
    Foo<T> create(String name); 
} 

class Foo<T> { 

    @Inject 
    public Foo(TypeLiteral<T> type, @Assisted String name) { 
     System.out.println(type.getRawType()); 
     System.out.println(name); 
    } 
} 

class TestMod extends AbstractModule { 
    @Override 
    protected void configure() { 
     install(new FactoryModuleBuilder().build(new TypeLiteral<FooFactory<String>>() {})); 
    } 
} 

輸出:

class java.lang.String 
myname 

注意我用了一個普通@Inject註釋,而不是@AssistedInject認爲是在多個構造一個工廠。

public class AnotherGuiceTest { 
    public static void main(String[] args) { 
     Injector i = Guice.createInjector(new TestMod()); 
     AppClass ac = i.getInstance(AppClass.class); 
    } 
} 

class AppClass { 
    @Inject 
    public AppClass(FooFactory<String> fooFactory) { 
     fooFactory.create("test"); 
    } 
} 

輸出:

class java.lang.String 
test 
+0

啊哈..所以這是一個設置問題,如果你直接注入實例這也適用。感謝您花時間測試它並回答。原來,這是因爲我有一個涉及GIN的jar,guice-assistedinject-snapshot.jar而不是guice-assistedinject-3.0.jar(注意,常規的輔助注入似乎可以在這個jar中工作,而不是在泛型中) – aidanok 2012-04-19 19:31:21