1 类注释

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.

Object类是类层次结构的根,是每一个类的父类。所有的对象(包括数组)都是实现了object类的方法。

2 outline(大纲)

outline中图标的含义可以看博客http://blog.csdn.net/frankarmstrong/article/details/61520279

这里有7个native方法:registerNatives()、getClass()、hashCode()、clone()、notify()、notifyAll()、wait(long)

什么是native方法?官方给的说明是"A native method is a Java method whose implementation is provided by non-java code."

简单的说,native表示该方法的实现java本身并没有完成,而是有c/c++来完成,放在.dll动态库文件中。

这里我们不关注本地方法的具体,我们可以看看其注释和声明,知道这些方法是干什么的。

(1)registerNatives()

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

该方法源码中并没有任何注释说明,而且在静态块中调用了方法。首先明确在类初始化的时候,这个方法被调用执行了。

至于该方法的做用,请看native方法的c代码实现:

这里是相关的C代码(来自OpenJDK6):

static JNINativeMethod methods[] = {

  {“hashCode”, “()I”, (void *)&JVM_IHashCode},

  {“wait”, “(J)V”, (void *)&JVM_MonitorWait},

  {“notify”, “()V”, (void *)&JVM_MonitorNotify},

  {“notifyAll”, “()V”, (void *)&JVM_MonitorNotifyAll},

  {“clone”, “()Ljava/lang/Object;”, (void *)&JVM_Clone},

};

JNIEXPORT void JNICALL

Java_java_lang_Object_registerNatives(JNIEnv *env, jclass cls)
{
  (*env)->RegisterNatives(env, cls,methods, sizeof(methods)/sizeof(methods[]));
}

详细的说:通常情况下,为了使JVM发现您的本机功能,他们被一定的方式命名。例如,对于java.lang.Object.registerNatives,对应的C函数命名为Java_java_lang_Object_registerNatives。通过使用registerNatives(或者更确切地说,JNI函数RegisterNatives),您可以命名任何你想要你的C函数。(来自:https://www.linuxidc.com/Linux/2015-06/118676.htm)

简单的说:就是对几个本地方法进行注册(也就是初始化java方法映射到C的方法)。

细心的读者可能发现这里为什么没有getClass()方法的注册?因为它不需要被注册,它有一个Java_java_lang_Object_getClass的“标准”名称。

(2)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.
*
* <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>
*
* @return The {@code Class} object that represents the runtime
* class of this object.
* @jls 15.8.2 Class Literals
*/
public final native Class<?> getClass();

返回Object的运行时class对象,返回的对象是被静态同步方法锁定的对象(这意味着,该类的所有对象中,同时只有一个对象可以获得锁)。而且实际上返回的class对象是多态的,可以是调用者的子类(注释中Number的例子解释了这一内容)。

(3)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
*/
public native int hashCode();

hashCode()也是一个native方法,该方法返回调用对象的hash码。hashCode必须满足以下协议:

  • 在一个Java应用中,对同一个对象多次调用hashCode()方法,必须返回相同的值。在对象被修改时,不提供equals方法的比较信息。(我的理解:不可以将hashCode值作为equals方法相等的充要条件,同一对象hashCode值肯定相等,不同对象hashCode值不一定不相等)
  • 如果两个对象通过equals方法相等,那么两个对象的hashCode返回值必须要相等。
  • 如果两个对象通过equals方法不相等,两个对象的hashCode返回值不一定不相等。但是程序员应该知道,不相等的对象若返回不想等的hash值,有助于提高hash表的性能。

(4)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:
* <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
*/
public boolean equals(Object obj) {
return (this == obj);
}

判断两个对象是不是相等。该方法遵循如下性质:

  • 自反性:对于任意非空引用x,则x.equals(x)返回true。
  • 对称性:对于任意非空引用x、y,若x.equals(y)返回true,则y.equals(x)返回true。
  • 传递性:对于任意非空引用x、y、z,若x.equals(y)返回true且y.equals(z)返回true,则x.equals(z)返回true。
  • 对于任何非空引用值x和y,多次调用x.equals(y)始终返回true或者始终返回false,没有提供任何信息进行相等比较的对象被修改。
  • 对于任意非空引用x,则x.equals(null)返回false。

重写equals方法必须重写hashCode方法来保证对任意两个对象equals返回值true时,他们的hashCode返回值必须相等。

请注意源码中的实现是“==”号,必要时请重写该方法!

(5)clone()

  /**
* Creates and returns a copy of this object. The precise meaning
* of "copy" may depend on the class of the object. The general
* intent is that, for any object {@code x}, the expression:
* <blockquote>
* <pre>
* x.clone() != x</pre></blockquote>
* will be true, and that the expression:
* <blockquote>
* <pre>
* x.clone().getClass() == x.getClass()</pre></blockquote>
* will be {@code true}, but these are not absolute requirements.
* While it is typically the case that:
* <blockquote>
* <pre>
* x.clone().equals(x)</pre></blockquote>
* will be {@code true}, this is not an absolute requirement.
* <p>
* By convention, the returned object should be obtained by calling
* {@code super.clone}. If a class and all of its superclasses (except
* {@code Object}) obey this convention, it will be the case that
* {@code x.clone().getClass() == x.getClass()}.
* <p>
* By convention, the object returned by this method should be independent
* of this object (which is being cloned). To achieve this independence,
* it may be necessary to modify one or more fields of the object returned
* by {@code super.clone} before returning it. Typically, this means
* copying any mutable objects that comprise the internal "deep structure"
* of the object being cloned and replacing the references to these
* objects with references to the copies. If a class contains only
* primitive fields or references to immutable objects, then it is usually
* the case that no fields in the object returned by {@code super.clone}
* need to be modified.
* <p>
* The method {@code clone} for class {@code Object} performs a
* specific cloning operation. First, if the class of this object does
* not implement the interface {@code Cloneable}, then a
* {@code CloneNotSupportedException} is thrown. Note that all arrays
* are considered to implement the interface {@code Cloneable} and that
* the return type of the {@code clone} method of an array type {@code T[]}
* is {@code T[]} where T is any reference or primitive type.
* Otherwise, this method creates a new instance of the class of this
* object and initializes all its fields with exactly the contents of
* the corresponding fields of this object, as if by assignment; the
* contents of the fields are not themselves cloned. Thus, this method
* performs a "shallow copy" of this object, not a "deep copy" operation.
* <p>
* The class {@code Object} does not itself implement the interface
* {@code Cloneable}, so calling the {@code clone} method on an object
* whose class is {@code Object} will result in throwing an
* exception at run time.
*
* @return a clone of this instance.
* @throws CloneNotSupportedException if the object's class does not
* support the {@code Cloneable} interface. Subclasses
* that override the {@code clone} method can also
* throw this exception to indicate that an instance cannot
* be cloned.
* @see java.lang.Cloneable
*/
protected native Object clone() throws CloneNotSupportedException;

创建和返回一个对象的复制。注意以下几点:

x.clone() != x  是true

一个对象可以被克隆的前提是该对象代表的类实现了Cloneable接口,否者会抛出一个CloneNotSupportedException异常。

调用clone方法时,分配的内存和源对象(即调用clone方法的对象)相同,然后再使用原对象中对应的各个域,填充新对象的域, 填充完成之后,clone方法返回,一个新的相同的对象被创建,同样可以把这个新对象的引用发布到外部。

克隆是浅复制。(详情:http://www.importnew.com/22035.html)

思考:如何进行深拷贝?

(6)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());
}

