Java-Object类源码解析

Object 定义

Class Object是类层次结构的根。 每个Class都有Object作为超类。 所有对象(包括数组)都实现了这个类的方法。(Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.)

重要方法

1、getClass()

/**
     * Returns the runtime class of this {@code Object}. The returned
     * {@code Class} object is the object that is locked by {@code
     * static synchronized} methods of the represented class.
     */
    public final native Class<?> getClass();

这个方法的作用就是返回某个对象的运行时类,它的返回值是 Class 类型,Class c = obj.getClass();通过对象 c ,我们可以获取该对象的所有成员方法,每个成员方法都是一个 Method 对象;我们也可以获取该对象的所有成员变量,每个成员变量都是一个 Field 对象;同样的,我们也可以获取该对象的构造函数,构造函数则是一个 Constructor 对象。这个方法在反射时会常用到。

2、hashCode()

	/**
     * Returns a hash code value for the object. This method is
     * supported for the benefit of hash tables such as those provided by
     */
    public native int hashCode();
  • hashCode 方法返回散列值。
  • 返回值默认是由对象的地址转换而来的。
  • 同一个对象调用 hashCode 的返回值是相等的。
  • 两个对象的 equals 相等,那 hashCode 一定相等。
  • 两个对象的 equals 不相等,那 hashCode 也不一定相等。

3、equals(Object obj)

	    /**
     * Indicates whether some other object is "equal to" this one.
     * <p>
     * The {@code equals} method implements an equivalence relation
     * on non-null object references:
     */
    public boolean equals(Object obj) {
        return (this == obj);
    }

作用就是比较两个对象是否相等,而比较的依据就是二者的内存地址。除此之外,equals 还遵循以下几个原则:

  • 1、自反性:x.equals(x); // true
  • 2、对称性:x.equals(y) == y.equals(x); // true
  • 3、传递性:if (x.equals(y) && y.equals(z))
    x.equals(z); // true;
  • 4、一致性,只要对象没有被修改,多次调用 equals() 方法结果不变:
    x.equals(y) == x.equals(y); // true
  • 5、非空性,对任何不是 null 的对象 x 调用 x.equals(null) 结果都为 false :
    x.equals(null); // false;

4、clone()

	     /**
     * Creates and returns a copy of this object.  The precise meaning
     * of "copy" may depend on the class of the object. The general
     */
    protected native Object clone() throws CloneNotSupportedException;

clone() 是 Object 的 protected 方法,它不是 public,一个类不显式去重写 clone(),其它类就不能直接去调用该类实例的 clone() 方法。此外,Clone 的注释中还提到比较重要的几点:
• 克隆的对象必须要实现 Cloneable 接口并重写 clone 方法,否则会报 CloneNotSupportedException 异常
• clone() 方法并不是 Cloneable 接口的方法,而是 Object 的一个 protected 方法。Cloneable 接口只是规定,如果一个类没有实现 Cloneable 接口又调用了 clone() 方法,就会抛出 CloneNotSupportedException。
• 浅拷贝:拷贝对象和原始对象的引用类型引用同一个对象。
• 深拷贝:拷贝对象和原始对象的引用类型引用不同对象。

5、toString()

    /**
     * Returns a string representation of the object. In general, the
     * {@code toString} method returns a string that
     * "textually represents" this object. The result should
     * be a concise but informative representation that is easy for a
     * person to read.
     * It is recommended that all subclasses override this method.
     * <p>
     * The {@code toString} method for class {@code Object}
     * returns a string consisting of the name of the class of which the
     * object is an instance, the at-sign character `{@code @}', and
     * the unsigned hexadecimal representation of the hash code of the
     * object. In other words, this method returns a string equal to the
     * value of:
     * <blockquote>
     * <pre>
     * getClass().getName() + '@' + Integer.toHexString(hashCode())
     * </pre></blockquote>
     *
     * @return  a string representation of the object.
     */
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

原生的 toString 方法仅仅返回,对象名 + 它的 hashCode ,但做过开发的都知道,原生的 toString 作用不大。我们需要重写 toString 一般是因为方便调试,需要知道对象的属性值,而不仅仅是 hashCode 。

6、notify()和notifyAll()

   	public final native void notify();
	public final native void notifyAll();

notify 的作用就是随机唤醒在等待队列的某个线程,而 notifyAll 就是唤醒在等待队列的所有线程。

7、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 > 0) {
            timeout++;
        }

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

wait 的作用是让当前线程进入等待状态,同时,wait() 也会让当前线程释放它所持有的锁。直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法,当前线程被唤醒进入就绪状态。
wait(long timeout) (以毫秒为单位)让当前线程处于等待(阻塞)状态,直到其他线程调用此对象的notify() 方法或 notifyAll() 方法,或者超过指定的时间量,当前线程被唤醒进入就绪状态。
wait(long timeout, int nanos) 和 wait(long timeout) 功能一样,唯一的区别是这个可以提供更高的精度。总超时时间(以纳秒为单位)计算为 1000000 *timeout+ nanos。By the way ,wait(0,0) 和 wait(0) 效果一样。

8.finalize

    /**
     * Called by the garbage collector on an object when garbage collection
     * determines that there are no more references to the object.
     */
    protected void finalize() throws Throwable { }

当垃圾收集确定不再有对该对象的引用时,由对象上的垃圾收集器调用。子类覆盖 finalize()方法来处理系统资源或执行其他清理。

每个对象的 finalize() 方法只能被系统执行一次,该方法类似析构函数但不等价。

死亡逃逸,可以在对象被回收之前在 finalize 方法里面重新与其他对象(其他对象不能是即将被回收的对象)建立关联即可,但机会只有一次。

在JDK9及其之后已被废弃使用。原因是最终确定机制本质上是有问题的。最终确定会导致性能问题、死锁和挂起。终结器中的错误可能导致资源泄漏;如果不再需要,则无法取消最终确定;并且在对不同对象的 finalize 方法的调用之间没有指定顺序。此外,无法保证最终确定的时间。 finalize() 方法可能仅在无限期延迟之后才在可终结对象上调用

对象持有非堆资源的类应该提供一种方法来启用这些资源的显式释放,它们可以实现 java.lang.AutoCloseable 。

java.lang.ref.Cleaner 和 java.lang.ref.PhantomReference 提供了更灵活、更有效的方法来在对象变得无法访问时释放资源。

  • 26
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值