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 org.apidesign.bck2brwsr.emul.AnnotationImpl;
29 import java.io.InputStream;
30 import java.lang.annotation.Annotation;
31 import java.lang.reflect.Field;
32 import java.lang.reflect.Method;
33 import java.lang.reflect.TypeVariable;
34 import org.apidesign.bck2brwsr.core.JavaScriptBody;
37 * Instances of the class {@code Class} represent classes and
38 * interfaces in a running Java application. An enum is a kind of
39 * class and an annotation is a kind of interface. Every array also
40 * belongs to a class that is reflected as a {@code Class} object
41 * that is shared by all arrays with the same element type and number
42 * of dimensions. The primitive Java types ({@code boolean},
43 * {@code byte}, {@code char}, {@code short},
44 * {@code int}, {@code long}, {@code float}, and
45 * {@code double}), and the keyword {@code void} are also
46 * represented as {@code Class} objects.
48 * <p> {@code Class} has no public constructor. Instead {@code Class}
49 * objects are constructed automatically by the Java Virtual Machine as classes
50 * are loaded and by calls to the {@code defineClass} method in the class
53 * <p> The following example uses a {@code Class} object to print the
54 * class name of an object:
56 * <p> <blockquote><pre>
57 * void printClassName(Object obj) {
58 * System.out.println("The class of " + obj +
59 * " is " + obj.getClass().getName());
63 * <p> It is also possible to get the {@code Class} object for a named
64 * type (or for void) using a class literal. See Section 15.8.2 of
65 * <cite>The Java™ Language Specification</cite>.
69 * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
72 * @param <T> the type of the class modeled by this {@code Class}
73 * object. For example, the type of {@code String.class} is {@code
74 * Class<String>}. Use {@code Class<?>} if the class being modeled is
78 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
82 class Class<T> implements java.io.Serializable,
83 java.lang.reflect.GenericDeclaration,
84 java.lang.reflect.Type,
85 java.lang.reflect.AnnotatedElement {
86 private static final int ANNOTATION= 0x00002000;
87 private static final int ENUM = 0x00004000;
88 private static final int SYNTHETIC = 0x00001000;
91 * Constructor. Only the Java Virtual Machine creates Class
98 * Converts the object to a string. The string representation is the
99 * string "class" or "interface", followed by a space, and then by the
100 * fully qualified name of the class in the format returned by
101 * {@code getName}. If this {@code Class} object represents a
102 * primitive type, this method returns the name of the primitive type. If
103 * this {@code Class} object represents void this method returns
106 * @return a string representation of this class object.
108 public String toString() {
109 return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
115 * Returns the {@code Class} object associated with the class or
116 * interface with the given string name. Invoking this method is
120 * {@code Class.forName(className, true, currentLoader)}
123 * where {@code currentLoader} denotes the defining class loader of
126 * <p> For example, the following code fragment returns the
127 * runtime {@code Class} descriptor for the class named
128 * {@code java.lang.Thread}:
131 * {@code Class t = Class.forName("java.lang.Thread")}
134 * A call to {@code forName("X")} causes the class named
135 * {@code X} to be initialized.
137 * @param className the fully qualified name of the desired class.
138 * @return the {@code Class} object for the class with the
140 * @exception LinkageError if the linkage fails
141 * @exception ExceptionInInitializerError if the initialization provoked
142 * by this method fails
143 * @exception ClassNotFoundException if the class cannot be located
145 public static Class<?> forName(String className)
146 throws ClassNotFoundException {
147 throw new UnsupportedOperationException();
152 * Creates a new instance of the class represented by this {@code Class}
153 * object. The class is instantiated as if by a {@code new}
154 * expression with an empty argument list. The class is initialized if it
155 * has not already been initialized.
157 * <p>Note that this method propagates any exception thrown by the
158 * nullary constructor, including a checked exception. Use of
159 * this method effectively bypasses the compile-time exception
160 * checking that would otherwise be performed by the compiler.
162 * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
163 * Constructor.newInstance} method avoids this problem by wrapping
164 * any exception thrown by the constructor in a (checked) {@link
165 * java.lang.reflect.InvocationTargetException}.
167 * @return a newly allocated instance of the class represented by this
169 * @exception IllegalAccessException if the class or its nullary
170 * constructor is not accessible.
171 * @exception InstantiationException
172 * if this {@code Class} represents an abstract class,
173 * an interface, an array class, a primitive type, or void;
174 * or if the class has no nullary constructor;
175 * or if the instantiation fails for some other reason.
176 * @exception ExceptionInInitializerError if the initialization
177 * provoked by this method fails.
178 * @exception SecurityException
179 * If a security manager, <i>s</i>, is present and any of the
180 * following conditions is met:
185 * {@link SecurityManager#checkMemberAccess
186 * s.checkMemberAccess(this, Member.PUBLIC)} denies
187 * creation of new instances of this class
189 * <li> the caller's class loader is not the same as or an
190 * ancestor of the class loader for the current class and
191 * invocation of {@link SecurityManager#checkPackageAccess
192 * s.checkPackageAccess()} denies access to the package
198 @JavaScriptBody(args = "self", body =
199 "var inst = self.cnstr();"
200 + "inst.cons__V(inst);"
203 public T newInstance()
204 throws InstantiationException, IllegalAccessException
206 throw new UnsupportedOperationException();
210 * Determines if the specified {@code Object} is assignment-compatible
211 * with the object represented by this {@code Class}. This method is
212 * the dynamic equivalent of the Java language {@code instanceof}
213 * operator. The method returns {@code true} if the specified
214 * {@code Object} argument is non-null and can be cast to the
215 * reference type represented by this {@code Class} object without
216 * raising a {@code ClassCastException.} It returns {@code false}
219 * <p> Specifically, if this {@code Class} object represents a
220 * declared class, this method returns {@code true} if the specified
221 * {@code Object} argument is an instance of the represented class (or
222 * of any of its subclasses); it returns {@code false} otherwise. If
223 * this {@code Class} object represents an array class, this method
224 * returns {@code true} if the specified {@code Object} argument
225 * can be converted to an object of the array class by an identity
226 * conversion or by a widening reference conversion; it returns
227 * {@code false} otherwise. If this {@code Class} object
228 * represents an interface, this method returns {@code true} if the
229 * class or any superclass of the specified {@code Object} argument
230 * implements this interface; it returns {@code false} otherwise. If
231 * this {@code Class} object represents a primitive type, this method
232 * returns {@code false}.
234 * @param obj the object to check
235 * @return true if {@code obj} is an instance of this class
239 public native boolean isInstance(Object obj);
243 * Determines if the class or interface represented by this
244 * {@code Class} object is either the same as, or is a superclass or
245 * superinterface of, the class or interface represented by the specified
246 * {@code Class} parameter. It returns {@code true} if so;
247 * otherwise it returns {@code false}. If this {@code Class}
248 * object represents a primitive type, this method returns
249 * {@code true} if the specified {@code Class} parameter is
250 * exactly this {@code Class} object; otherwise it returns
253 * <p> Specifically, this method tests whether the type represented by the
254 * specified {@code Class} parameter can be converted to the type
255 * represented by this {@code Class} object via an identity conversion
256 * or via a widening reference conversion. See <em>The Java Language
257 * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
259 * @param cls the {@code Class} object to be checked
260 * @return the {@code boolean} value indicating whether objects of the
261 * type {@code cls} can be assigned to objects of this class
262 * @exception NullPointerException if the specified Class parameter is
266 public native boolean isAssignableFrom(Class<?> cls);
270 * Determines if the specified {@code Class} object represents an
273 * @return {@code true} if this object represents an interface;
274 * {@code false} otherwise.
276 public native boolean isInterface();
280 * Determines if this {@code Class} object represents an array class.
282 * @return {@code true} if this object represents an array class;
283 * {@code false} otherwise.
286 public boolean isArray() {
292 * Determines if the specified {@code Class} object represents a
295 * <p> There are nine predefined {@code Class} objects to represent
296 * the eight primitive types and void. These are created by the Java
297 * Virtual Machine, and have the same names as the primitive types that
298 * they represent, namely {@code boolean}, {@code byte},
299 * {@code char}, {@code short}, {@code int},
300 * {@code long}, {@code float}, and {@code double}.
302 * <p> These objects may only be accessed via the following public static
303 * final variables, and are the only {@code Class} objects for which
304 * this method returns {@code true}.
306 * @return true if and only if this class represents a primitive type
308 * @see java.lang.Boolean#TYPE
309 * @see java.lang.Character#TYPE
310 * @see java.lang.Byte#TYPE
311 * @see java.lang.Short#TYPE
312 * @see java.lang.Integer#TYPE
313 * @see java.lang.Long#TYPE
314 * @see java.lang.Float#TYPE
315 * @see java.lang.Double#TYPE
316 * @see java.lang.Void#TYPE
319 public native boolean isPrimitive();
322 * Returns true if this {@code Class} object represents an annotation
323 * type. Note that if this method returns true, {@link #isInterface()}
324 * would also return true, as all annotation types are also interfaces.
326 * @return {@code true} if this class object represents an annotation
327 * type; {@code false} otherwise
330 public boolean isAnnotation() {
331 return (getModifiers() & ANNOTATION) != 0;
335 * Returns {@code true} if this class is a synthetic class;
336 * returns {@code false} otherwise.
337 * @return {@code true} if and only if this class is a synthetic class as
338 * defined by the Java Language Specification.
341 public boolean isSynthetic() {
342 return (getModifiers() & SYNTHETIC) != 0;
346 * Returns the name of the entity (class, interface, array class,
347 * primitive type, or void) represented by this {@code Class} object,
348 * as a {@code String}.
350 * <p> If this class object represents a reference type that is not an
351 * array type then the binary name of the class is returned, as specified
353 * <cite>The Java™ Language Specification</cite>.
355 * <p> If this class object represents a primitive type or void, then the
356 * name returned is a {@code String} equal to the Java language
357 * keyword corresponding to the primitive type or void.
359 * <p> If this class object represents a class of arrays, then the internal
360 * form of the name consists of the name of the element type preceded by
361 * one or more '{@code [}' characters representing the depth of the array
362 * nesting. The encoding of element type names is as follows:
364 * <blockquote><table summary="Element types and encodings">
365 * <tr><th> Element Type <th> <th> Encoding
366 * <tr><td> boolean <td> <td align=center> Z
367 * <tr><td> byte <td> <td align=center> B
368 * <tr><td> char <td> <td align=center> C
369 * <tr><td> class or interface
370 * <td> <td align=center> L<i>classname</i>;
371 * <tr><td> double <td> <td align=center> D
372 * <tr><td> float <td> <td align=center> F
373 * <tr><td> int <td> <td align=center> I
374 * <tr><td> long <td> <td align=center> J
375 * <tr><td> short <td> <td align=center> S
376 * </table></blockquote>
378 * <p> The class or interface name <i>classname</i> is the binary name of
379 * the class specified above.
383 * String.class.getName()
384 * returns "java.lang.String"
385 * byte.class.getName()
387 * (new Object[3]).getClass().getName()
388 * returns "[Ljava.lang.Object;"
389 * (new int[3][4][5][6][7][8][9]).getClass().getName()
391 * </pre></blockquote>
393 * @return the name of the class or interface
394 * represented by this object.
396 public String getName() {
397 return jvmName().replace('/', '.');
400 @JavaScriptBody(args = "self", body = "return self.jvmName;")
401 private native String jvmName();
405 * Returns an array of {@code TypeVariable} objects that represent the
406 * type variables declared by the generic declaration represented by this
407 * {@code GenericDeclaration} object, in declaration order. Returns an
408 * array of length 0 if the underlying generic declaration declares no type
411 * @return an array of {@code TypeVariable} objects that represent
412 * the type variables declared by this generic declaration
413 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
414 * signature of this generic declaration does not conform to
415 * the format specified in
416 * <cite>The Java™ Virtual Machine Specification</cite>
419 public TypeVariable<Class<T>>[] getTypeParameters() {
420 throw new UnsupportedOperationException();
424 * Returns the {@code Class} representing the superclass of the entity
425 * (class, interface, primitive type or void) represented by this
426 * {@code Class}. If this {@code Class} represents either the
427 * {@code Object} class, an interface, a primitive type, or void, then
428 * null is returned. If this object represents an array class then the
429 * {@code Class} object representing the {@code Object} class is
432 * @return the superclass of the class represented by this object.
434 @JavaScriptBody(args = "self", body = "return self.superclass;")
435 public native Class<? super T> getSuperclass();
438 * Returns the Java language modifiers for this class or interface, encoded
439 * in an integer. The modifiers consist of the Java Virtual Machine's
440 * constants for {@code public}, {@code protected},
441 * {@code private}, {@code final}, {@code static},
442 * {@code abstract} and {@code interface}; they should be decoded
443 * using the methods of class {@code Modifier}.
445 * <p> If the underlying class is an array class, then its
446 * {@code public}, {@code private} and {@code protected}
447 * modifiers are the same as those of its component type. If this
448 * {@code Class} represents a primitive type or void, its
449 * {@code public} modifier is always {@code true}, and its
450 * {@code protected} and {@code private} modifiers are always
451 * {@code false}. If this object represents an array class, a
452 * primitive type or void, then its {@code final} modifier is always
453 * {@code true} and its interface modifier is always
454 * {@code false}. The values of its other modifiers are not determined
455 * by this specification.
457 * <p> The modifier encodings are defined in <em>The Java Virtual Machine
458 * Specification</em>, table 4.1.
460 * @return the {@code int} representing the modifiers for this class
461 * @see java.lang.reflect.Modifier
464 public native int getModifiers();
468 * Returns the simple name of the underlying class as given in the
469 * source code. Returns an empty string if the underlying class is
472 * <p>The simple name of an array is the simple name of the
473 * component type with "[]" appended. In particular the simple
474 * name of an array whose component type is anonymous is "[]".
476 * @return the simple name of the underlying class
479 public String getSimpleName() {
481 return getComponentType().getSimpleName()+"[]";
483 String simpleName = getSimpleBinaryName();
484 if (simpleName == null) { // top level class
485 simpleName = getName();
486 return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
488 // According to JLS3 "Binary Compatibility" (13.1) the binary
489 // name of non-package classes (not top level) is the binary
490 // name of the immediately enclosing class followed by a '$' followed by:
491 // (for nested and inner classes): the simple name.
492 // (for local classes): 1 or more digits followed by the simple name.
493 // (for anonymous classes): 1 or more digits.
495 // Since getSimpleBinaryName() will strip the binary name of
496 // the immediatly enclosing class, we are now looking at a
497 // string that matches the regular expression "\$[0-9]*"
498 // followed by a simple name (considering the simple of an
499 // anonymous class to be the empty string).
501 // Remove leading "\$[0-9]*" from the name
502 int length = simpleName.length();
503 if (length < 1 || simpleName.charAt(0) != '$')
504 throw new IllegalStateException("Malformed class name");
506 while (index < length && isAsciiDigit(simpleName.charAt(index)))
508 // Eventually, this is the empty string iff this is an anonymous class
509 return simpleName.substring(index);
513 * Returns the "simple binary name" of the underlying class, i.e.,
514 * the binary name without the leading enclosing class name.
515 * Returns {@code null} if the underlying class is a top level
518 private String getSimpleBinaryName() {
519 Class<?> enclosingClass = null; // XXX getEnclosingClass();
520 if (enclosingClass == null) // top level class
522 // Otherwise, strip the enclosing class' name
524 return getName().substring(enclosingClass.getName().length());
525 } catch (IndexOutOfBoundsException ex) {
526 throw new IllegalStateException("Malformed class name");
531 * Returns an array containing {@code Field} objects reflecting all
532 * the accessible public fields of the class or interface represented by
533 * this {@code Class} object. The elements in the array returned are
534 * not sorted and are not in any particular order. This method returns an
535 * array of length 0 if the class or interface has no accessible public
536 * fields, or if it represents an array class, a primitive type, or void.
538 * <p> Specifically, if this {@code Class} object represents a class,
539 * this method returns the public fields of this class and of all its
540 * superclasses. If this {@code Class} object represents an
541 * interface, this method returns the fields of this interface and of all
542 * its superinterfaces.
544 * <p> The implicit length field for array class is not reflected by this
545 * method. User code should use the methods of class {@code Array} to
548 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
550 * @return the array of {@code Field} objects representing the
552 * @exception SecurityException
553 * If a security manager, <i>s</i>, is present and any of the
554 * following conditions is met:
559 * {@link SecurityManager#checkMemberAccess
560 * s.checkMemberAccess(this, Member.PUBLIC)} denies
561 * access to the fields within this class
563 * <li> the caller's class loader is not the same as or an
564 * ancestor of the class loader for the current class and
565 * invocation of {@link SecurityManager#checkPackageAccess
566 * s.checkPackageAccess()} denies access to the package
573 public Field[] getFields() throws SecurityException {
574 throw new SecurityException();
578 * Returns an array containing {@code Method} objects reflecting all
579 * the public <em>member</em> methods of the class or interface represented
580 * by this {@code Class} object, including those declared by the class
581 * or interface and those inherited from superclasses and
582 * superinterfaces. Array classes return all the (public) member methods
583 * inherited from the {@code Object} class. The elements in the array
584 * returned are not sorted and are not in any particular order. This
585 * method returns an array of length 0 if this {@code Class} object
586 * represents a class or interface that has no public member methods, or if
587 * this {@code Class} object represents a primitive type or void.
589 * <p> The class initialization method {@code <clinit>} is not
590 * included in the returned array. If the class declares multiple public
591 * member methods with the same parameter types, they are all included in
592 * the returned array.
594 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
596 * @return the array of {@code Method} objects representing the
597 * public methods of this class
598 * @exception SecurityException
599 * If a security manager, <i>s</i>, is present and any of the
600 * following conditions is met:
605 * {@link SecurityManager#checkMemberAccess
606 * s.checkMemberAccess(this, Member.PUBLIC)} denies
607 * access to the methods within this class
609 * <li> the caller's class loader is not the same as or an
610 * ancestor of the class loader for the current class and
611 * invocation of {@link SecurityManager#checkPackageAccess
612 * s.checkPackageAccess()} denies access to the package
619 public Method[] getMethods() throws SecurityException {
620 return Method.findMethods(this);
624 * Returns a {@code Field} object that reflects the specified public
625 * member field of the class or interface represented by this
626 * {@code Class} object. The {@code name} parameter is a
627 * {@code String} specifying the simple name of the desired field.
629 * <p> The field to be reflected is determined by the algorithm that
630 * follows. Let C be the class represented by this object:
632 * <LI> If C declares a public field with the name specified, that is the
633 * field to be reflected.</LI>
634 * <LI> If no field was found in step 1 above, this algorithm is applied
635 * recursively to each direct superinterface of C. The direct
636 * superinterfaces are searched in the order they were declared.</LI>
637 * <LI> If no field was found in steps 1 and 2 above, and C has a
638 * superclass S, then this algorithm is invoked recursively upon S.
639 * If C has no superclass, then a {@code NoSuchFieldException}
643 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
645 * @param name the field name
646 * @return the {@code Field} object of this class specified by
648 * @exception NoSuchFieldException if a field with the specified name is
650 * @exception NullPointerException if {@code name} is {@code null}
651 * @exception SecurityException
652 * If a security manager, <i>s</i>, is present and any of the
653 * following conditions is met:
658 * {@link SecurityManager#checkMemberAccess
659 * s.checkMemberAccess(this, Member.PUBLIC)} denies
660 * access to the field
662 * <li> the caller's class loader is not the same as or an
663 * ancestor of the class loader for the current class and
664 * invocation of {@link SecurityManager#checkPackageAccess
665 * s.checkPackageAccess()} denies access to the package
672 public Field getField(String name)
673 throws SecurityException {
674 throw new SecurityException();
679 * Returns a {@code Method} object that reflects the specified public
680 * member method of the class or interface represented by this
681 * {@code Class} object. The {@code name} parameter is a
682 * {@code String} specifying the simple name of the desired method. The
683 * {@code parameterTypes} parameter is an array of {@code Class}
684 * objects that identify the method's formal parameter types, in declared
685 * order. If {@code parameterTypes} is {@code null}, it is
686 * treated as if it were an empty array.
688 * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
689 * {@code NoSuchMethodException} is raised. Otherwise, the method to
690 * be reflected is determined by the algorithm that follows. Let C be the
691 * class represented by this object:
693 * <LI> C is searched for any <I>matching methods</I>. If no matching
694 * method is found, the algorithm of step 1 is invoked recursively on
695 * the superclass of C.</LI>
696 * <LI> If no method was found in step 1 above, the superinterfaces of C
697 * are searched for a matching method. If any such method is found, it
701 * To find a matching method in a class C: If C declares exactly one
702 * public method with the specified name and exactly the same formal
703 * parameter types, that is the method reflected. If more than one such
704 * method is found in C, and one of these methods has a return type that is
705 * more specific than any of the others, that method is reflected;
706 * otherwise one of the methods is chosen arbitrarily.
708 * <p>Note that there may be more than one matching method in a
709 * class because while the Java language forbids a class to
710 * declare multiple methods with the same signature but different
711 * return types, the Java virtual machine does not. This
712 * increased flexibility in the virtual machine can be used to
713 * implement various language features. For example, covariant
714 * returns can be implemented with {@linkplain
715 * java.lang.reflect.Method#isBridge bridge methods}; the bridge
716 * method and the method being overridden would have the same
717 * signature but different return types.
719 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
721 * @param name the name of the method
722 * @param parameterTypes the list of parameters
723 * @return the {@code Method} object that matches the specified
724 * {@code name} and {@code parameterTypes}
725 * @exception NoSuchMethodException if a matching method is not found
726 * or if the name is "<init>"or "<clinit>".
727 * @exception NullPointerException if {@code name} is {@code null}
728 * @exception SecurityException
729 * If a security manager, <i>s</i>, is present and any of the
730 * following conditions is met:
735 * {@link SecurityManager#checkMemberAccess
736 * s.checkMemberAccess(this, Member.PUBLIC)} denies
737 * access to the method
739 * <li> the caller's class loader is not the same as or an
740 * ancestor of the class loader for the current class and
741 * invocation of {@link SecurityManager#checkPackageAccess
742 * s.checkPackageAccess()} denies access to the package
749 public Method getMethod(String name, Class<?>... parameterTypes)
750 throws SecurityException {
751 Method m = Method.findMethod(this, name, parameterTypes);
753 throw new SecurityException(); // XXX: NoSuchMethodException
759 * Character.isDigit answers {@code true} to some non-ascii
760 * digits. This one does not.
762 private static boolean isAsciiDigit(char c) {
763 return '0' <= c && c <= '9';
767 * Returns the canonical name of the underlying class as
768 * defined by the Java Language Specification. Returns null if
769 * the underlying class does not have a canonical name (i.e., if
770 * it is a local or anonymous class or an array whose component
771 * type does not have a canonical name).
772 * @return the canonical name of the underlying class if it exists, and
773 * {@code null} otherwise.
776 public String getCanonicalName() {
778 String canonicalName = getComponentType().getCanonicalName();
779 if (canonicalName != null)
780 return canonicalName + "[]";
784 // if (isLocalOrAnonymousClass())
786 // Class<?> enclosingClass = getEnclosingClass();
787 Class<?> enclosingClass = null;
788 if (enclosingClass == null) { // top level class
791 String enclosingName = enclosingClass.getCanonicalName();
792 if (enclosingName == null)
794 return enclosingName + "." + getSimpleName();
799 * Finds a resource with a given name. The rules for searching resources
800 * associated with a given class are implemented by the defining
801 * {@linkplain ClassLoader class loader} of the class. This method
802 * delegates to this object's class loader. If this object was loaded by
803 * the bootstrap class loader, the method delegates to {@link
804 * ClassLoader#getSystemResourceAsStream}.
806 * <p> Before delegation, an absolute resource name is constructed from the
807 * given resource name using this algorithm:
811 * <li> If the {@code name} begins with a {@code '/'}
812 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
813 * portion of the {@code name} following the {@code '/'}.
815 * <li> Otherwise, the absolute name is of the following form:
818 * {@code modified_package_name/name}
821 * <p> Where the {@code modified_package_name} is the package name of this
822 * object with {@code '/'} substituted for {@code '.'}
823 * (<tt>'\u002e'</tt>).
827 * @param name name of the desired resource
828 * @return A {@link java.io.InputStream} object or {@code null} if
829 * no resource with this name is found
830 * @throws NullPointerException If {@code name} is {@code null}
833 public InputStream getResourceAsStream(String name) {
834 name = resolveName(name);
835 ClassLoader cl = getClassLoader0();
838 return ClassLoader.getSystemResourceAsStream(name);
840 return cl.getResourceAsStream(name);
844 * Finds a resource with a given name. The rules for searching resources
845 * associated with a given class are implemented by the defining
846 * {@linkplain ClassLoader class loader} of the class. This method
847 * delegates to this object's class loader. If this object was loaded by
848 * the bootstrap class loader, the method delegates to {@link
849 * ClassLoader#getSystemResource}.
851 * <p> Before delegation, an absolute resource name is constructed from the
852 * given resource name using this algorithm:
856 * <li> If the {@code name} begins with a {@code '/'}
857 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
858 * portion of the {@code name} following the {@code '/'}.
860 * <li> Otherwise, the absolute name is of the following form:
863 * {@code modified_package_name/name}
866 * <p> Where the {@code modified_package_name} is the package name of this
867 * object with {@code '/'} substituted for {@code '.'}
868 * (<tt>'\u002e'</tt>).
872 * @param name name of the desired resource
873 * @return A {@link java.net.URL} object or {@code null} if no
874 * resource with this name is found
877 public java.net.URL getResource(String name) {
878 name = resolveName(name);
879 ClassLoader cl = getClassLoader0();
882 return ClassLoader.getSystemResource(name);
884 return cl.getResource(name);
889 * Add a package name prefix if the name is not absolute Remove leading "/"
890 * if name is absolute
892 private String resolveName(String name) {
896 if (!name.startsWith("/")) {
898 while (c.isArray()) {
899 c = c.getComponentType();
901 String baseName = c.getName();
902 int index = baseName.lastIndexOf('.');
904 name = baseName.substring(0, index).replace('.', '/')
908 name = name.substring(1);
914 * Returns the class loader for the class. Some implementations may use
915 * null to represent the bootstrap class loader. This method will return
916 * null in such implementations if this class was loaded by the bootstrap
919 * <p> If a security manager is present, and the caller's class loader is
920 * not null and the caller's class loader is not the same as or an ancestor of
921 * the class loader for the class whose class loader is requested, then
922 * this method calls the security manager's {@code checkPermission}
923 * method with a {@code RuntimePermission("getClassLoader")}
924 * permission to ensure it's ok to access the class loader for the class.
927 * represents a primitive type or void, null is returned.
929 * @return the class loader that loaded the class or interface
930 * represented by this object.
931 * @throws SecurityException
932 * if a security manager exists and its
933 * {@code checkPermission} method denies
934 * access to the class loader for the class.
935 * @see java.lang.ClassLoader
936 * @see SecurityManager#checkPermission
937 * @see java.lang.RuntimePermission
939 public ClassLoader getClassLoader() {
940 throw new SecurityException();
943 // Package-private to allow ClassLoader access
944 native ClassLoader getClassLoader0();
947 * Returns the {@code Class} representing the component type of an
948 * array. If this class does not represent an array class this method
951 * @return the {@code Class} representing the component type of this
952 * class if this class is an array
953 * @see java.lang.reflect.Array
956 public Class<?> getComponentType() {
961 * Returns true if and only if this class was declared as an enum in the
964 * @return true if and only if this class was declared as an enum in the
968 public boolean isEnum() {
969 // An enum must both directly extend java.lang.Enum and have
970 // the ENUM bit set; classes for specialized enum constants
971 // don't do the former.
972 return (this.getModifiers() & ENUM) != 0 &&
973 this.getSuperclass() == java.lang.Enum.class;
977 * Casts an object to the class or interface represented
978 * by this {@code Class} object.
980 * @param obj the object to be cast
981 * @return the object after casting, or null if obj is null
983 * @throws ClassCastException if the object is not
984 * null and is not assignable to the type T.
988 public T cast(Object obj) {
989 if (obj != null && !isInstance(obj))
990 throw new ClassCastException(cannotCastMsg(obj));
994 private String cannotCastMsg(Object obj) {
995 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
999 * Casts this {@code Class} object to represent a subclass of the class
1000 * represented by the specified class object. Checks that that the cast
1001 * is valid, and throws a {@code ClassCastException} if it is not. If
1002 * this method succeeds, it always returns a reference to this class object.
1004 * <p>This method is useful when a client needs to "narrow" the type of
1005 * a {@code Class} object to pass it to an API that restricts the
1006 * {@code Class} objects that it is willing to accept. A cast would
1007 * generate a compile-time warning, as the correctness of the cast
1008 * could not be checked at runtime (because generic types are implemented
1011 * @return this {@code Class} object, cast to represent a subclass of
1012 * the specified class object.
1013 * @throws ClassCastException if this {@code Class} object does not
1014 * represent a subclass of the specified class (here "subclass" includes
1015 * the class itself).
1018 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
1019 if (clazz.isAssignableFrom(this))
1020 return (Class<? extends U>) this;
1022 throw new ClassCastException(this.toString());
1025 @JavaScriptBody(args = { "self", "ac" },
1028 + " return self.anno['L' + ac.jvmName + ';'];"
1029 + "} else return null;"
1031 private Object getAnnotationData(Class<?> annotationClass) {
1032 throw new UnsupportedOperationException();
1035 * @throws NullPointerException {@inheritDoc}
1038 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
1039 Object data = getAnnotationData(annotationClass);
1040 return data == null ? null : AnnotationImpl.create(annotationClass, data);
1044 * @throws NullPointerException {@inheritDoc}
1047 @JavaScriptBody(args = { "self", "ac" },
1048 body = "if (self.anno && self.anno['L' + ac.jvmName + ';']) { return true; }"
1049 + "else return false;"
1051 public boolean isAnnotationPresent(
1052 Class<? extends Annotation> annotationClass) {
1053 if (annotationClass == null)
1054 throw new NullPointerException();
1056 return getAnnotation(annotationClass) != null;
1059 @JavaScriptBody(args = "self", body = "return self.anno;")
1060 private Object getAnnotationData() {
1061 throw new UnsupportedOperationException();
1067 public Annotation[] getAnnotations() {
1068 Object data = getAnnotationData();
1069 return data == null ? new Annotation[0] : AnnotationImpl.create(data);
1075 public Annotation[] getDeclaredAnnotations() {
1076 throw new UnsupportedOperationException();
1079 static Class getPrimitiveClass(String type) {
1081 return Object.class;
1084 public boolean desiredAssertionStatus() {