返回一个表示该对象的字符串,默认实现是:类名@Integer.toHexString(hashCode())

建议子类重写该方法。

(6)notify()、notifyAll()、wait()、wait(long)、wait(long,int)

这几个方法是多线程编程里面常用的方法,这里不多解释。

(7)finalize()

  /**
* Called by the garbage collector on an object when garbage collection
* determines that there are no more references to the object.
* A subclass overrides the {@code finalize} method to dispose of
* system resources or to perform other cleanup.
* <p>
* The general contract of {@code finalize} is that it is invoked
* if and when the Java&trade; virtual
* machine has determined that there is no longer any
* means by which this object can be accessed by any thread that has
* not yet died, except as a result of an action taken by the
* finalization of some other object or class which is ready to be
* finalized. The {@code finalize} method may take any action, including
* making this object available again to other threads; the usual purpose
* of {@code finalize}, however, is to perform cleanup actions before
* the object is irrevocably discarded. For example, the finalize method
* for an object that represents an input/output connection might perform
* explicit I/O transactions to break the connection before the object is
* permanently discarded.
* <p>
* The {@code finalize} method of class {@code Object} performs no
* special action; it simply returns normally. Subclasses of
* {@code Object} may override this definition.
* <p>
* The Java programming language does not guarantee which thread will
* invoke the {@code finalize} method for any given object. It is
* guaranteed, however, that the thread that invokes finalize will not
* be holding any user-visible synchronization locks when finalize is
* invoked. If an uncaught exception is thrown by the finalize method,
* the exception is ignored and finalization of that object terminates.
* <p>
* After the {@code finalize} method has been invoked for an object, no
* further action is taken until the Java virtual machine has again
* determined that there is no longer any means by which this object can
* be accessed by any thread that has not yet died, including possible
* actions by other objects or classes which are ready to be finalized,
* at which point the object may be discarded.
* <p>
* The {@code finalize} method is never invoked more than once by a Java
* virtual machine for any given object.
* <p>
* Any exception thrown by the {@code finalize} method causes
* the finalization of this object to be halted, but is otherwise
* ignored.
*
* @throws Throwable the {@code Exception} raised by this method
* @see java.lang.ref.WeakReference
* @see java.lang.ref.PhantomReference
* @jls 12.6 Finalization of Class Instances
*/
protected void finalize() throws Throwable { }

