Java源码-Object.java

Object.java(jdk1.7)

package java.lang;

/**
 * Class {@code Object} is the root of the class hierarchy.
 * Every class has {@code Object} as a superclass. All objects,
 * including arrays, implement the methods of this class.
 *
 * @author  unascribed
 * @see     java.lang.Class
 * @since   JDK1.0
 */
public class Object {

    //native修饰,本地方法,作用是注册该类中的本地方法
    private static native void registerNatives();
    static {
        registerNatives();
    }

    /**
     * 本地方法,返回一个对象的运行时类
     */
    public final native Class<?> getClass();

    /**
     *这也是一个本地方法,返回值是对象的一个哈希值。 
     *在编写实现hashCode()方法时,我们需要遵守一些约定:
     * 在应用程序执行期间,如果一个对象用于equals()方法的属性没有被修改的话,那么要保证对该对象多次返回的hashcode值要相等。
    * 如果2个对象通过equals()方法判断的结果为true,那么要保证二者的hashcode值相等。
    * 如果2个对象通过equals()方法判断的结果为false,那么对二者hashcode值是否相等并没有明确要求。如果不相**等,那么能够提升散列表的性能。
     */
    public native int hashCode();

    /**
     * 对象比较,注意String.java中的重写
     */
    public boolean equals(Object obj) {
        return (this == obj);
    }

    /**
     * 对象克隆(浅拷贝),子类需要深克隆,需要实现克隆接口,重写此方法(改为public)
     */
    protected native Object clone() throws CloneNotSupportedException;

    /**
    * tostring方法,经常需要重写
     */
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

    /**
     *唤醒一个在当前对象监视器上等待的线程
     */
    public final native void notify();

    /**
     *唤醒所有在当前对象监视器上等待的线程
     */
    public final native void notifyAll();

    /**
     * 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");
        }
        //四舍五入,nanos为
        if (nanos >= 500000 || (nanos != 0 && timeout == 0)) {
            timeout++;
        }

        wait(timeout);
    }

    /**
    *
     */
    public final void wait() throws InterruptedException {
        wait(0);
    }

    /**
    *垃圾回收器在认为该对象是垃圾对象的时候会调用该方法。子类可以通过重写该方法来达到资源释放的目的。 
    *在方法调用过程中出现的异常会被忽略且方法调用会被终止。 
    *任何对象的该方法只会被调用一次。
    * 不推荐使用:1.jvm不保证被执行;2.加长gc时间

         */
    protected void finalize() throws Throwable { }
}
文章目录
  1. 1. Object.java(jdk1.7)
|