java - 为什么有些类的方法开始先判断getId() == null?
本文介绍了java - 为什么有些类的方法开始先判断getId() == null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
mybatis3中PerpetualCache中的equals和hashCode方法在第一行先判断getId() == null, 有点不能理解, 为什么要这个判断, 不是不可能为null吗。
代码如下:
@Override
public boolean equals(Object o) {
if (getId() == null) {
throw new CacheException("Cache instances require an ID.");
}
if (this == o) {
return true;
}
if (!(o instanceof Cache)) {
return false;
}
Cache otherCache = (Cache) o;
return getId().equals(otherCache.getId());
}
@Override
public int hashCode() {
if (getId() == null) {
throw new CacheException("Cache instances require an ID.");
}
return getId().hashCode();
}
解决方案
底层框架的方法无法知道应用层的所有使用情况,极可能有些人没有遵守规则,为了保证程序的正确性,做一些防卫性的代码,是有必要的。
这篇关于java - 为什么有些类的方法开始先判断getId() == null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文