Object
类是Java类层次结构的根,每个类都直接或间接地继承自Object
类。它提供了一些最基本的方法,这些方法在所有Java对象中都可用。以下是对Object
类源码的详细分析:
Object
类源码
package java.lang;
public class Object {
static {
registerNatives();
}
private static native void registerNatives();
public final native Class<?> getClass();
public native int hashCode();
public boolean equals(Object obj) {
return (this == obj);
}
protected native Object clone() throws CloneNotSupportedException;
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
public final native void notify();
public final native void notifyAll();
public final native void wait(long timeout) throws InterruptedException;
public final void wait(long timeout, int nanos) throws InterruptedException {
if (timeout < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}
if (nanos > 0) {
timeout++;
}
wait(timeout);
}
public final void wait() throws InterruptedException {
wait(0);
}
protected void finalize() throws Throwable { }
}
方法详解
registerNatives()
private static native void registerNatives();
- 这是一个静态本地方法,用于注册其他本地方法。
- 本地方法由JNI(Java Native Interface)实现。
getClass()
public final native Class<?> getClass();
- 返回对象运行时的类对象
Class
。 - 是一个本地方法,由JVM实现。
hashCode()
public native int hashCode();
- 返回对象的哈希码。
- 本地方法,由JVM实现,通常基于对象的内存地址计算。
equals(Object obj)
public boolean equals(Object obj) {
return (this == obj);
}
- 比较两个对象是否相等。
- 默认实现是比较对象的引用是否相同。
clone()
protected native Object clone() throws CloneNotSupportedException;
- 创建并返回当前对象的一个副本。
- 受保护的本地方法,由JVM实现。
toString()
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
- 返回对象的字符串表示。
- 默认实现返回类的名称和对象的哈希码。
notify()
public final native void notify();
- 唤醒在此对象监视器上等待的单个线程。
- 本地方法,由JVM实现。
notifyAll()
public final native void notifyAll();
- 唤醒在此对象监视器上等待的所有线程。
- 本地方法,由JVM实现。
wait(long timeout)
public final native void wait(long timeout) throws InterruptedException;
- 使当前线程等待,直到另一个线程调用
notify()
或notifyAll()
,或指定的时间已过。 - 本地方法,由JVM实现。
wait(long timeout, int nanos)
public final void wait(long timeout, int nanos) throws InterruptedException {
if (timeout < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}
if (nanos > 0) {
timeout++;
}
wait(timeout);
}
- 使当前线程等待,直到另一个线程调用
notify()
或notifyAll()
,或指定的时间已过。 - 包含检查参数范围和增加超时时间的逻辑。
wait()
public final void wait() throws InterruptedException {
wait(0);
}
- 使当前线程无限期等待,直到另一个线程调用
notify()
或notifyAll()
。 - 调用带有0超时时间的
wait(long timeout)
方法。
finalize()
protected void finalize() throws Throwable { }
- 垃圾回收器在确定不再有对该对象的引用时调用。
- 是一个空实现,可以由子类重写以释放资源。
小结
Object
类提供了基本的对象方法,这些方法在所有Java对象中都是可用的。- 其中许多方法都是本地方法,由JVM实现,以提高性能。
equals()
、hashCode()
、toString()
等方法可以被子类重写,以提供更具体的行为。