Guice SPI:按通配符类型查找绑定
Guice 提供了一种查找给定类型的所有绑定的方法 (Injector#findBindingsByType),它还提供了 TypeLiteral 类 似乎可以从中构造通配符类型。 我想做的是找到由通配符类型参数化的某种类型的所有绑定,但我不知道如何做到这一点。 看看 guice src 表明我可能会叫错树,但我想我无论如何都会问一下......所以例如给定一个类型
Foo<E extends Bar>
BarImplOne implements Bar
BarImplTwo implements Bar
和一些绑定,
bind(new TypeLiteral<Foo<BarImplOne>>() {}).to(MyFooOne.class);
bind(new TypeLiteral<Foo<BarImplTwo>>() {}).to(MyFooTwo.class);
然后我希望能够发现这两个绑定
Injector.findBindingsByType(TypeLiteral.get(Types.newParameterizedType(Foo.class, Types.subtypeOf(Bar.class))));
有任何想法吗?
干杯 马特
Guice provides a means to find all bindings for a given type (Injector#findBindingsByType) and it also provides a TypeLiteral class from which it seems possible to construct a wildcard type. What I would like to do is find all bindings for some type that is parameterised by a wildcard type but I can't figure out how to do it. A look at the guice src suggests I might be barking up the wrong tree but I figured I'd ask around anyway... so for example given a type
Foo<E extends Bar>
BarImplOne implements Bar
BarImplTwo implements Bar
and some bindings like
bind(new TypeLiteral<Foo<BarImplOne>>() {}).to(MyFooOne.class);
bind(new TypeLiteral<Foo<BarImplTwo>>() {}).to(MyFooTwo.class);
then I want to be able to discover both bindings with something like
Injector.findBindingsByType(TypeLiteral.get(Types.newParameterizedType(Foo.class, Types.subtypeOf(Bar.class))));
Any ideas?
Cheers
Matt
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,没有现成的 API 可以告诉您一个 TypeLiteral 是否可以从另一个 TypeLiteral 分配。 您需要使用一堆可怕的 instanceof 检查来执行老式循环。 像这样的恶心的事情:
当然,使用现成的 API 来做一些事情会更好。 我欢迎对实现和测试 TypeLiteral.isAssignableFrom(TypeLiteral) 的 Guice 做出贡献。 联系我们的用户名单来担任志愿者!
Unfortunately, there's no out-of-the-box API that will tell you whether one TypeLiteral is assignable from another. You'll need to do an old-school loop with a bunch of hideous instanceof checks. Something gross like this:
Of course, it would be much nicer to do something using an off-the-shelf API. I'd welcome an contribution to Guice that implements and tests TypeLiteral.isAssignableFrom(TypeLiteral). Contact our user's list to volunteer!