Injecting generics with Guice

Posted by paradigmatic on Stack Overflow See other posts from Stack Overflow or by paradigmatic
Published on 2010-04-05T20:57:55Z Indexed on 2010/04/05 21:43 UTC
Read the original article Hit count: 607

Filed under:
|
|

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:

import com.google.inject.Inject;

public class Console<T> {
  private final StringOutput<T> out;
  @Inject
  public Console(StringOutput<T> out) {
    this.out = out;
  }
  public void print(T t) {
    System.out.println(out.converter(t));
  }
}

public class StringOutput<T> {
  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<Integer> out = injector.getInstance(StringOutput.class);
    System.out.println( out.converter(12) );
    Console<Double> cons = injector.getInstance(Console.class);
    cons.print(123.0);
  }

}

When I run this example, all I got is:

Exception in thread "main" com.google.inject.CreationException: Guice creation errors:

1) playground.StringOutput<T> 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)

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 configure method:

bind(new TypeLiteral<StringOutput<Double>>() {}).toInstance(new StringOutput<Double>());

But without success (same error message).

Can someone explain me the error message and provide me some tips ? Thanks.

© Stack Overflow or respective owner

Related posts about guice

Related posts about java