Java泛型进阶问题:为什么我们需要指定冗余信息
我的 JPA 模型 POJO 有一些通用类,如下所示:
public interface Identifiable<PK extends Serializable> {
PK getUniqueId();
}
public interface GenericDao<T extends Identifiable<PK>> {
public T findById(PK id);
}
此代码无法编译。 为此,我需要指定
public interface GenericDao<T extends Identifiable<PK>, PK extends Serializable>
但这是多余的信息! T 扩展 Identificable 的事实意味着将为 Identifying 实例指定 PK 类型,并且这是用于 DAO PK 的类型。
我怎样才能在没有冗余信息的情况下完成这项工作?
谢谢 Fred
编辑: 简化示例
I've got some generic class for my JPA model POJO that goes like this:
public interface Identifiable<PK extends Serializable> {
PK getUniqueId();
}
public interface GenericDao<T extends Identifiable<PK>> {
public T findById(PK id);
}
This code won't compile. For this to work, I need to specify
public interface GenericDao<T extends Identifiable<PK>, PK extends Serializable>
But that's redundant information !! The fact that T extends Identifiable imply that a PK type will be specified for the Identifiable instance and that this is the type to use for the DAO's PK.
How can I make this work without redundant information ?
Thanks, Fred
Edit: Simplified example
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你尝试过吗:(
即它是一个
Watchable
,但我不在乎Something
是什么)我还没有尝试过,但值得一试。
编辑:问题编辑后,看来您确实需要 PK 作为接口的类型参数。 在这种情况下,我相信你必须像你正在做的那样有效地重复约束。 是的,它是多余的,但我认为它比语言必须根据其在其他地方用作类型参数来指定哪些有效约束将应用于 PK 更简单。 如果有什么安慰的话,C# 中也是如此。
它还使得 PK 的约束仅从接口本身就变得清晰,而不必查看另一个接口来看看什么是可行的。
Have you tried:
(i.e. it's a
Watchable<Something>
but I don't care whatSomething
is)I haven't tried it, but it's worth a go.
EDIT: Post question edit, it seems that you really do need PK as a type parameter to the interface. In that case, I believe you have to effectively repeat the constraint as you are doing. Yes, it's redundant, but I think it's simpler than the language having to specify what effective constraints would apply to PK based on its use as a type argument elsewhere. If it's any consolation, the same is true in C#.
It also makes the constraints on PK clear from just the interface itself, rather than having to look at another interface to see what's feasible.