java源码阅读Object

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[0]));
}

详细的说:通常情况下,为了使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()

 1     /**
 2      * Returns a hash code value for the object. This method is
 3      * supported for the benefit of hash tables such as those provided by
 4      * {@link java.util.HashMap}.
 5      * <p>
 6      * The general contract of {@code hashCode} is:
 7      * <ul>
 8      * <li>Whenever it is invoked on the same object more than once during
 9      *     an execution of a Java application, the {@code hashCode} method
10      *     must consistently return the same integer, provided no information
11      *     used in {@code equals} comparisons on the object is modified.
12      *     This integer need not remain consistent from one execution of an
13      *     application to another execution of the same application.
14      * <li>If two objects are equal according to the {@code equals(Object)}
15      *     method, then calling the {@code hashCode} method on each of
16      *     the two objects must produce the same integer result.
17      * <li>It is <em>not</em> required that if two objects are unequal
18      *     according to the {@link java.lang.Object#equals(java.lang.Object)}
19      *     method, then calling the {@code hashCode} method on each of the
20      *     two objects must produce distinct integer results.  However, the
21      *     programmer should be aware that producing distinct integer results
22      *     for unequal objects may improve the performance of hash tables.
23      * </ul>
24      * <p>
25      * As much as is reasonably practical, the hashCode method defined by
26      * class {@code Object} does return distinct integers for distinct
27      * objects. (This is typically implemented by converting the internal
28      * address of the object into an integer, but this implementation
29      * technique is not required by the
30      * Java&trade; programming language.)
31      *
32      * @return  a hash code value for this object.
33      * @see     java.lang.Object#equals(java.lang.Object)
34      * @see     java.lang.System#identityHashCode
35      */
36     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)

 1  /**
 2      * Indicates whether some other object is "equal to" this one.
 3      * <p>
 4      * The {@code equals} method implements an equivalence relation
 5      * on non-null object references:
 6      * <ul>
 7      * <li>It is <i>reflexive</i>: for any non-null reference value
 8      *     {@code x}, {@code x.equals(x)} should return
 9      *     {@code true}.
10      * <li>It is <i>symmetric</i>: for any non-null reference values
11      *     {@code x} and {@code y}, {@code x.equals(y)}
12      *     should return {@code true} if and only if
13      *     {@code y.equals(x)} returns {@code true}.
14      * <li>It is <i>transitive</i>: for any non-null reference values
15      *     {@code x}, {@code y}, and {@code z}, if
16      *     {@code x.equals(y)} returns {@code true} and
17      *     {@code y.equals(z)} returns {@code true}, then
18      *     {@code x.equals(z)} should return {@code true}.
19      * <li>It is <i>consistent</i>: for any non-null reference values
20      *     {@code x} and {@code y}, multiple invocations of
21      *     {@code x.equals(y)} consistently return {@code true}
22      *     or consistently return {@code false}, provided no
23      *     information used in {@code equals} comparisons on the
24      *     objects is modified.
25      * <li>For any non-null reference value {@code x},
26      *     {@code x.equals(null)} should return {@code false}.
27      * </ul>
28      * <p>
29      * The {@code equals} method for class {@code Object} implements
30      * the most discriminating possible equivalence relation on objects;
31      * that is, for any non-null reference values {@code x} and
32      * {@code y}, this method returns {@code true} if and only
33      * if {@code x} and {@code y} refer to the same object
34      * ({@code x == y} has the value {@code true}).
35      * <p>
36      * Note that it is generally necessary to override the {@code hashCode}
37      * method whenever this method is overridden, so as to maintain the
38      * general contract for the {@code hashCode} method, which states
39      * that equal objects must have equal hash codes.
40      *
41      * @param   obj   the reference object with which to compare.
42      * @return  {@code true} if this object is the same as the obj
43      *          argument; {@code false} otherwise.
44      * @see     #hashCode()
45      * @see     java.util.HashMap
46      */
47     public boolean equals(Object obj) {
48         return (this == obj);
49     }

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

  • 自反性:对于任意非空引用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()

 1  /**
 2      * Creates and returns a copy of this object.  The precise meaning
 3      * of "copy" may depend on the class of the object. The general
 4      * intent is that, for any object {@code x}, the expression:
 5      * <blockquote>
 6      * <pre>
 7      * x.clone() != x</pre></blockquote>
 8      * will be true, and that the expression:
 9      * <blockquote>
10      * <pre>
11      * x.clone().getClass() == x.getClass()</pre></blockquote>
12      * will be {@code true}, but these are not absolute requirements.
13      * While it is typically the case that:
14      * <blockquote>
15      * <pre>
16      * x.clone().equals(x)</pre></blockquote>
17      * will be {@code true}, this is not an absolute requirement.
18      * <p>
19      * By convention, the returned object should be obtained by calling
20      * {@code super.clone}.  If a class and all of its superclasses (except
21      * {@code Object}) obey this convention, it will be the case that
22      * {@code x.clone().getClass() == x.getClass()}.
23      * <p>
24      * By convention, the object returned by this method should be independent
25      * of this object (which is being cloned).  To achieve this independence,
26      * it may be necessary to modify one or more fields of the object returned
27      * by {@code super.clone} before returning it.  Typically, this means
28      * copying any mutable objects that comprise the internal "deep structure"
29      * of the object being cloned and replacing the references to these
30      * objects with references to the copies.  If a class contains only
31      * primitive fields or references to immutable objects, then it is usually
32      * the case that no fields in the object returned by {@code super.clone}
33      * need to be modified.
34      * <p>
35      * The method {@code clone} for class {@code Object} performs a
36      * specific cloning operation. First, if the class of this object does
37      * not implement the interface {@code Cloneable}, then a
38      * {@code CloneNotSupportedException} is thrown. Note that all arrays
39      * are considered to implement the interface {@code Cloneable} and that
40      * the return type of the {@code clone} method of an array type {@code T[]}
41      * is {@code T[]} where T is any reference or primitive type.
42      * Otherwise, this method creates a new instance of the class of this
43      * object and initializes all its fields with exactly the contents of
44      * the corresponding fields of this object, as if by assignment; the
45      * contents of the fields are not themselves cloned. Thus, this method
46      * performs a "shallow copy" of this object, not a "deep copy" operation.
47      * <p>
48      * The class {@code Object} does not itself implement the interface
49      * {@code Cloneable}, so calling the {@code clone} method on an object
50      * whose class is {@code Object} will result in throwing an
51      * exception at run time.
52      *
53      * @return     a clone of this instance.
54      * @throws  CloneNotSupportedException  if the object's class does not
55      *               support the {@code Cloneable} interface. Subclasses
56      *               that override the {@code clone} method can also
57      *               throw this exception to indicate that an instance cannot
58      *               be cloned.
59      * @see java.lang.Cloneable
60      */
61     protected native Object clone() throws CloneNotSupportedException;

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

