我有一个接口TestInterface <U,V>有很多实现,当我使用Guice进行绑定时,我收到一条消息,说TestInterface <Impl1,Impl2>没有绑定到实现.以下是我用来将接口与其实现绑定的语法.
绑定(TestInterface.class).annotatedWith(Names.named( "Impl1Test"))至(Impl1.class).
ps我测试了一个虚拟接口,但没有泛型,它工作正常,我认为泛型需要做一些特别的事情.
Col*_*inD 11
绑定泛型类型时,需要使用TypeLiteral而不是raw class.否则,Guice将无法区分泛型类型.在你的情况下,它看起来像这样:
bind(new TypeLiteral<TestInterface<Impl1, Impl2>>(){})
.annotatedWith(Names.named("Impl1Test"))
.to(Impl1.class);
Run Code Online (Sandbox Code Playgroud)
annotatedWith如果您没有其他想要绑定的东西,您可能甚至不需要TestInterface<Impl1, Impl2>.请注意,{}在创建TypeLiteral... TypeLiteral时,为了保留泛型类型信息,必须使用匿名子类.
| 归档时间: |
|
| 查看次数: |
975 次 |
| 最近记录: |