Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice annotatedWith for interface with Generics

Tags:

guice

I have an interface TestInterface<U,V> that has many implementations, when I use Guice for binding I get a message saying TestInterface<Impl1, Impl2> not bound to an implementation. Following is the syntax I am using to bind interface with its implementations.

bind(TestInterface.class).annotatedWith(Names.named("Impl1Test")).to(Impl1.class);

p.s. I tested with a dummy interface but without generics and it worked fine, I reckon for generics something special needs to be done.

like image 615
Abidi Avatar asked Feb 11 '11 09:02

Abidi


1 Answers

When binding generic types, you need to use a TypeLiteral rather than the raw class. Otherwise, Guice wouldn't be able to distinguish between the generic types. In your case, it would look something like this:

bind(new TypeLiteral<TestInterface<Impl1, Impl2>>(){})
    .annotatedWith(Names.named("Impl1Test"))
    .to(Impl1.class);

You may not even need the annotatedWith if you don't have other things that you want to bind as TestInterface<Impl1, Impl2>. Note the {} in the creation of the TypeLiteral... an anonymous subclass of TypeLiteral is necessary in order to have the generic type information preserved.

like image 159
ColinD Avatar answered Oct 14 '22 10:10

ColinD