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™ 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™ 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方法拋出異常,這個對象的終結將會停止。