我有一个接口(interface) TestInterface 有许多实现,当我使用 Guice 进行绑定(bind)时,我收到一条消息说 TestInterface
bind(TestInterface.class).annotatedWith(Names.named("Impl1Test")).to(Impl1.class);
p.s.我用一个虚拟接口(interface)进行了测试,但没有泛型,它工作得很好,我认为泛型需要做一些特殊的事情。
最佳答案
绑定(bind)泛型类型时,需要使用 TypeLiteral
而不是原始的class
.否则,Guice 将无法区分泛型类型。在您的情况下,它看起来像这样:
bind(new TypeLiteral<TestInterface<Impl1, Impl2>>(){})
.annotatedWith(Names.named("Impl1Test"))
.to(Impl1.class);
您甚至可能不需要
annotatedWith
如果您没有其他要绑定(bind)为 TestInterface<Impl1, Impl2>
的内容.注意 {}
在创建 TypeLiteral
... TypeLiteral
的匿名子类为了保留泛型类型信息是必要的。
关于Guice annotatedWith 用于与泛型的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4967350/