这是一个被垃圾收集器调用的方法,当一个对象没有被其他引用指向时,垃圾回收器会清理该对象,在回收该对象之前会调用finalize方法。子类一般会重写该方法做一些系统资源清理工作。一个对象只会被调用一次finalize方法。如果finalize方法抛出异常,这个对象的终结将会停止。

java源码阅读Object的更多相关文章

  1. Java源码阅读的真实体会(一种学习思路)

    Java源码阅读的真实体会(一种学习思路) 刚才在论坛不经意间,看到有关源码阅读的帖子.回想自己前几年,阅读源码那种兴奋和成就感(1),不禁又有一种激动. 源码阅读,我觉得最核心有三点:技术基础+强烈 ...

  2. Java源码阅读的真实体会(一种学习思路)【转】

    Java源码阅读的真实体会(一种学习思路)   刚才在论坛不经意间,看到有关源码阅读的帖子.回想自己前几年,阅读源码那种兴奋和成就感(1),不禁又有一种激动. 源码阅读,我觉得最核心有三点:技术基础+ ...

  3. java源码阅读Hashtable

    1类签名与注释 public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, C ...

  4. Java源码阅读Stack

    Stack(栈)实现了一个后进先出(LIFO)的数据结构.该类继承了Vector类,是通过调用父类Vector的方法实现基本操作的. Stack共有以下五个操作: put:将元素压入栈顶. pop:弹 ...

  5. 如何阅读Java源码 阅读java的真实体会

    刚才在论坛不经意间,看到有关源码阅读的帖子.回想自己前几年,阅读源码那种兴奋和成就感(1),不禁又有一种激动. 源码阅读,我觉得最核心有三点:技术基础+强烈的求知欲+耐心.   说到技术基础,我打个比 ...

  6. [收藏] Java源码阅读的真实体会

    收藏自http://www.iteye.com/topic/1113732 刚才在论坛不经意间,看到有关源码阅读的帖子.回想自己前几年,阅读源码那种兴奋和成就感(1),不禁又有一种激动. 源码阅读,我 ...

  7. Java源码之Object

    本文出自:http://blog.csdn.net/dt235201314/article/details/78318399 一丶概述 JAVA中所有的类都继承自Object类,就从Object作为源 ...

  8. java源码阅读ArrayBlockingQueue

    1类签名与简介 public class ArrayBlockingQueue<E> extends AbstractQueue<E> implements BlockingQ ...

  9. Java源码阅读ArrayList

    1简介 public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAc ...

随机推荐

  1. 如何让spring源码正常的部署在idea中

    我在这里把我从GitHub下载的源码成功编译之后的文件放在了我的百度网盘上大家可以直接下载,也可以按如下步骤自己编译部署到idea中, 下载的地址是:http://pan.baidu.com/s/1d ...

  2. 笔记本电脑上面安装linux网络配置以及ping通问题

    ping不同,XShell连接不上linux: 360全部关闭,即可. 具体参考: http://blog.csdn.net/xiezhaoxuan/article/details/52673236 ...

  3. 《vue.js实战》练习---数字输入框组件

    html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...

  4. BestCoder Round #39 解题报告

    现场只做出前三题w 不过不管怎样这既是第一次认真打BC 又是第一次体验用在线编译器调代码 订正最后一题花了今天一整个下午(呜呜 收获还是比较大的^_^ Delete wld有n个数(a1,a2,... ...

  5. 阶段性总结⓵触摸事件&手势识别⓶Quartz2D绘图⓷CALayer图层⓸CAAnimation⓹UIDynamic UI动力学⓺KVC&KVO

    知识点复习   1. 触摸事件&手势识别   1> 4个触摸事件,针对视图的 2> 6个手势识别(除了用代码添加,也可以用Storyboard添加)   附加在某一个特定视图上的, ...

  6. JHDU 2601 An easy problem (数学 )

    title: An easy problem 数学 杭电2601 tags: [数学] 题目链接 Problem Description When Teddy was a child , he was ...

  7. bzoj 1601 最小生成树

    原题传送门http://www.lydsy.com/JudgeOnline/problem.php?id=1601 最小生成树的比较水的题,我们只需要加一个源点,连向所有的点,边权为每个点建水库的代价 ...

  8. hdu 1686 Oulipo (kmp)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1686 题目大意:寻找子链在母链中出现的次数. #include <iostream> #i ...

  9. 手把手教你最简单的开源项目托管GitHub入门教程

    自从google code关闭了下载服务了之后,GitHub作为了目前最好用的免费开源项目托管站点,众多开源项目都托管在github,其中不乏著名的播放器MPC-HC. 不习惯于英文的朋友,难免少不了 ...

  10. [Leetcode Week2]Sort List

    Sort List题解 题目来源:https://leetcode.com/problems/sort-list/description/ Description Sort a linked list ...