JDK源码解析基础篇--java.lang.Object及其方法约定

这是源码阅读的开端,当然选择从类层次结构的根类–java.lang.Object类开始。
所有类的默认继承Object类(若没有继承其他类),Object类是继承体系的根类,由类直接或间接继承。

Object方法分类

 首先,可以先看一下Object类中有哪些方法。

这里写图片描述

方法很少,很简单对不对!但是这些方法都很重要,可以将这些方法分一下类。它非final方法有:equals,hashCode,toString,clone(访问限制级别:protected)和finalize(访问限制级别:protected)方法。这些方法是可以被子类重写的,且它们都有通用的约定(在第三部分详细解释),任何一个类,它在覆盖这些方法的时候,都有责任遵守这些通用的约定,如果不能做到这一点,其他依赖于这些约定的类就无法结合该类一起正常工作。除这些方法外,其他方法都是final修饰的,是不可以重写的。另外,除equals,toString和finalize方法外,其他方法都是native方法,即:其具体实现是在C(C++)动态库中,通过JNI(Java Native Interface)调用。native关键字要在方法的返回值类型之前。Java语言本身不能对操作系统底层进行访问与操作,但可以通过JNI接口来调用其他语言来实现对底层的访问,JNI已加入Java标准。可以自己编译openJDK,来查看JVM实现。

方法解析

下边直接上源码,来分析Object类中的方法。因为大部分都是native本地方法,所以,方法都很简单。
1. registerNatives

    private static native void registerNatives();
    static {
        registerNatives();
    }

注册native本地方法到JVM。在类初始化时调用static块,调用registerNatives方法。
2. getClass()

public final native Class<?> getClass();

返回运行时的Class对象。这里的返回值,泛型Class<?>需要注意一下。我们看一下它的官方注释,就明白了。

    /**
     * <p><b>The actual result type is {@code Class<? extends |X|>}
     * where {@code |X|} is the erasure of the static type of the
     * expression on which {@code getClass} is called.</b> For
     * example, no cast is required in this code fragment:</p>
     *
     * <p>
     * {@code Number n = 0;                             }<br>
     * {@code Class<? extends Number> c = n.getClass(); }
     * </p>
     */

3. hashCode()

public native int hashCode();

hashCode方法,很重要的方法。关于它的解释,我在另一篇博文详解重写equals()方法就必须重写hashCode()方法的原因中进行了解释。
另外关于HashCode的约定,在后边会统一解释。

    public boolean equals(Object obj) {
        return (this == obj);
    }
equals方法也是很重要的方法,Object中,equals比较的是对象的内存地址(对象堆地址(引用存储的))。

4. toString()

    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

toString方法,Object类中是输出 类名@对象地址。当对象被传递给println、print、字符串操作符+(唯一的操作符重载)以及assert或者被调试器打印出来时,toString方法会被自动调用。

5. clone()

protected native Object clone() throws CloneNotSupportedException;

这实现了浅拷贝。关于浅拷贝和深拷贝:浅拷贝是指当拷贝对象内部中有引用类型的属性变量,在拷贝时候,只拷贝一份引用,拷贝的引用和原引用都指向原来的对象地址。关于clone方法的约定,也在后边详细解释。

6. 与线程有关的wait,notify,notifyAll

   //使持有此对象锁的线程释放锁,进入等待状态(没有权利获得锁),超时唤醒或者被另一个线程调用notify或
   //notifyAll唤醒,使之重新有获得锁的权利
    public final native void wait(long timeout) throws InterruptedException;

   //使持有此对象锁的线程释放锁,进入等待状态(没有权利获得锁),直到被另一个线程调用notify或notifyAll
   //唤醒,使之重新有获得锁的权利
    public final void wait() throws InterruptedException {
        wait(0);
    }

   //使持有此对象锁的线程释放锁,进入等待状态(没有权利获得锁),超时唤醒或者被另一个线程调用notify或
   //notifyAll唤醒,使之重新有获得锁的权利
    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 native void notify();
  //唤醒所有等待中的线程
  public final native void notifyAll();

