2014-10-20 35 views
0

我遇到了一個錯誤,試圖讓guice連線。下面是轉載我看到的問題的一些示例代碼:從靜態類/接口Guice的泛型配置錯誤

public class GuiceGenerics<K, V> { 

    public static interface Foo<K, V> { 

    } 

    public static class FooImpl<K, V> implements Foo<K, V> { 

    } 

    public static class FooModule extends PrivateModule { 

     @Override 
     protected void configure() { 
      bind(new TypeLiteral<Foo<String, Integer>>(){}).to(new TypeLiteral<FooImpl<String, Integer>>(){}); 

      bind(new TypeLiteral<GuiceGenerics<String, Integer>>(){}); 
      expose(new TypeLiteral<GuiceGenerics<String, Integer>>(){}); 
     } 
    } 

    private Foo<K, V> foo; 

    @Inject 
    public GuiceGenerics(Foo<K, V> foo) { 
     this.foo = foo; 
    } 

    public static void main(String args[]) { 
     Injector injector = Guice.createInjector(new FooModule()); 
     GuiceGenerics<String, Integer> guiceGenerics = injector.getInstance(GuiceGenerics.class); 
    } 
} 

當我運行的main(),我得到這個錯誤:

Exception in thread "main" com.google.inject.ConfigurationException: Guice configuration errors: 

1) com.knewton.recommendationservice.retries.GuiceGenerics$Foo<K, V> cannot be used as a key; It is not fully specified. 
    at com.knewton.recommendationservice.retries.GuiceGenerics.<init>(GuiceGenerics.java:36) 
    while locating com.knewton.recommendationservice.retries.GuiceGenerics 

1 error 
    at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1004) 
    at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:961) 
    at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1013) 
    at com.knewton.recommendationservice.retries.GuiceGenerics.main(GuiceGenerics.java:42) 

我得到的是我使用不當TypeLiteral的感覺,但我無法弄清楚我做錯了什麼。有什麼建議麼?

回答

1

由於類型刪除,您的getInstance()呼叫無法工作。代之以:

GuiceGenerics<String, Integer> guiceGenerics = 
     injector.getInstance(new Key<GuiceGenerics<String, Integer>>() { });