【发布时间】:2015-11-09 22:48:20
【问题描述】:
我经常使用 Eclipse 的代码生成工具(Source / Generate hashCode() 和 equals()...)为简单的 POJO 类创建 equals() 实现。如果我选择“使用 instanceof 来比较类型”,则会产生类似于以下的 equals() 实现:
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MyClass)) {
return false;
}
MyClass other = (MyClass) obj;
// check the relevant fields for equality
}
今天一位同事指出,第二个if语句根本不需要,因为只要obj为null,instanceof类型检查就会返回false。 (See question 3328138.)
现在,我想那些为 Eclipse JDT 编写代码模板的人也值得一试。所以我认为空检查一定有一些原因,但我不确定它是什么?
(另外question 7570764 可能会给出提示:如果我们使用 getClass() 比较进行类型检查而不是 instanceof,则 obj.getClass() 不是 null 安全的。也许代码模板不够聪明,无法省略 null 检查如果我们使用 instanceof。)
编辑:Dragan 在他的回答中注意到,instanceof 类型检查不是 Eclipse 中的默认设置,所以我编辑了这个问题。但这不会改变任何事情。
另外请不要建议我应该使用 getClass() 或(甚至更好!)不同的 IDE。这不是重点,这不能回答问题。我没有就如何编写equals()实现、是否使用instanceof或getClass()等征求意见。
问题大致是:这是 Eclipse 中的一个小错误吗?如果不是,那为什么它可以作为一项功能呢?
【问题讨论】:
-
不知道,但 instanceof 并不总是被认为是最好的方法。另一种方法是将 obj.getClass() 与 this.getClass() 进行比较,然后您确实需要进行 null 检查
-
我会引用a comment on this answer。
Specifically, in Item 8, he notes that in equals() methods, one instanceof operator serves two purposes - it verifies that the argument is both non-null and of the correct type. "...[S]o you don't need a separate null check." -
IntelliJ Idea 生成一个包含
null检查的equalsimplementation,但使用的是getClass():if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; /*...*/ -
使用 Eclipse Luna。空检查后生成的代码
getClass() != obj.getClass()。 -
Any reason to prefer getClass() over instanceof when generating .equals() 很好地介绍了是否使用
instanceof或getClass()。 Josh Bloch 喜欢使用instanceof;他的论点可以从this (old) interview找到。
标签: java eclipse-jdt