x.clone() != x  是true

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

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

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

思考:如何进行深拷贝?

(6)toString()

 1 /**
 2      * Returns a string representation of the object. In general, the
 3      * {@code toString} method returns a string that
 4      * "textually represents" this object. The result should
 5      * be a concise but informative representation that is easy for a
 6      * person to read.
 7      * It is recommended that all subclasses override this method.
 8      * <p>
 9      * The {@code toString} method for class {@code Object}
10      * returns a string consisting of the name of the class of which the
11      * object is an instance, the at-sign character `{@code @}', and
12      * the unsigned hexadecimal representation of the hash code of the
13      * object. In other words, this method returns a string equal to the
14      * value of:
15      * <blockquote>
16      * <pre>
17      * getClass().getName() + '@' + Integer.toHexString(hashCode())
18      * </pre></blockquote>
19      *
20      * @return  a string representation of the object.
21      */
22     public String toString() {
23         return getClass().getName() + "@" + Integer.toHexString(hashCode());
24     }

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

建议子类重写该方法。

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

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

(7)finalize()

 1  /**
 2      * Called by the garbage collector on an object when garbage collection
 3      * determines that there are no more references to the object.
 4      * A subclass overrides the {@code finalize} method to dispose of
 5      * system resources or to perform other cleanup.
 6      * <p>
 7      * The general contract of {@code finalize} is that it is invoked
 8      * if and when the Java&trade; virtual
 9      * machine has determined that there is no longer any
10      * means by which this object can be accessed by any thread that has
11      * not yet died, except as a result of an action taken by the
12      * finalization of some other object or class which is ready to be
13      * finalized. The {@code finalize} method may take any action, including
14      * making this object available again to other threads; the usual purpose
15      * of {@code finalize}, however, is to perform cleanup actions before
16      * the object is irrevocably discarded. For example, the finalize method
17      * for an object that represents an input/output connection might perform
18      * explicit I/O transactions to break the connection before the object is
19      * permanently discarded.
20      * <p>
21      * The {@code finalize} method of class {@code Object} performs no
22      * special action; it simply returns normally. Subclasses of
23      * {@code Object} may override this definition.
24      * <p>
25      * The Java programming language does not guarantee which thread will
26      * invoke the {@code finalize} method for any given object. It is
27      * guaranteed, however, that the thread that invokes finalize will not
28      * be holding any user-visible synchronization locks when finalize is
29      * invoked. If an uncaught exception is thrown by the finalize method,
30      * the exception is ignored and finalization of that object terminates.
31      * <p>
32      * After the {@code finalize} method has been invoked for an object, no
33      * further action is taken until the Java virtual machine has again
34      * determined that there is no longer any means by which this object can
35      * be accessed by any thread that has not yet died, including possible
36      * actions by other objects or classes which are ready to be finalized,
37      * at which point the object may be discarded.
38      * <p>
39      * The {@code finalize} method is never invoked more than once by a Java
40      * virtual machine for any given object.
41      * <p>
42      * Any exception thrown by the {@code finalize} method causes
43      * the finalization of this object to be halted, but is otherwise
44      * ignored.
45      *
46      * @throws Throwable the {@code Exception} raised by this method
47      * @see java.lang.ref.WeakReference
48      * @see java.lang.ref.PhantomReference
49      * @jls 12.6 Finalization of Class Instances
50      */
51     protected void finalize() throws Throwable { }

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

原文地址:https://www.cnblogs.com/ouym/p/8599148.html