JPA 实体和抽象实体上的 equals 方法
我有一个抽象实体类,由 3 个略有不同的实体实现。在我的 3 个子类中,我已经重写了 equals 和 has 方法,但问题是,我也应该在抽象实体中执行此操作吗?如果我不这样做,我将无法比较仅由抽象实体定义的实体,除非我对它们进行强制转换。如果我进行平等,我是否会冒险与不同的子实体进行比较并发现它们是相似的?
例子:
abstract class Log{}
SystemLog extends Log{}
UserLog extends Log{}
public void test(Log log){
Log myInner = new SystemLog();
if(log.equals(myInner)){
//do random stuff
}
}
I have a abstract entity class that 3 slightly different entities implements. In my 3 sub classes I have overriden the equals and has methods but the question is, should I also do this in the abstract entity? If I dont I will not be able to compare entities that are only defined by abstract entity unless i cast them. If i do a equals will I risk to compare to different sub entities and get that they are alike?
Example:
abstract class Log{}
SystemLog extends Log{}
UserLog extends Log{}
public void test(Log log){
Log myInner = new SystemLog();
if(log.equals(myInner)){
//do random stuff
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我看不出铸造有问题。 equals 的参数类型是 Object,因此您必须进行强制转换才能访问属性。
如果在每个子类中都定义了 equals 方法,那么什么时候会出现调用抽象超类中的 equals 的情况呢?
您都面临着将不同子实体相互比较的风险。想象一下,使用超类作为类型填充的对象是两个不同子类的两个实例。它与您是否覆盖超类中的 equals 没有太大关系。
在您的示例中,如果我们已经在实际子类中实现了,则可能不会调用抽象类 Log 中可能实现的 equals 方法:
假设:
I cannot see problem with casting. Type of argument to equals is Object, so you have to cast anyway to have access to attributes.
If you define equals method in each subclasses, when comes the situation where equals in abstract superclass is called?
You are in the risk of comparing different subentities to each others anyway. Just imagine Set with superclass as type populated with objects that are two instances of two different subclasses. It has not too much to do with do you override equals in superclass or not.
In your example equals method possibly implemented in abstract class Log will not be called, if we have implementation already in actual subclass:
Assuming: