Object类是所有Java类的超类,包含9个原生方法,开发者最常使用的有以下关键方法:
方法签名 | 出现频率 | 重要性 | 是否需要重写 |
---|---|---|---|
toString() | ⭐⭐⭐⭐⭐ | 高 | 建议 |
equals(Object obj) | ⭐⭐⭐⭐⭐ | 高 | 必须 |
hashCode() | ⭐⭐⭐⭐ | 高 | 必须 |
getClass() | ⭐⭐⭐ | 中 | 禁止 |
clone() | ⭐⭐ | 中 | 选择性 |
finalize() | ⭐ | 低 | 已过时 |
wait()/notify()/notifyAll() | ⭐⭐⭐ | 高 | 禁止 |
// 默认实现:类名@哈希码十六进制
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
// 正确重写示例
public class Student {
private String name;
private int age;
@Override
public String toString() {
return "Student{name='" + name + "', age=" + age + "}";
}
}
作用:
重写原则:
// equals重写模板
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyClass obj = (MyClass) o;
return Objects.equals(field1, obj.field1) &&
field2 == obj.field2;
}
// hashCode正确实现
@Override
public int hashCode() {
return Objects.hash(field1, field2);
}
equals方法契约:
hashCode契约:
常见误区:
❌ 仅重写equals不重写hashCode
❌ 使用随机数生成hashCode
❌ 在equals中进行类型转换前不检查类型
// 类型检查示例
public void process(Object obj) {
if (obj.getClass() == ArrayList.class) {
// 处理ArrayList特例
}
}
// 获取类元信息
Class<?> clazz = object.getClass();
String className = clazz.getSimpleName();
应用场景:
注意事项:
// 深拷贝实现示例
public class DeepClone implements Cloneable {
private int[] data;
@Override
public DeepClone clone() {
try {
DeepClone cloned = (DeepClone) super.clone();
cloned.data = Arrays.copyOf(this.data, this.data.length);
return cloned;
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
}
克隆类型对比:
类型 | 实现方式 | 特点 |
---|---|---|
浅拷贝 | super.clone() | 复制基本类型字段,引用类型共享 |
深拷贝 | 递归调用引用对象clone() | 完全独立的对象副本 |
序列化拷贝 | 通过ObjectOutputStream | 最彻底的深拷贝方式 |
最佳实践:
✅ 优先使用拷贝构造器:new MyClass(existingInstance)
✅ 复杂对象使用序列化实现深拷贝
✅ 结合Cloneable接口需谨慎
// 标准使用模板
synchronized (lockObject) {
while (conditionNotMet) {
lockObject.wait();
}
// 执行操作
lockObject.notifyAll();
}
方法对比:
方法 | 作用范围 | 使用场景 |
---|---|---|
wait() | 当前对象锁 | 释放锁并进入等待状态 |
notify() | 当前对象锁 | 随机唤醒一个等待线程 |
notifyAll() | 当前对象锁 | 唤醒所有等待线程 |
使用规范:
@Deprecated(since="9")
protected void finalize() throws Throwable {
// 资源清理逻辑
}
淘汰原因:
替代方案:
✅ 使用try-with-resources管理资源
✅ 显式编写close()方法
✅ 使用PhantomReference进行资源清理
// 使用Objects工具类优化空判断
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return Objects.equals(this.name, ((Person)o).name);
}
// 安全调用链
String code = Optional.ofNullable(obj)
.map(MyObject::getDetail)
.map(Detail::getCode)
.orElse("default");
// Apache Commons实现
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(name)
.append(age)
.toHashCode();
}
// Google Guava实现
public int hashCode() {
return Objects.hashCode(name, age);
}
现象:
对象存入HashSet后无法正确检索
解决方案:
案例:
int[] original = {1,2,3};
int[] cloned = original.clone();
cloned[0] = 9; // original数组也被修改!
修复方案:
int[] deepCloned = Arrays.copyOf(original, original.length);
通过合理运用Object类方法,可以显著提升代码的健壮性和可维护性。建议结合具体业务场景选择最合适的实现方式,并使用静态代码分析工具(如SonarQube)进行规则检查。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。