Inject Generic Implementation using Guice

In order to use generics with Guice you need to use the TypeLiteral class to bind the generic variants. This is an example of how you're Guice injector configuration could look like:

package your-application.com;

import com.google.inject.AbstractModule;
import com.google.inject.TypeLiteral;

public class MyModule extends AbstractModule {
  @Override
  protected void configure() {
    bind(new TypeLiteral<Repository<Class1>>(){})
      .to(new TypeLiteral<MyRepository<Class1>>(){});
  }
}

(Repository is the generic interface, MyRepository is the generic implementation, Class1 is the specific class used in the generics).


Generics not being retained at run-time sure made it harder to grasp the concept at first. Anyways, there are reasons new ArrayList<String>().getClass() returns Class<?> and not Class<String> and although its safe to cast it to Class<? extends String> you should remember that generics are there just for compile-time type checks (sort of like implicit validation, if you will).

So if you want to use Guice to inject MyRepository (with any type) implementation whenever you need a new instance of Repository (with any type) then you don't have to think about generics at all, but you're on your own to ensure type safety (that's why you get those pesky "unchecked" warning).

Here is an example of code working just fine:

public class GuiceTest extends AbstractModule {

    @Inject
    List collection;

    public static void main(String[] args) {
        GuiceTest app = new GuiceTest();
        app.test();
    }

    public void test(){
        Injector injector = Guice.createInjector(new GuiceTest());
        injector.injectMembers(this);

        List<String> strCollection = collection;
        strCollection.add("I'm a String");
        System.out.println(collection.get(0));

        List<Integer> intCollection = collection;
        intCollection.add(new Integer(33));
        System.out.println(collection.get(1));
    }

    @Override
    protected void configure() {
        bind(List.class).to(LinkedList.class);
    }
}

This prints:

I'm a String
33

But that list is implemented by a LinkedList. Although in this example, if you tried to asign an int something that is String you would get an exception.

int i = collection.get(0)

But if you want to get an injectable object already type-casted and dandy you can ask for List<String> instead of just List, but then Guice will treat that Type variable as part of the binding key (similar to a qualifier such as @Named). What this means is that if you want injection specifically List<String> to be of ArrayList<String> implementation and List<Integer> to be of LinkedList<Integer>, Guice lets you do that (not tested, educated guess).

But there's a catch:

    @Override
    protected void configure() {
        bind(List<String>.class).to(LinkedList<String>.class); <-- *Not Happening*
    }

As you might notice class literals aren't generic. That's where you use Guice's TypeLiterals.

    @Override
    protected void configure() {
        bind(new TypeLiteral<List<String>>(){}).to(new TypeLiteral<LinkedList<String>>(){});
    }

TypeLiterals retain the generic type variable as part of meta-information to map to desired implementation. Hope this helps.


You can use (abuse?) the @ImplementedBy annotation to make Guice generate generic bindings for you:

@ImplementedBy(MyRepository.class)
interface Repository<T> { ... }

class MyRepository<T> implements Repository<T> { ... }

As long as just-in-time bindings are enabled, you can inject Repository<Whatever> without any explicit binding:

    Injector injector = Guice.createInjector();
    System.out.println(injector.getBinding(new Key<Repository<String>>(){}));
    System.out.println(injector.getBinding(new Key<Repository<Integer>>(){}));

The catch is that the target of the binding is MyRepository, rather than MyRepository<T>:

LinkedKeyBinding{key=Key[type=Repository<java.lang.String>, annotation=[none]], source=interface Repository, scope=Scopes.NO_SCOPE, target=Key[type=MyRepository, annotation=[none]]}
LinkedKeyBinding{key=Key[type=Repository<java.lang.Integer>, annotation=[none]], source=interface Repository, scope=Scopes.NO_SCOPE, target=Key[type=MyRepository, annotation=[none]]}

That's usually not a problem, but it means that MyRepository can't inject a TypeLiteral<T> to figure out its own type at runtime, which would be particularly useful in this situation. Aside from that, to the best of my knowledge, this works fine.

(If someone feels like fixing this, I'm pretty sure it would just require some extra calculations around here to fill in the target type parameters from the source key.)