最近在读Java源码,然后打算自己动手写一遍,加深对Java的理解。
那么第一次分析,当然要看一个最顶端的类——Object类,一切类的父类。
首先看一下源码:
package java.lang;
public class Object {
private static native void registerNatives();
static {
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 >= 500000 || (nanos != 0 && timeout == 0)) {
timeout++;
}
wait(timeout);
}
public final void wait() throws InterruptedException {
wait(0);
}
protected void finalize() throws Throwable { }
}
1)registerNatives()方法
private static native void registerNatives();
static {
registerNatives();
}
这个方法主要用于注册本地方法,为了JVM发现本机功能。
2)getClass()方法
public final native Class<?> getClass();
获得对象的类名,常见于Java反射机制中
3)hashCode()方法
public native int hashCode();
返回对象的哈希码值。native关键字表明要调用本机操作系统函数
4)equals()方法
public boolean equals(Object obj) {
return (this == obj);
}
一个比较重要的方法,
注意,这个方法比较的是对象的引用而不是内容,所以需要之时要记得重写这个方法。
5)clone()方法
protected native Object clone() throws CloneNotSupportedException;
用于对象的复制。Object的直接接或间接子类通过在重写该方法并直接调用本类的该方法完成对象克隆。默认情况下,这个函数会将内容对应复制一份。
6)toString()方法
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
打印对象信息时常用的方法,但是经常需要重写。
7)notify()方法和notifyAll()方法
public final native void notify();
public final native void notifyAll();
唤醒一个进程和唤醒全部进程。
8)wait()方法
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 >= 500000 || (nanos != 0 && timeout == 0)) {
timeout++;
}
wait(timeout);
}
public final void wait() throws InterruptedException {
wait(0);
}
线程等待方法,还可以指定最长等待的毫秒和纳秒。
9)finalize()方法
protected void finalize() throws Throwable { }
对象回收函数,当用户想在回收前进行一些操作,就需要重写这个函数。