Object类的源码分析

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Object类的源码分析相关的知识,希望对你有一定的参考价值。

JDK 1.8中Object 的源码如下:

  1 public class Object {
  2 
  3     private static native void registerNatives();
  4     static {
  5         registerNatives();
  6     }
  7 
  8     /**
  9      * Returns the runtime class of this {@code Object}. The returned
 10      * {@code Class} object is the object that is locked by {@code
 11      * static synchronized} methods of the represented class.
 12      *
 13      * <p><b>The actual result type is {@code Class<? extends |X|>}
 14      * where {@code |X|} is the erasure of the static type of the
 15      * expression on which {@code getClass} is called.</b> For
 16      * example, no cast is required in this code fragment:</p>
 17      *
 18      * <p>
 19      * {@code Number n = 0;                             }<br>
 20      * {@code Class<? extends Number> c = n.getClass(); }
 21      * </p>
 22      *
 23      * @return The {@code Class} object that represents the runtime
 24      *         class of this object.
 25      * @jls 15.8.2 Class Literals
 26      */
 27     public final native Class<?> getClass();
 28 
 29     /**
 30      * Returns a hash code value for the object. This method is
 31      * supported for the benefit of hash tables such as those provided by
 32      * {@link java.util.HashMap}.
 33      * <p>
 34      * The general contract of {@code hashCode} is:
 35      * <ul>
 36      * <li>Whenever it is invoked on the same object more than once during
 37      *     an execution of a Java application, the {@code hashCode} method
 38      *     must consistently return the same integer, provided no information
 39      *     used in {@code equals} comparisons on the object is modified.
 40      *     This integer need not remain consistent from one execution of an
 41      *     application to another execution of the same application.
 42      * <li>If two objects are equal according to the {@code equals(Object)}
 43      *     method, then calling the {@code hashCode} method on each of
 44      *     the two objects must produce the same integer result.
 45      * <li>It is <em>not</em> required that if two objects are unequal
 46      *     according to the {@link java.lang.Object#equals(java.lang.Object)}
 47      *     method, then calling the {@code hashCode} method on each of the
 48      *     two objects must produce distinct integer results.  However, the
 49      *     programmer should be aware that producing distinct integer results
 50      *     for unequal objects may improve the performance of hash tables.
 51      * </ul>
 52      * <p>
 53      * As much as is reasonably practical, the hashCode method defined by
 54      * class {@code Object} does return distinct integers for distinct
 55      * objects. (This is typically implemented by converting the internal
 56      * address of the object into an integer, but this implementation
 57      * technique is not required by the
 58      * Java&trade; programming language.)
 59      *
 60      * @return  a hash code value for this object.
 61      * @see     java.lang.Object#equals(java.lang.Object)
 62      * @see     java.lang.System#identityHashCode
 63      */
 64     public native int hashCode();
 65 
 66     /**
 67      * Indicates whether some other object is "equal to" this one.
 68      * <p>
 69      * The {@code equals} method implements an equivalence relation
 70      * on non-null object references:
 71      * <ul>
 72      * <li>It is <i>reflexive</i>: for any non-null reference value
 73      *     {@code x}, {@code x.equals(x)} should return
 74      *     {@code true}.
 75      * <li>It is <i>symmetric</i>: for any non-null reference values
 76      *     {@code x} and {@code y}, {@code x.equals(y)}
 77      *     should return {@code true} if and only if
 78      *     {@code y.equals(x)} returns {@code true}.
 79      * <li>It is <i>transitive</i>: for any non-null reference values
 80      *     {@code x}, {@code y}, and {@code z}, if
 81      *     {@code x.equals(y)} returns {@code true} and
 82      *     {@code y.equals(z)} returns {@code true}, then
 83      *     {@code x.equals(z)} should return {@code true}.
 84      * <li>It is <i>consistent</i>: for any non-null reference values
 85      *     {@code x} and {@code y}, multiple invocations of
 86      *     {@code x.equals(y)} consistently return {@code true}
 87      *     or consistently return {@code false}, provided no
 88      *     information used in {@code equals} comparisons on the
 89      *     objects is modified.
 90      * <li>For any non-null reference value {@code x},
 91      *     {@code x.equals(null)} should return {@code false}.
 92      * </ul>
 93      * <p>
 94      * The {@code equals} method for class {@code Object} implements
 95      * the most discriminating possible equivalence relation on objects;
 96      * that is, for any non-null reference values {@code x} and
 97      * {@code y}, this method returns {@code true} if and only
 98      * if {@code x} and {@code y} refer to the same object
 99      * ({@code x == y} has the value {@code true}).
100      * <p>
101      * Note that it is generally necessary to override the {@code hashCode}
102      * method whenever this method is overridden, so as to maintain the
103      * general contract for the {@code hashCode} method, which states
104      * that equal objects must have equal hash codes.
105      *
106      * @param   obj   the reference object with which to compare.
107      * @return  {@code true} if this object is the same as the obj
108      *          argument; {@code false} otherwise.
109      * @see     #hashCode()
110      * @see     java.util.HashMap
111      */
112     public boolean equals(Object obj) {
113         return (this == obj);
114     }
115 
116     /**
117      * Creates and returns a copy of this object.  The precise meaning
118      * of "copy" may depend on the class of the object. The general
119      * intent is that, for any object {@code x}, the expression:
120      * <blockquote>
121      * <pre>
122      * x.clone() != x</pre></blockquote>
123      * will be true, and that the expression:
124      * <blockquote>
125      * <pre>
126      * x.clone().getClass() == x.getClass()</pre></blockquote>
127      * will be {@code true}, but these are not absolute requirements.
128      * While it is typically the case that:
129      * <blockquote>
130      * <pre>
131      * x.clone().equals(x)</pre></blockquote>
132      * will be {@code true}, this is not an absolute requirement.
133      * <p>
134      * By convention, the returned object should be obtained by calling
135      * {@code super.clone}.  If a class and all of its superclasses (except
136      * {@code Object}) obey this convention, it will be the case that
137      * {@code x.clone().getClass() == x.getClass()}.
138      * <p>
139      * By convention, the object returned by this method should be independent
140      * of this object (which is being cloned).  To achieve this independence,
141      * it may be necessary to modify one or more fields of the object returned
142      * by {@code super.clone} before returning it.  Typically, this means
143      * copying any mutable objects that comprise the internal "deep structure"
144      * of the object being cloned and replacing the references to these
145      * objects with references to the copies.  If a class contains only
146      * primitive fields or references to immutable objects, then it is usually
147      * the case that no fields in the object returned by {@code super.clone}
148      * need to be modified.
149      * <p>
150      * The method {@code clone} for class {@code Object} performs a
151      * specific cloning operation. First, if the class of this object does
152      * not implement the interface {@code Cloneable}, then a
153      * {@code CloneNotSupportedException} is thrown. Note that all arrays
154      * are considered to implement the interface {@code Cloneable} and that
155      * the return type of the {@code clone} method of an array type {@code T[]}
156      * is {@code T[]} where T is any reference or primitive type.
157      * Otherwise, this method creates a new instance of the class of this
158      * object and initializes all its fields with exactly the contents of
159      * the corresponding fields of this object, as if by assignment; the
160      * contents of the fields are not themselves cloned. Thus, this method
161      * performs a "shallow copy" of this object, not a "deep copy" operation.
162      * <p>
163      * The class {@code Object} does not itself implement the interface
164      * {@code Cloneable}, so calling the {@code clone} method on an object
165      * whose class is {@code Object} will result in throwing an
166      * exception at run time.
167      *
168      * @return     a clone of this instance.
169      * @throws  CloneNotSupportedException  if the object‘s class does not
170      *               support the {@code Cloneable} interface. Subclasses
171      *               that override the {@code clone} method can also
172      *               throw this exception to indicate that an instance cannot
173      *               be cloned.
174      * @see java.lang.Cloneable
175      */
176     protected native Object clone() throws CloneNotSupportedException;
177 
178     /**
179      * Returns a string representation of the object. In general, the
180      * {@code toString} method returns a string that
181      * "textually represents" this object. The result should
182      * be a concise but informative representation that is easy for a
183      * person to read.
184      * It is recommended that all subclasses override this method.
185      * <p>
186      * The {@code toString} method for class {@code Object}
187      * returns a string consisting of the name of the class of which the
188      * object is an instance, the at-sign character `{@code @}‘, and
189      * the unsigned hexadecimal representation of the hash code of the
190      * object. In other words, this method returns a string equal to the
191      * value of:
192      * <blockquote>
193      * <pre>
194      * getClass().getName() + ‘@‘ + Integer.toHexString(hashCode())
195      * </pre></blockquote>
196      *
197      * @return  a string representation of the object.
198      */
199     public String toString() {
200         return getClass().getName() + "@" + Integer.toHexString(hashCode());
201     }
202 
203     /**
204      * Wakes up a single thread that is waiting on this object‘s
205      * monitor. If any threads are waiting on this object, one of them
206      * is chosen to be awakened. The choice is arbitrary and occurs at
207      * the discretion of the implementation. A thread waits on an object‘s
208      * monitor by calling one of the {@code wait} methods.
209      * <p>
210      * The awakened thread will not be able to proceed until the current
211      * thread relinquishes the lock on this object. The awakened thread will
212      * compete in the usual manner with any other threads that might be
213      * actively competing to synchronize on this object; for example, the
214      * awakened thread enjoys no reliable privilege or disadvantage in being
215      * the next thread to lock this object.
216      * <p>
217      * This method should only be called by a thread that is the owner
218      * of this object‘s monitor. A thread becomes the owner of the
219      * object‘s monitor in one of three ways:
220      * <ul>
221      * <li>By executing a synchronized instance method of that object.
222      * <li>By executing the body of a {@code synchronized} statement
223      *     that synchronizes on the object.
224      * <li>For objects of type {@code Class,} by executing a
225      *     synchronized static method of that class.
226      * </ul>
227      * <p>
228      * Only one thread at a time can own an object‘s monitor.
229      *
230      * @throws  IllegalMonitorStateException  if the current thread is not
231      *               the owner of this object‘s monitor.
232      * @see        java.lang.Object#notifyAll()
233      * @see        java.lang.Object#wait()
234      */
235     public final native void notify();
236 
237     /**
238      * Wakes up all threads that are waiting on this object‘s monitor. A
239      * thread waits on an object‘s monitor by calling one of the
240      * {@code wait} methods.
241      * <p>
242      * The awakened threads will not be able to proceed until the current
243      * thread relinquishes the lock on this object. The awakened threads
244      * will compete in the usual manner with any other threads that might
245      * be actively competing to synchronize on this object; for example,
246      * the awakened threads enjoy no reliable privilege or disadvantage in
247      * being the next thread to lock this object.
248      * <p>
249      * This method should only be called by a thread that is the owner
250      * of this object‘s monitor. See the {@code notify} method for a
251      * description of the ways in which a thread can become the owner of
252      * a monitor.
253      *
254      * @throws  IllegalMonitorStateException  if the current thread is not
255      *               the owner of this object‘s monitor.
256      * @see        java.lang.Object#notify()
257      * @see        java.lang.Object#wait()
258      */
259     public final native void notifyAll();
260 
261     /**
262      * Causes the current thread to wait until either another thread invokes the
263      * {@link java.lang.Object#notify()} method or the
264      * {@link java.lang.Object#notifyAll()} method for this object, or a
265      * specified amount of time has elapsed.
266      * <p>
267      * The current thread must own this object‘s monitor.
268      * <p>
269      * This method causes the current thread (call it <var>T</var>) to
270      * place itself in the wait set for this object and then to relinquish
271      * any and all synchronization claims on this object. Thread <var>T</var>
272      * becomes disabled for thread scheduling purposes and lies dormant
273      * until one of four things happens:
274      * <ul>
275      * <li>Some other thread invokes the {@code notify} method for this
276      * object and thread <var>T</var> happens to be arbitrarily chosen as
277      * the thread to be awakened.
278      * <li>Some other thread invokes the {@code notifyAll} method for this
279      * object.
280      * <li>Some other thread {@linkplain Thread#interrupt() interrupts}
281      * thread <var>T</var>.
282      * <li>The specified amount of real time has elapsed, more or less.  If
283      * {@code timeout} is zero, however, then real time is not taken into
284      * consideration and the thread simply waits until notified.
285      * </ul>
286      * The thread <var>T</var> is then removed from the wait set for this
287      * object and re-enabled for thread scheduling. It then competes in the
288      * usual manner with other threads for the right to synchronize on the
289      * object; once it has gained control of the object, all its
290      * synchronization claims on the object are restored to the status quo
291      * ante - that is, to the situation as of the time that the {@code wait}
292      * method was invoked. Thread <var>T</var> then returns from the
293      * invocation of the {@code wait} method. Thus, on return from the
294      * {@code wait} method, the synchronization state of the object and of
295      * thread {@code T} is exactly as it was when the {@code wait} method
296      * was invoked.
297      * <p>
298      * A thread can also wake up without being notified, interrupted, or
299      * timing out, a so-called <i>spurious wakeup</i>.  While this will rarely
300      * occur in practice, applications must guard against it by testing for
301      * the condition that should have caused the thread to be awakened, and
302      * continuing to wait if the condition is not satisfied.  In other words,
303      * waits should always occur in loops, like this one:
304      * <pre>
305      *     synchronized (obj) {
306      *         while (&lt;condition does not hold&gt;)
307      *             obj.wait(timeout);
308      *         ... // Perform action appropriate to condition
309      *     }
310      * </pre>
311      * (For more information on this topic, see Section 3.2.3 in Doug Lea‘s
312      * "Concurrent Programming in Java (Second Edition)" (Addison-Wesley,
313      * 2000), or Item 50 in Joshua Bloch‘s "Effective Java Programming
314      * Language Guide" (Addison-Wesley, 2001).
315      *
316      * <p>If the current thread is {@linkplain java.lang.Thread#interrupt()
317      * interrupted} by any thread before or while it is waiting, then an
318      * {@code InterruptedException} is thrown.  This exception is not
319      * thrown until the lock status of this object has been restored as
320      * described above.
321      *
322      * <p>
323      * Note that the {@code wait} method, as it places the current thread
324      * into the wait set for this object, unlocks only this object; any
325      * other objects on which the current thread may be synchronized remain
326      * locked while the thread waits.
327      * <p>
328      * This method should only be called by a thread that is the owner
329      * of this object‘s monitor. See the {@code notify} method for a
330      * description of the ways in which a thread can become the owner of
331      * a monitor.
332      *
333      * @param      timeout   the maximum time to wait in milliseconds.
334      * @throws  IllegalArgumentException      if the value of timeout is
335      *               negative.
336      * @throws  IllegalMonitorStateException  if the current thread is not
337      *               the owner of the object‘s monitor.
338      * @throws  InterruptedException if any thread interrupted the
339      *             current thread before or while the current thread
340      *             was waiting for a notification.  The <i>interrupted
341      *             status</i> of the current thread is cleared when
342      *             this exception is thrown.
343      * @see        java.lang.Object#notify()
344      * @see        java.lang.Object#notifyAll()
345      */
346     public final native void wait(long timeout) throws InterruptedException;
347 
348     /**
349      * Causes the current thread to wait until another thread invokes the
350      * {@link java.lang.Object#notify()} method or the
351      * {@link java.lang.Object#notifyAll()} method for this object, or
352      * some other thread interrupts the current thread, or a certain
353      * amount of real time has elapsed.
354      * <p>
355      * This method is similar to the {@code wait} method of one
356      * argument, but it allows finer control over the amount of time to
357      * wait for a notification before giving up. The amount of real time,
358      * measured in nanoseconds, is given by:
359      * <blockquote>
360      * <pre>
361      * 1000000*timeout+nanos</pre></blockquote>
362      * <p>
363      * In all other respects, this method does the same thing as the
364      * method {@link #wait(long)} of one argument. In particular,
365      * {@code wait(0, 0)} means the same thing as {@code wait(0)}.
366      * <p>
367      * The current thread must own this object‘s monitor. The thread
368      * releases ownership of this monitor and waits until either of the
369      * following two conditions has occurred:
370      * <ul>
371      * <li>Another thread notifies threads waiting on this object‘s monitor
372      *     to wake up either through a call to the {@code notify} method
373      *     or the {@code notifyAll} method.
374      * <li>The timeout period, specified by {@code timeout}
375      *     milliseconds plus {@code nanos} nanoseconds arguments, has
376      *     elapsed.
377      * </ul>
378      * <p>
379      * The thread then waits until it can re-obtain ownership of the
380      * monitor and resumes execution.
381      * <p>
382      * As in the one argument version, interrupts and spurious wakeups are
383      * possible, and this method should always be used in a loop:
384      * <pre>
385      *     synchronized (obj) {
386      *         while (&lt;condition does not hold&gt;)
387      *             obj.wait(timeout, nanos);
388      *         ... // Perform action appropriate to condition
389      *     }
390      * </pre>
391      * This method should only be called by a thread that is the owner
392      * of this object‘s monitor. See the {@code notify} method for a
393      * description of the ways in which a thread can become the owner of
394      * a monitor.
395      *
396      * @param      timeout   the maximum time to wait in milliseconds.
397      * @param      nanos      additional time, in nanoseconds range
398      *                       0-999999.
399      * @throws  IllegalArgumentException      if the value of timeout is
400      *                      negative or the value of nanos is
401      *                      not in the range 0-999999.
402      * @throws  IllegalMonitorStateException  if the current thread is not
403      *               the owner of this object‘s monitor.
404      * @throws  InterruptedException if any thread interrupted the
405      *             current thread before or while the current thread
406      *             was waiting for a notification.  The <i>interrupted
407      *             status</i> of the current thread is cleared when
408      *             this exception is thrown.
409      */
410     public final void wait(long timeout, int nanos) throws InterruptedException {
411         if (timeout < 0) {
412             throw new IllegalArgumentException("timeout value is negative");
413         }
414 
415         if (nanos < 0 || nanos > 999999) {
416             throw new IllegalArgumentException(
417                                 "nanosecond timeout value out of range");
418         }
419 
420         if (nanos > 0) {
421             timeout++;
422         }
423 
424         wait(timeout);
425     }
426 
427     /**
428      * Causes the current thread to wait until another thread invokes the
429      * {@link java.lang.Object#notify()} method or the
430      * {@link java.lang.Object#notifyAll()} method for this object.
431      * In other words, this method behaves exactly as if it simply
432      * performs the call {@code wait(0)}.
433      * <p>
434      * The current thread must own this object‘s monitor. The thread
435      * releases ownership of this monitor and waits until another thread
436      * notifies threads waiting on this object‘s monitor to wake up
437      * either through a call to the {@code notify} method or the
438      * {@code notifyAll} method. The thread then waits until it can
439      * re-obtain ownership of the monitor and resumes execution.
440      * <p>
441      * As in the one argument version, interrupts and spurious wakeups are
442      * possible, and this method should always be used in a loop:
443      * <pre>
444      *     synchronized (obj) {
445      *         while (&lt;condition does not hold&gt;)
446      *             obj.wait();
447      *         ... // Perform action appropriate to condition
448      *     }
449      * </pre>
450      * This method should only be called by a thread that is the owner
451      * of this object‘s monitor. See the {@code notify} method for a
452      * description of the ways in which a thread can become the owner of
453      * a monitor.
454      *
455      * @throws  IllegalMonitorStateException  if the current thread is not
456      *               the owner of the object‘s monitor.
457      * @throws  InterruptedException if any thread interrupted the
458      *             current thread before or while the current thread
459      *             was waiting for a notification.  The <i>interrupted
460      *             status</i> of the current thread is cleared when
461      *             this exception is thrown.
462      * @see        java.lang.Object#notify()
463      * @see        java.lang.Object#notifyAll()
464      */
465     public final void wait() throws InterruptedException {
466         wait(0);
467     }
468 
469     /**
470      * Called by the garbage collector on an object when garbage collection
471      * determines that there are no more references to the object.
472      * A subclass overrides the {@code finalize} method to dispose of
473      * system resources or to perform other cleanup.
474      * <p>
475      * The general contract of {@code finalize} is that it is invoked
476      * if and when the Java&trade; virtual
477      * machine has determined that there is no longer any
478      * means by which this object can be accessed by any thread that has
479      * not yet died, except as a result of an action taken by the
480      * finalization of some other object or class which is ready to be
481      * finalized. The {@code finalize} method may take any action, including
482      * making this object available again to other threads; the usual purpose
483      * of {@code finalize}, however, is to perform cleanup actions before
484      * the object is irrevocably discarded. For example, the finalize method
485      * for an object that represents an input/output connection might perform
486      * explicit I/O transactions to break the connection before the object is
487      * permanently discarded.
488      * <p>
489      * The {@code finalize} method of class {@code Object} performs no
490      * special action; it simply returns normally. Subclasses of
491      * {@code Object} may override this definition.
492      * <p>
493      * The Java programming language does not guarantee which thread will
494      * invoke the {@code finalize} method for any given object. It is
495      * guaranteed, however, that the thread that invokes finalize will not
496      * be holding any user-visible synchronization locks when finalize is
497      * invoked. If an uncaught exception is thrown by the finalize method,
498      * the exception is ignored and finalization of that object terminates.
499      * <p>
500      * After the {@code finalize} method has been invoked for an object, no
501      * further action is taken until the Java virtual machine has again
502      * determined that there is no longer any means by which this object can
503      * be accessed by any thread that has not yet died, including possible
504      * actions by other objects or classes which are ready to be finalized,
505      * at which point the object may be discarded.
506      * <p>
507      * The {@code finalize} method is never invoked more than once by a Java
508      * virtual machine for any given object.
509      * <p>
510      * Any exception thrown by the {@code finalize} method causes
511      * the finalization of this object to be halted, but is otherwise
512      * ignored.
513      *
514      * @throws Throwable the {@code Exception} raised by this method
515      * @see java.lang.ref.WeakReference
516      * @see java.lang.ref.PhantomReference
517      * @jls 12.6 Finalization of Class Instances
518      */
519     protected void finalize() throws Throwable { }
520 }

