Java 泛型 - 多次使用相同的通配符
我有一个使用泛型和有界通配符的类声明:
class Factory<T extends Logic<? extends Entity>,
U extends DAO<? extends Entity>>
{
}
基本上它是一个泛型工厂,它采用逻辑接口 (T) 并返回配置的实现。为了实例化逻辑,我采用了一个适当的 DAO 类来实现 DAO 接口 (U)。
逻辑接口和 DAO 接口都是通用的,并采用要使用的实体的类型作为其类型参数。但是,我想进一步限制这一点,以便 DAO 和 Logic 不仅具有扩展实体的类型参数,而且它们扩展相同的实体。结果可能类似于:
class <X extends Entity> Factory<T extends Logic<X>,
U extends DAO<X>>
{
}
Can I get that with java generics?
I have a class declaration which uses generics and bounded wildcards:
class Factory<T extends Logic<? extends Entity>,
U extends DAO<? extends Entity>>
{
}
Basically its a generic factory, which takes a logic interface (T) and returns a configured implementation. In order to instantiate the logic, I take a appropriate DAO class implementing the DAO interface (U).
Both interfaces for logic and DAO are generic as well and take the type of the entity to work with as their type parameter. However, I want to constrain that further, so that DAO and Logic not only have a type parameter which extends Entity, but that they extend the same Entity. The result may look similiar to that:
class <X extends Entity> Factory<T extends Logic<X>,
U extends DAO<X>>
{
}
Can I achieve that with java generics?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,你很接近。这样做:
替代方案
Yes, you're close. Do it like this:
Alternative
另一种方法可能是提供一个包装器(尽管这并不是很优雅;)):
Another approach could be to provide a wrapper (although that's not really elegant ;) ):
会进行以下工作吗? X 将是“通用”类型,其中 Logic 和 DAO 都将使用此类型。
Would the following work. X would be the "common" type, where Logic and DAO both would use this type.