注意:使用上边方法的前提是:必须拥有对象锁时才可以使用。对象锁是:当理由synchronized进行线程同步时,是利用锁实现的,只有一个线程可以拥有锁。synchronized进行同步时,分对象锁和类锁。对象锁:synchronized(this)当前类对象锁,synchronized(非静态属性)某一属性的对象锁,synchronized修饰方法 对象锁。类锁:synchronized(….class),synchronized(静态属性对象),synchronized 修饰静态方法。修饰静态方法一定会同步,但修饰非静态方法需在单例下才可以。
我们可以分析wait方法和Thread.sleep方法的区别:Thread.sleep不会导致锁行为的改变,如果当前线程是拥有锁的,那么Thread.sleep不会让线程释放锁。如果能够帮助你记忆的话,可以简单认为和锁相关的方法都定义在Object类中,因此调用Thread.sleep是不会影响锁的相关行为。我们可以很容易就推理,上边的方法wait,notify和notifyAll是谁负责调用的,当然是锁对象进行调用的,在拥有锁的线程中调用。

7. finalize

 protected void finalize() throws Throwable { }

子类可重写此方法,以实现非内存资源的清理。此方法在GC回收给对象之前,会自动调用此方法。如果用户显示地调用此方法,代表普通方法调用,与对象的回收销毁无关。
一般不建议使用此方法来进行释放非内存资源,它不同于C++的析构函数,析构函数在对象作用域调用,执行时间点确定。而此方法,是在内存不足,GC发生时进行调用,由于GC是不确定随机的,所以无法确定此方法的执行时间。

方法通用约定

尽管Objcet类是一个具体类,但是设计它主要为了扩展。它所有的非final方法(equals,hashCode,toString,clone,finalize)都有明确的通用约定,下边我们就详细解释一下。

- 覆盖equals时遵循的通用约定

若equals方法覆盖不当时,会产生十分严重的后果。当不覆盖equals方法时,类的每个实例只与它的自身相等。如果类具有自己特有的“逻辑相等”概念,而且超类还没有覆盖equals以实现期望的行为,这时我们就需要覆盖equals方法。这通常属于“值类”,当利用equals方法比较值对象的引用时,希望知道他们在逻辑上是否相等,这需要覆盖equals方法。equals方法覆盖时,需要遵守的通用规定如下,来自JDK1.8 equlas 方法的注释:

 /**
     * Indicates whether some other object is "equal to" this one.
     * <p>
     * The {@code equals} method implements an equivalence relation
     * on non-null object references:
     * <ul>
     * <li>It is <i>reflexive</i>: for any non-null reference value
     *     {@code x}, {@code x.equals(x)} should return
     *     {@code true}.
     * <li>It is <i>symmetric</i>: for any non-null reference values
     *     {@code x} and {@code y}, {@code x.equals(y)}
     *     should return {@code true} if and only if
     *     {@code y.equals(x)} returns {@code true}.
     * <li>It is <i>transitive</i>: for any non-null reference values
     *     {@code x}, {@code y}, and {@code z}, if
     *     {@code x.equals(y)} returns {@code true} and
     *     {@code y.equals(z)} returns {@code true}, then
     *     {@code x.equals(z)} should return {@code true}.
     * <li>It is <i>consistent</i>: for any non-null reference values
     *     {@code x} and {@code y}, multiple invocations of
     *     {@code x.equals(y)} consistently return {@code true}
     *     or consistently return {@code false}, provided no
     *     information used in {@code equals} comparisons on the
     *     objects is modified.
     * <li>For any non-null reference value {@code x},
     *     {@code x.equals(null)} should return {@code false}.
     * </ul>
     * <p>
     * The {@code equals} method for class {@code Object} implements
     * the most discriminating possible equivalence relation on objects;
     * that is, for any non-null reference values {@code x} and
     * {@code y}, this method returns {@code true} if and only
     * if {@code x} and {@code y} refer to the same object
     * ({@code x == y} has the value {@code true}).
     * <p>
     * Note that it is generally necessary to override the {@code hashCode}
     * method whenever this method is overridden, so as to maintain the
     * general contract for the {@code hashCode} method, which states
     * that equal objects must have equal hash codes.
     *
     * @param   obj   the reference object with which to compare.
     * @return  {@code true} if this object is the same as the obj
     *          argument; {@code false} otherwise.
     * @see     #hashCode()
     * @see     java.util.HashMap
     */