所以Object的所有方法如下:

技术分享

需要注意的是:其中:这些方法是 被 native 关键字修饰的

1 registerNatives();
2 getClass();
3 hashCode();
4 clone();
5 notify();
6 notifyAll();
7 wait(long timeout)

备注下:native 关键字主要是说明,这是java对外的方法定义,是与其他语言(C语言)的沟通

官方的解释如下:

native关键字说明其修饰的方法是一个原生态方法,方法对应的实现不是在当前文件,而是在用其他语言(如C和C++)实现的文件中。Java语言本身不能对操作系统底层进行访问和操作,但是可以通过JNI接口调用其他语言来实现对底层的访问。

    JNI是Java本机接口(Java Native Interface),是一个本机编程接口,它是Java软件开发工具箱(Java Software Development Kit,SDK)的一部分。JNI允许Java代码使用以其他语言编写的代码和代码库。Invocation API(JNI的一部分)可以用来将Java虚拟机(JVM)嵌入到本机应用程序中,从而允许程序员从本机代码内部调用Java代码。

参考文章:http://www.cnblogs.com/huzi007/p/3982026.html

 


以上是关于Object类的源码分析的主要内容,如果未能解决你的问题,请参考以下文章

我的jdk源码:Object 一切类的根本!

jdk源码分析——Object类

yii2 源码分析Behavior类分析

从 JDK 源码角度看 Object

分析JDK源码 | Java Object

java源码分析-String