Home > Guice > How to inject a generic interface using Guice

How to inject a generic interface using Guice

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: ,
  1. fabgregas
    29 December 2009 at 1:53 pm

    At least copy things completely when publishing them.
    TypeLiteral is completely missing.

    • Tobias
      29 April 2011 at 7:25 am

      TypeLiteral is a class that is included with Guice, which is why Panos didn’t include its source code. Maybe you misunderstood that?

  2. 30 December 2009 at 9:32 am

    Please read more carefully the post. TypeLiteral is shown in the second code fragment.

  3. violoncello2003
    23 July 2012 at 12:48 am

    Thanks!

  4. violoncello2003
    23 July 2012 at 12:53 am

    One question, can we “not” use the annotations in your example? We use TypeLiteral to distinguish among implementations, wouldn’t it be a little redundant?

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: