Java——Object

Object

Java的最高层的一个根目录,所有的类都会继承该类,换句话说Object类是所有的类的父类。

 各种本地方法和final关键字标记的方法

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

待续

posted @ 2019-12-20 03:08  子春十一  阅读(577)  评论(0)    收藏  举报