Guice annotatedWith for interface with Generics
I have an interface TestInterface<U,V> that has many implementation开发者_如何学JAVAs, 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.
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.
精彩评论