总结一下就是需要保证:自反性,对称性,传递性和一致性。必须遵守,有许多类,包括所有的集合类,都依赖传递给他们的对象是否遵守了equals约定。

- hashCode方法约定
在每个覆盖了equals方法的类中,也必须覆盖hashCode方法。如果不这样做的话,就会违反Object.hashCode的通用规定,从而导致该类无法结合所有基于散列的集合一起正常运作。我们可直接看JDK1.8 的hashCode的注释代码:

 /**
     * Returns a hash code value for the object. This method is
     * supported for the benefit of hash tables such as those provided by
     * {@link java.util.HashMap}.
     * <p>
     * The general contract of {@code hashCode} is:
     * <ul>
     * <li>Whenever it is invoked on the same object more than once during
     *     an execution of a Java application, the {@code hashCode} method
     *     must consistently return the same integer, provided no information
     *     used in {@code equals} comparisons on the object is modified.
     *     This integer need not remain consistent from one execution of an
     *     application to another execution of the same application.
     * <li>If two objects are equal according to the {@code equals(Object)}
     *     method, then calling the {@code hashCode} method on each of
     *     the two objects must produce the same integer result.
     * <li>It is <em>not</em> required that if two objects are unequal
     *     according to the {@link java.lang.Object#equals(java.lang.Object)}
     *     method, then calling the {@code hashCode} method on each of the
     *     two objects must produce distinct integer results.  However, the
     *     programmer should be aware that producing distinct integer results
     *     for unequal objects may improve the performance of hash tables.
     * </ul>
     * <p>
     * As much as is reasonably practical, the hashCode method defined by
     * class {@code Object} does return distinct integers for distinct
     * objects. (This is typically implemented by converting the internal
     * address of the object into an integer, but this implementation
     * technique is not required by the
     * Java&trade; programming language.)
     *
     * @return  a hash code value for this object.
     * @see     java.lang.Object#equals(java.lang.Object)
     * @see     java.lang.System#identityHashCode
     */

关于它,我在另一篇博文详解重写equals()方法就必须重写hashCode()方法的原因中进行了解释。这里不再进行分析了。

- 始终覆盖toString

虽然Objcet类中提供了toString方法的一个实现,但是它返回的并不是友好的。toString的通用约定指出,被返回的字符串应该是一个“简洁的、信息丰富并且易于阅读的表达形式”。toString约定建议所有的子类都覆盖这个方法。当对象被传递给println、print、字符串+操作和调试器打印时,toString会被自动调用。

- 谨慎覆盖clone

要使用clone方法,该类需要实现Cloneable接口(标志接口,与Serializable接口类似),它决定了受保护的clone方法实现的行为,如果一个类实现了Cloneable,Object的clone方法就返回该对象的拷贝,否则会抛出CloneNotSupportException异常。而且在重写clone方法时,需用:super.clone();来实现。如果类的所有超类都遵守这个规则,那么调用clone方法最终会调用到Object类的clone方法。也可以实现深拷贝。clone是实现原型设计模式的方法。 重写时,可放大访问限制符权限,不可缩小。

- 避免使用finalize方法

finalize方法通常是不可预测的,会导致不稳定、降低性能、以及可移植性问题。finalize方法的缺点是在于不能保证会被及时地执行,从一个对象变得不可达开始,到它的终结方法被执行,所花费的时间是任意长的,这意味着:注重时间的任务不应该由finalize方法来完成。比如:用finalize方法来关闭已打开的文件,这是严重的错误,因为打开文件描述符是一种很有限的资源,由于JVM进行GC的时间不确定性,所以finalize方法调用也不确定,所以导致大量的文件保留在打开状态。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值