Make sure subclasses of java.lang.Object will have good implementation of toString() method
2 * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
28 import java.lang.reflect.Array;
29 import org.apidesign.bck2brwsr.core.JavaScriptBody;
30 import org.apidesign.bck2brwsr.core.JavaScriptPrototype;
33 * Class {@code Object} is the root of the class hierarchy.
34 * Every class has {@code Object} as a superclass. All objects,
35 * including arrays, implement the methods of this class.
38 * @see java.lang.Class
41 @JavaScriptPrototype(container = "Object.prototype", prototype = "new Object")
44 private static void registerNatives() {
45 boolean assertsOn = false;
46 assert assertsOn = false;
49 } catch (Throwable ex) {
53 @JavaScriptBody(args = {}, body = "var p = vm.java_lang_Object(false);" +
54 "p.toString = Object.prototype.toString__Ljava_lang_String_2;"
56 private static native void registerToString();
63 * Returns the runtime class of this {@code Object}. The returned
64 * {@code Class} object is the object that is locked by {@code
65 * static synchronized} methods of the represented class.
67 * <p><b>The actual result type is {@code Class<? extends |X|>}
68 * where {@code |X|} is the erasure of the static type of the
69 * expression on which {@code getClass} is called.</b> For
70 * example, no cast is required in this code fragment:</p>
73 * {@code Number n = 0; }<br>
74 * {@code Class<? extends Number> c = n.getClass(); }
77 * @return The {@code Class} object that represents the runtime
78 * class of this object.
79 * @see Class Literals, section 15.8.2 of
80 * <cite>The Java™ Language Specification</cite>.
82 @JavaScriptBody(args={}, body="return this.constructor.$class;")
83 public final native Class<?> getClass();
86 * Returns a hash code value for the object. This method is
87 * supported for the benefit of hash tables such as those provided by
88 * {@link java.util.HashMap}.
90 * The general contract of {@code hashCode} is:
92 * <li>Whenever it is invoked on the same object more than once during
93 * an execution of a Java application, the {@code hashCode} method
94 * must consistently return the same integer, provided no information
95 * used in {@code equals} comparisons on the object is modified.
96 * This integer need not remain consistent from one execution of an
97 * application to another execution of the same application.
98 * <li>If two objects are equal according to the {@code equals(Object)}
99 * method, then calling the {@code hashCode} method on each of
100 * the two objects must produce the same integer result.
101 * <li>It is <em>not</em> required that if two objects are unequal
102 * according to the {@link java.lang.Object#equals(java.lang.Object)}
103 * method, then calling the {@code hashCode} method on each of the
104 * two objects must produce distinct integer results. However, the
105 * programmer should be aware that producing distinct integer results
106 * for unequal objects may improve the performance of hash tables.
109 * As much as is reasonably practical, the hashCode method defined by
110 * class {@code Object} does return distinct integers for distinct
111 * objects. (This is typically implemented by converting the internal
112 * address of the object into an integer, but this implementation
113 * technique is not required by the
114 * Java<font size="-2"><sup>TM</sup></font> programming language.)
116 * @return a hash code value for this object.
117 * @see java.lang.Object#equals(java.lang.Object)
118 * @see java.lang.System#identityHashCode
120 @JavaScriptBody(args = {}, body =
121 "if (this.$hashCode) return this.$hashCode;\n"
122 + "var h = this.computeHashCode__I();\n"
123 + "return this.$hashCode = h & h;"
125 public native int hashCode();
127 @JavaScriptBody(args = {}, body = "return Math.random() * Math.pow(2, 32);")
128 native int computeHashCode();
131 * Indicates whether some other object is "equal to" this one.
133 * The {@code equals} method implements an equivalence relation
134 * on non-null object references:
136 * <li>It is <i>reflexive</i>: for any non-null reference value
137 * {@code x}, {@code x.equals(x)} should return
139 * <li>It is <i>symmetric</i>: for any non-null reference values
140 * {@code x} and {@code y}, {@code x.equals(y)}
141 * should return {@code true} if and only if
142 * {@code y.equals(x)} returns {@code true}.
143 * <li>It is <i>transitive</i>: for any non-null reference values
144 * {@code x}, {@code y}, and {@code z}, if
145 * {@code x.equals(y)} returns {@code true} and
146 * {@code y.equals(z)} returns {@code true}, then
147 * {@code x.equals(z)} should return {@code true}.
148 * <li>It is <i>consistent</i>: for any non-null reference values
149 * {@code x} and {@code y}, multiple invocations of
150 * {@code x.equals(y)} consistently return {@code true}
151 * or consistently return {@code false}, provided no
152 * information used in {@code equals} comparisons on the
153 * objects is modified.
154 * <li>For any non-null reference value {@code x},
155 * {@code x.equals(null)} should return {@code false}.
158 * The {@code equals} method for class {@code Object} implements
159 * the most discriminating possible equivalence relation on objects;
160 * that is, for any non-null reference values {@code x} and
161 * {@code y}, this method returns {@code true} if and only
162 * if {@code x} and {@code y} refer to the same object
163 * ({@code x == y} has the value {@code true}).
165 * Note that it is generally necessary to override the {@code hashCode}
166 * method whenever this method is overridden, so as to maintain the
167 * general contract for the {@code hashCode} method, which states
168 * that equal objects must have equal hash codes.
170 * @param obj the reference object with which to compare.
171 * @return {@code true} if this object is the same as the obj
172 * argument; {@code false} otherwise.
174 * @see java.util.HashMap
176 public boolean equals(Object obj) {
177 return (this == obj);
181 * Creates and returns a copy of this object. The precise meaning
182 * of "copy" may depend on the class of the object. The general
183 * intent is that, for any object {@code x}, the expression:
186 * x.clone() != x</pre></blockquote>
187 * will be true, and that the expression:
190 * x.clone().getClass() == x.getClass()</pre></blockquote>
191 * will be {@code true}, but these are not absolute requirements.
192 * While it is typically the case that:
195 * x.clone().equals(x)</pre></blockquote>
196 * will be {@code true}, this is not an absolute requirement.
198 * By convention, the returned object should be obtained by calling
199 * {@code super.clone}. If a class and all of its superclasses (except
200 * {@code Object}) obey this convention, it will be the case that
201 * {@code x.clone().getClass() == x.getClass()}.
203 * By convention, the object returned by this method should be independent
204 * of this object (which is being cloned). To achieve this independence,
205 * it may be necessary to modify one or more fields of the object returned
206 * by {@code super.clone} before returning it. Typically, this means
207 * copying any mutable objects that comprise the internal "deep structure"
208 * of the object being cloned and replacing the references to these
209 * objects with references to the copies. If a class contains only
210 * primitive fields or references to immutable objects, then it is usually
211 * the case that no fields in the object returned by {@code super.clone}
212 * need to be modified.
214 * The method {@code clone} for class {@code Object} performs a
215 * specific cloning operation. First, if the class of this object does
216 * not implement the interface {@code Cloneable}, then a
217 * {@code CloneNotSupportedException} is thrown. Note that all arrays
218 * are considered to implement the interface {@code Cloneable} and that
219 * the return type of the {@code clone} method of an array type {@code T[]}
220 * is {@code T[]} where T is any reference or primitive type.
221 * Otherwise, this method creates a new instance of the class of this
222 * object and initializes all its fields with exactly the contents of
223 * the corresponding fields of this object, as if by assignment; the
224 * contents of the fields are not themselves cloned. Thus, this method
225 * performs a "shallow copy" of this object, not a "deep copy" operation.
227 * The class {@code Object} does not itself implement the interface
228 * {@code Cloneable}, so calling the {@code clone} method on an object
229 * whose class is {@code Object} will result in throwing an
230 * exception at run time.
232 * @return a clone of this instance.
233 * @exception CloneNotSupportedException if the object's class does not
234 * support the {@code Cloneable} interface. Subclasses
235 * that override the {@code clone} method can also
236 * throw this exception to indicate that an instance cannot
238 * @see java.lang.Cloneable
240 protected Object clone() throws CloneNotSupportedException {
241 Object ret = clone(this);
243 throw new CloneNotSupportedException(getClass().getName());
248 @JavaScriptBody(args = "self", body =
249 "\nif (!self.$instOf_java_lang_Cloneable) {"
252 + "\n var clone = self.constructor(true);"
253 + "\n var props = Object.getOwnPropertyNames(self);"
254 + "\n for (var i = 0; i < props.length; i++) {"
255 + "\n var p = props[i];"
256 + "\n clone[p] = self[p];"
261 private static native Object clone(Object self) throws CloneNotSupportedException;
264 * Returns a string representation of the object. In general, the
265 * {@code toString} method returns a string that
266 * "textually represents" this object. The result should
267 * be a concise but informative representation that is easy for a
269 * It is recommended that all subclasses override this method.
271 * The {@code toString} method for class {@code Object}
272 * returns a string consisting of the name of the class of which the
273 * object is an instance, the at-sign character `{@code @}', and
274 * the unsigned hexadecimal representation of the hash code of the
275 * object. In other words, this method returns a string equal to the
279 * getClass().getName() + '@' + Integer.toHexString(hashCode())
280 * </pre></blockquote>
282 * @return a string representation of the object.
284 public String toString() {
285 return getClass().getName() + "@" + Integer.toHexString(hashCode());
289 * Wakes up a single thread that is waiting on this object's
290 * monitor. If any threads are waiting on this object, one of them
291 * is chosen to be awakened. The choice is arbitrary and occurs at
292 * the discretion of the implementation. A thread waits on an object's
293 * monitor by calling one of the {@code wait} methods.
295 * The awakened thread will not be able to proceed until the current
296 * thread relinquishes the lock on this object. The awakened thread will
297 * compete in the usual manner with any other threads that might be
298 * actively competing to synchronize on this object; for example, the
299 * awakened thread enjoys no reliable privilege or disadvantage in being
300 * the next thread to lock this object.
302 * This method should only be called by a thread that is the owner
303 * of this object's monitor. A thread becomes the owner of the
304 * object's monitor in one of three ways:
306 * <li>By executing a synchronized instance method of that object.
307 * <li>By executing the body of a {@code synchronized} statement
308 * that synchronizes on the object.
309 * <li>For objects of type {@code Class,} by executing a
310 * synchronized static method of that class.
313 * Only one thread at a time can own an object's monitor.
315 * @exception IllegalMonitorStateException if the current thread is not
316 * the owner of this object's monitor.
317 * @see java.lang.Object#notifyAll()
318 * @see java.lang.Object#wait()
320 public final native void notify();
323 * Wakes up all threads that are waiting on this object's monitor. A
324 * thread waits on an object's monitor by calling one of the
325 * {@code wait} methods.
327 * The awakened threads will not be able to proceed until the current
328 * thread relinquishes the lock on this object. The awakened threads
329 * will compete in the usual manner with any other threads that might
330 * be actively competing to synchronize on this object; for example,
331 * the awakened threads enjoy no reliable privilege or disadvantage in
332 * being the next thread to lock this object.
334 * This method should only be called by a thread that is the owner
335 * of this object's monitor. See the {@code notify} method for a
336 * description of the ways in which a thread can become the owner of
339 * @exception IllegalMonitorStateException if the current thread is not
340 * the owner of this object's monitor.
341 * @see java.lang.Object#notify()
342 * @see java.lang.Object#wait()
344 public final native void notifyAll();
347 * Causes the current thread to wait until either another thread invokes the
348 * {@link java.lang.Object#notify()} method or the
349 * {@link java.lang.Object#notifyAll()} method for this object, or a
350 * specified amount of time has elapsed.
352 * The current thread must own this object's monitor.
354 * This method causes the current thread (call it <var>T</var>) to
355 * place itself in the wait set for this object and then to relinquish
356 * any and all synchronization claims on this object. Thread <var>T</var>
357 * becomes disabled for thread scheduling purposes and lies dormant
358 * until one of four things happens:
360 * <li>Some other thread invokes the {@code notify} method for this
361 * object and thread <var>T</var> happens to be arbitrarily chosen as
362 * the thread to be awakened.
363 * <li>Some other thread invokes the {@code notifyAll} method for this
365 * <li>Some other thread {@linkplain Thread#interrupt() interrupts}
366 * thread <var>T</var>.
367 * <li>The specified amount of real time has elapsed, more or less. If
368 * {@code timeout} is zero, however, then real time is not taken into
369 * consideration and the thread simply waits until notified.
371 * The thread <var>T</var> is then removed from the wait set for this
372 * object and re-enabled for thread scheduling. It then competes in the
373 * usual manner with other threads for the right to synchronize on the
374 * object; once it has gained control of the object, all its
375 * synchronization claims on the object are restored to the status quo
376 * ante - that is, to the situation as of the time that the {@code wait}
377 * method was invoked. Thread <var>T</var> then returns from the
378 * invocation of the {@code wait} method. Thus, on return from the
379 * {@code wait} method, the synchronization state of the object and of
380 * thread {@code T} is exactly as it was when the {@code wait} method
383 * A thread can also wake up without being notified, interrupted, or
384 * timing out, a so-called <i>spurious wakeup</i>. While this will rarely
385 * occur in practice, applications must guard against it by testing for
386 * the condition that should have caused the thread to be awakened, and
387 * continuing to wait if the condition is not satisfied. In other words,
388 * waits should always occur in loops, like this one:
390 * synchronized (obj) {
391 * while (<condition does not hold>)
393 * ... // Perform action appropriate to condition
396 * (For more information on this topic, see Section 3.2.3 in Doug Lea's
397 * "Concurrent Programming in Java (Second Edition)" (Addison-Wesley,
398 * 2000), or Item 50 in Joshua Bloch's "Effective Java Programming
399 * Language Guide" (Addison-Wesley, 2001).
401 * <p>If the current thread is {@linkplain java.lang.Thread#interrupt()
402 * interrupted} by any thread before or while it is waiting, then an
403 * {@code InterruptedException} is thrown. This exception is not
404 * thrown until the lock status of this object has been restored as
408 * Note that the {@code wait} method, as it places the current thread
409 * into the wait set for this object, unlocks only this object; any
410 * other objects on which the current thread may be synchronized remain
411 * locked while the thread waits.
413 * This method should only be called by a thread that is the owner
414 * of this object's monitor. See the {@code notify} method for a
415 * description of the ways in which a thread can become the owner of
418 * @param timeout the maximum time to wait in milliseconds.
419 * @exception IllegalArgumentException if the value of timeout is
421 * @exception IllegalMonitorStateException if the current thread is not
422 * the owner of the object's monitor.
423 * @exception InterruptedException if any thread interrupted the
424 * current thread before or while the current thread
425 * was waiting for a notification. The <i>interrupted
426 * status</i> of the current thread is cleared when
427 * this exception is thrown.
428 * @see java.lang.Object#notify()
429 * @see java.lang.Object#notifyAll()
431 public final native void wait(long timeout) throws InterruptedException;
434 * Causes the current thread to wait until another thread invokes the
435 * {@link java.lang.Object#notify()} method or the
436 * {@link java.lang.Object#notifyAll()} method for this object, or
437 * some other thread interrupts the current thread, or a certain
438 * amount of real time has elapsed.
440 * This method is similar to the {@code wait} method of one
441 * argument, but it allows finer control over the amount of time to
442 * wait for a notification before giving up. The amount of real time,
443 * measured in nanoseconds, is given by:
446 * 1000000*timeout+nanos</pre></blockquote>
448 * In all other respects, this method does the same thing as the
449 * method {@link #wait(long)} of one argument. In particular,
450 * {@code wait(0, 0)} means the same thing as {@code wait(0)}.
452 * The current thread must own this object's monitor. The thread
453 * releases ownership of this monitor and waits until either of the
454 * following two conditions has occurred:
456 * <li>Another thread notifies threads waiting on this object's monitor
457 * to wake up either through a call to the {@code notify} method
458 * or the {@code notifyAll} method.
459 * <li>The timeout period, specified by {@code timeout}
460 * milliseconds plus {@code nanos} nanoseconds arguments, has
464 * The thread then waits until it can re-obtain ownership of the
465 * monitor and resumes execution.
467 * As in the one argument version, interrupts and spurious wakeups are
468 * possible, and this method should always be used in a loop:
470 * synchronized (obj) {
471 * while (<condition does not hold>)
472 * obj.wait(timeout, nanos);
473 * ... // Perform action appropriate to condition
476 * This method should only be called by a thread that is the owner
477 * of this object's monitor. See the {@code notify} method for a
478 * description of the ways in which a thread can become the owner of
481 * @param timeout the maximum time to wait in milliseconds.
482 * @param nanos additional time, in nanoseconds range
484 * @exception IllegalArgumentException if the value of timeout is
485 * negative or the value of nanos is
486 * not in the range 0-999999.
487 * @exception IllegalMonitorStateException if the current thread is not
488 * the owner of this object's monitor.
489 * @exception InterruptedException if any thread interrupted the
490 * current thread before or while the current thread
491 * was waiting for a notification. The <i>interrupted
492 * status</i> of the current thread is cleared when
493 * this exception is thrown.
495 public final void wait(long timeout, int nanos) throws InterruptedException {
497 throw new IllegalArgumentException("timeout value is negative");
500 if (nanos < 0 || nanos > 999999) {
501 throw new IllegalArgumentException(
502 "nanosecond timeout value out of range");
505 if (nanos >= 500000 || (nanos != 0 && timeout == 0)) {
513 * Causes the current thread to wait until another thread invokes the
514 * {@link java.lang.Object#notify()} method or the
515 * {@link java.lang.Object#notifyAll()} method for this object.
516 * In other words, this method behaves exactly as if it simply
517 * performs the call {@code wait(0)}.
519 * The current thread must own this object's monitor. The thread
520 * releases ownership of this monitor and waits until another thread
521 * notifies threads waiting on this object's monitor to wake up
522 * either through a call to the {@code notify} method or the
523 * {@code notifyAll} method. The thread then waits until it can
524 * re-obtain ownership of the monitor and resumes execution.
526 * As in the one argument version, interrupts and spurious wakeups are
527 * possible, and this method should always be used in a loop:
529 * synchronized (obj) {
530 * while (<condition does not hold>)
532 * ... // Perform action appropriate to condition
535 * This method should only be called by a thread that is the owner
536 * of this object's monitor. See the {@code notify} method for a
537 * description of the ways in which a thread can become the owner of
540 * @exception IllegalMonitorStateException if the current thread is not
541 * the owner of the object's monitor.
542 * @exception InterruptedException if any thread interrupted the
543 * current thread before or while the current thread
544 * was waiting for a notification. The <i>interrupted
545 * status</i> of the current thread is cleared when
546 * this exception is thrown.
547 * @see java.lang.Object#notify()
548 * @see java.lang.Object#notifyAll()
550 public final void wait() throws InterruptedException {
555 * Called by the garbage collector on an object when garbage collection
556 * determines that there are no more references to the object.
557 * A subclass overrides the {@code finalize} method to dispose of
558 * system resources or to perform other cleanup.
560 * The general contract of {@code finalize} is that it is invoked
561 * if and when the Java<font size="-2"><sup>TM</sup></font> virtual
562 * machine has determined that there is no longer any
563 * means by which this object can be accessed by any thread that has
564 * not yet died, except as a result of an action taken by the
565 * finalization of some other object or class which is ready to be
566 * finalized. The {@code finalize} method may take any action, including
567 * making this object available again to other threads; the usual purpose
568 * of {@code finalize}, however, is to perform cleanup actions before
569 * the object is irrevocably discarded. For example, the finalize method
570 * for an object that represents an input/output connection might perform
571 * explicit I/O transactions to break the connection before the object is
572 * permanently discarded.
574 * The {@code finalize} method of class {@code Object} performs no
575 * special action; it simply returns normally. Subclasses of
576 * {@code Object} may override this definition.
578 * The Java programming language does not guarantee which thread will
579 * invoke the {@code finalize} method for any given object. It is
580 * guaranteed, however, that the thread that invokes finalize will not
581 * be holding any user-visible synchronization locks when finalize is
582 * invoked. If an uncaught exception is thrown by the finalize method,
583 * the exception is ignored and finalization of that object terminates.
585 * After the {@code finalize} method has been invoked for an object, no
586 * further action is taken until the Java virtual machine has again
587 * determined that there is no longer any means by which this object can
588 * be accessed by any thread that has not yet died, including possible
589 * actions by other objects or classes which are ready to be finalized,
590 * at which point the object may be discarded.
592 * The {@code finalize} method is never invoked more than once by a Java
593 * virtual machine for any given object.
595 * Any exception thrown by the {@code finalize} method causes
596 * the finalization of this object to be halted, but is otherwise
599 * @throws Throwable the {@code Exception} raised by this method
601 protected void finalize() throws Throwable { }