title: Injecting generics with Guice
body: <p>I am trying to migrate a small project, replacing some factories with Guice (it is my first Guice trial). However, I am stuck when trying to inject generics. I managed to extract a small toy example with two classes and a module:</p>
  
  <pre><code>import com.google.inject.Inject;
  
  public class Console&lt;T&gt; {
    private final StringOutput&lt;T&gt; out;
    @Inject
    public Console(StringOutput&lt;T&gt; out) {
      this.out = out;
    }
    public void print(T t) {
      System.out.println(out.converter(t));
    }
  }
  
  public class StringOutput&lt;T&gt; {
    public String converter(T t) {
      return t.toString();
    }
  }
  
  import com.google.inject.AbstractModule;
  import com.google.inject.Guice;
  import com.google.inject.Injector;
  import com.google.inject.TypeLiteral;
  
  
  public class MyModule extends AbstractModule {
  
    @Override
    protected void configure() {
      bind(StringOutput.class);
      bind(Console.class);
    }
  
    public static void main(String[] args) {
      Injector injector = Guice.createInjector( new MyModule() );
      StringOutput&lt;Integer&gt; out = injector.getInstance(StringOutput.class);
      System.out.println( out.converter(12) );
      Console&lt;Double&gt; cons = injector.getInstance(Console.class);
      cons.print(123.0);
    }
  
  }
  </code></pre>
  
  <p>When I run this example, all I got is:</p>
  
  <p>Exception in thread "main" com.google.inject.CreationException: Guice creation errors:</p>
  
  <pre><code>1) playground.StringOutput&lt;T&gt; cannot be used as a key; It is not fully specified.
    at playground.MyModule.configure(MyModule.java:15)
  
  1 error
      at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:354)
      at com.google.inject.InjectorBuilder.initializeStatically(InjectorBuilder.java:152)
      at com.google.inject.InjectorBuilder.build(InjectorBuilder.java:105)
      at com.google.inject.Guice.createInjector(Guice.java:92)
  </code></pre>
  
  <p>I tried looking for the error message, but without finding any useful hints. Further on the Guice FAQ I stumble upon a question about how to inject generics. I tried to add the following binding in the <code>configure</code> method:</p>
  
  <pre><code>bind(new TypeLiteral&lt;StringOutput&lt;Double&gt;&gt;() {}).toInstance(new StringOutput&lt;Double&gt;());
  </code></pre>
  
  <p>But without success (same error message).</p>
  
  <p>Can someone explain me the error message and provide me some tips ? Thanks.</p>