【发布时间】:2016-05-18 18:16:57
【问题描述】:
我的 Java 类表示数据库中的实体,我发现覆盖我的类的 equals 方法以按 id 进行比较是实用的。因此,例如在我的Transaction 类中,我有这段代码
@Override
public boolean equals(Object other){
if (other == null) return false;
if (other == this) return true;
if (!(other instanceof Transaction))return false;
Transaction otherTrans = (Transaction) other;
if (id == null || otherTrans.id == null) return false;
return id.equals(otherTrans.id);
}
现在对我来说似乎有点难看,每个类都拥有相同的代码,只是类的名称发生了变化。我想过让我的类扩展一个超类MyEntity,我将在其中编写上述方法,将instanceof Transaction 替换为instanceof this.getClass() 之类的东西,但这似乎是不可能的。我还考虑过用instanceof MyEntity 替换它,但这意味着两个对象即使属于不同的类也可以被认为是相等的,只要它们具有相同的ID。
有没有其他办法?
【问题讨论】:
标签: java instanceof dynamic-typing