Archive

Archive for the ‘Guice’ Category

How to inject a generic interface using Guice

17 November 2008 5 comments

In order to inject any generic type in Guice we should use a TypeLiteral. Lets say that we have a parameterised AnInterface interface and a myMethod method

public interface AnInterfacel<T>
{
    boolean myMethod(T object);
}

Now lets assume that we have two implementations of this interface, AnInterfaceImplA that uses the myMethod with a String and AnInterfaceImplB that uses the myMethod with an Integer. We want to inject these two by using guice. In order to do that we need to create a TypeLiteral

bind(new TypeLiteral<AnInterface<String>>(){}).annotatedWith(Names.name("NameA")).to(AnInterfaceImplA.class);
bind(new TypeLiteral<AnInterface<Integer>>(){}).annotatedWith(Names.name("NameB")).to(AnInterfaceImplB.class);

That’s it. We can then use the @Inject annotation to inject these implementation classes

@Inject
public MyClass(@Named("NameA") AnInterface<String> implementationA, @Named("NameB") AnInterface<Integer> implementationB)
{
...
}
Advertisements
Categories: Guice Tags: ,