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.io.InputStream;
29 import java.lang.annotation.Annotation;
30 import java.lang.reflect.Field;
31 import java.lang.reflect.Method;
32 import java.lang.reflect.TypeVariable;
33 import org.apidesign.bck2brwsr.core.JavaScriptBody;
36 * Instances of the class {@code Class} represent classes and
37 * interfaces in a running Java application. An enum is a kind of
38 * class and an annotation is a kind of interface. Every array also
39 * belongs to a class that is reflected as a {@code Class} object
40 * that is shared by all arrays with the same element type and number
41 * of dimensions. The primitive Java types ({@code boolean},
42 * {@code byte}, {@code char}, {@code short},
43 * {@code int}, {@code long}, {@code float}, and
44 * {@code double}), and the keyword {@code void} are also
45 * represented as {@code Class} objects.
47 * <p> {@code Class} has no public constructor. Instead {@code Class}
48 * objects are constructed automatically by the Java Virtual Machine as classes
49 * are loaded and by calls to the {@code defineClass} method in the class
52 * <p> The following example uses a {@code Class} object to print the
53 * class name of an object:
55 * <p> <blockquote><pre>
56 * void printClassName(Object obj) {
57 * System.out.println("The class of " + obj +
58 * " is " + obj.getClass().getName());
62 * <p> It is also possible to get the {@code Class} object for a named
63 * type (or for void) using a class literal. See Section 15.8.2 of
64 * <cite>The Java™ Language Specification</cite>.
68 * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
71 * @param <T> the type of the class modeled by this {@code Class}
72 * object. For example, the type of {@code String.class} is {@code
73 * Class<String>}. Use {@code Class<?>} if the class being modeled is
77 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
81 class Class<T> implements java.io.Serializable,
82 java.lang.reflect.GenericDeclaration,
83 java.lang.reflect.Type,
84 java.lang.reflect.AnnotatedElement {
85 private static final int ANNOTATION= 0x00002000;
86 private static final int ENUM = 0x00004000;
87 private static final int SYNTHETIC = 0x00001000;
90 * Constructor. Only the Java Virtual Machine creates Class
97 * Converts the object to a string. The string representation is the
98 * string "class" or "interface", followed by a space, and then by the
99 * fully qualified name of the class in the format returned by
100 * {@code getName}. If this {@code Class} object represents a
101 * primitive type, this method returns the name of the primitive type. If
102 * this {@code Class} object represents void this method returns
105 * @return a string representation of this class object.
107 public String toString() {
108 return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
114 * Returns the {@code Class} object associated with the class or
115 * interface with the given string name. Invoking this method is
119 * {@code Class.forName(className, true, currentLoader)}
122 * where {@code currentLoader} denotes the defining class loader of
125 * <p> For example, the following code fragment returns the
126 * runtime {@code Class} descriptor for the class named
127 * {@code java.lang.Thread}:
130 * {@code Class t = Class.forName("java.lang.Thread")}
133 * A call to {@code forName("X")} causes the class named
134 * {@code X} to be initialized.
136 * @param className the fully qualified name of the desired class.
137 * @return the {@code Class} object for the class with the
139 * @exception LinkageError if the linkage fails
140 * @exception ExceptionInInitializerError if the initialization provoked
141 * by this method fails
142 * @exception ClassNotFoundException if the class cannot be located
144 public static Class<?> forName(String className)
145 throws ClassNotFoundException {
146 throw new UnsupportedOperationException();
151 * Creates a new instance of the class represented by this {@code Class}
152 * object. The class is instantiated as if by a {@code new}
153 * expression with an empty argument list. The class is initialized if it
154 * has not already been initialized.
156 * <p>Note that this method propagates any exception thrown by the
157 * nullary constructor, including a checked exception. Use of
158 * this method effectively bypasses the compile-time exception
159 * checking that would otherwise be performed by the compiler.
161 * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
162 * Constructor.newInstance} method avoids this problem by wrapping
163 * any exception thrown by the constructor in a (checked) {@link
164 * java.lang.reflect.InvocationTargetException}.
166 * @return a newly allocated instance of the class represented by this
168 * @exception IllegalAccessException if the class or its nullary
169 * constructor is not accessible.
170 * @exception InstantiationException
171 * if this {@code Class} represents an abstract class,
172 * an interface, an array class, a primitive type, or void;
173 * or if the class has no nullary constructor;
174 * or if the instantiation fails for some other reason.
175 * @exception ExceptionInInitializerError if the initialization
176 * provoked by this method fails.
177 * @exception SecurityException
178 * If a security manager, <i>s</i>, is present and any of the
179 * following conditions is met:
184 * {@link SecurityManager#checkMemberAccess
185 * s.checkMemberAccess(this, Member.PUBLIC)} denies
186 * creation of new instances of this class
188 * <li> the caller's class loader is not the same as or an
189 * ancestor of the class loader for the current class and
190 * invocation of {@link SecurityManager#checkPackageAccess
191 * s.checkPackageAccess()} denies access to the package
197 @JavaScriptBody(args = "self", body =
198 "var inst = self.cnstr();"
199 + "inst.cons__V(inst);"
202 public T newInstance()
203 throws InstantiationException, IllegalAccessException
205 throw new UnsupportedOperationException();
209 * Determines if the specified {@code Object} is assignment-compatible
210 * with the object represented by this {@code Class}. This method is
211 * the dynamic equivalent of the Java language {@code instanceof}
212 * operator. The method returns {@code true} if the specified
213 * {@code Object} argument is non-null and can be cast to the
214 * reference type represented by this {@code Class} object without
215 * raising a {@code ClassCastException.} It returns {@code false}
218 * <p> Specifically, if this {@code Class} object represents a
219 * declared class, this method returns {@code true} if the specified
220 * {@code Object} argument is an instance of the represented class (or
221 * of any of its subclasses); it returns {@code false} otherwise. If
222 * this {@code Class} object represents an array class, this method
223 * returns {@code true} if the specified {@code Object} argument
224 * can be converted to an object of the array class by an identity
225 * conversion or by a widening reference conversion; it returns
226 * {@code false} otherwise. If this {@code Class} object
227 * represents an interface, this method returns {@code true} if the
228 * class or any superclass of the specified {@code Object} argument
229 * implements this interface; it returns {@code false} otherwise. If
230 * this {@code Class} object represents a primitive type, this method
231 * returns {@code false}.
233 * @param obj the object to check
234 * @return true if {@code obj} is an instance of this class
238 public native boolean isInstance(Object obj);
242 * Determines if the class or interface represented by this
243 * {@code Class} object is either the same as, or is a superclass or
244 * superinterface of, the class or interface represented by the specified
245 * {@code Class} parameter. It returns {@code true} if so;
246 * otherwise it returns {@code false}. If this {@code Class}
247 * object represents a primitive type, this method returns
248 * {@code true} if the specified {@code Class} parameter is
249 * exactly this {@code Class} object; otherwise it returns
252 * <p> Specifically, this method tests whether the type represented by the
253 * specified {@code Class} parameter can be converted to the type
254 * represented by this {@code Class} object via an identity conversion
255 * or via a widening reference conversion. See <em>The Java Language
256 * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
258 * @param cls the {@code Class} object to be checked
259 * @return the {@code boolean} value indicating whether objects of the
260 * type {@code cls} can be assigned to objects of this class
261 * @exception NullPointerException if the specified Class parameter is
265 public native boolean isAssignableFrom(Class<?> cls);
269 * Determines if the specified {@code Class} object represents an
272 * @return {@code true} if this object represents an interface;
273 * {@code false} otherwise.
275 public native boolean isInterface();
279 * Determines if this {@code Class} object represents an array class.
281 * @return {@code true} if this object represents an array class;
282 * {@code false} otherwise.
285 public boolean isArray() {
291 * Determines if the specified {@code Class} object represents a
294 * <p> There are nine predefined {@code Class} objects to represent
295 * the eight primitive types and void. These are created by the Java
296 * Virtual Machine, and have the same names as the primitive types that
297 * they represent, namely {@code boolean}, {@code byte},
298 * {@code char}, {@code short}, {@code int},
299 * {@code long}, {@code float}, and {@code double}.
301 * <p> These objects may only be accessed via the following public static
302 * final variables, and are the only {@code Class} objects for which
303 * this method returns {@code true}.
305 * @return true if and only if this class represents a primitive type
307 * @see java.lang.Boolean#TYPE
308 * @see java.lang.Character#TYPE
309 * @see java.lang.Byte#TYPE
310 * @see java.lang.Short#TYPE
311 * @see java.lang.Integer#TYPE
312 * @see java.lang.Long#TYPE
313 * @see java.lang.Float#TYPE
314 * @see java.lang.Double#TYPE
315 * @see java.lang.Void#TYPE
318 public native boolean isPrimitive();
321 * Returns true if this {@code Class} object represents an annotation
322 * type. Note that if this method returns true, {@link #isInterface()}
323 * would also return true, as all annotation types are also interfaces.
325 * @return {@code true} if this class object represents an annotation
326 * type; {@code false} otherwise
329 public boolean isAnnotation() {
330 return (getModifiers() & ANNOTATION) != 0;
334 * Returns {@code true} if this class is a synthetic class;
335 * returns {@code false} otherwise.
336 * @return {@code true} if and only if this class is a synthetic class as
337 * defined by the Java Language Specification.
340 public boolean isSynthetic() {
341 return (getModifiers() & SYNTHETIC) != 0;
345 * Returns the name of the entity (class, interface, array class,
346 * primitive type, or void) represented by this {@code Class} object,
347 * as a {@code String}.
349 * <p> If this class object represents a reference type that is not an
350 * array type then the binary name of the class is returned, as specified
352 * <cite>The Java™ Language Specification</cite>.
354 * <p> If this class object represents a primitive type or void, then the
355 * name returned is a {@code String} equal to the Java language
356 * keyword corresponding to the primitive type or void.
358 * <p> If this class object represents a class of arrays, then the internal
359 * form of the name consists of the name of the element type preceded by
360 * one or more '{@code [}' characters representing the depth of the array
361 * nesting. The encoding of element type names is as follows:
363 * <blockquote><table summary="Element types and encodings">
364 * <tr><th> Element Type <th> <th> Encoding
365 * <tr><td> boolean <td> <td align=center> Z
366 * <tr><td> byte <td> <td align=center> B
367 * <tr><td> char <td> <td align=center> C
368 * <tr><td> class or interface
369 * <td> <td align=center> L<i>classname</i>;
370 * <tr><td> double <td> <td align=center> D
371 * <tr><td> float <td> <td align=center> F
372 * <tr><td> int <td> <td align=center> I
373 * <tr><td> long <td> <td align=center> J
374 * <tr><td> short <td> <td align=center> S
375 * </table></blockquote>
377 * <p> The class or interface name <i>classname</i> is the binary name of
378 * the class specified above.
382 * String.class.getName()
383 * returns "java.lang.String"
384 * byte.class.getName()
386 * (new Object[3]).getClass().getName()
387 * returns "[Ljava.lang.Object;"
388 * (new int[3][4][5][6][7][8][9]).getClass().getName()
390 * </pre></blockquote>
392 * @return the name of the class or interface
393 * represented by this object.
395 public String getName() {
396 return jvmName().replace('/', '.');
399 @JavaScriptBody(args = "self", body = "return self.jvmName;")
400 private native String jvmName();
404 * Returns an array of {@code TypeVariable} objects that represent the
405 * type variables declared by the generic declaration represented by this
406 * {@code GenericDeclaration} object, in declaration order. Returns an
407 * array of length 0 if the underlying generic declaration declares no type
410 * @return an array of {@code TypeVariable} objects that represent
411 * the type variables declared by this generic declaration
412 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
413 * signature of this generic declaration does not conform to
414 * the format specified in
415 * <cite>The Java™ Virtual Machine Specification</cite>
418 public TypeVariable<Class<T>>[] getTypeParameters() {
419 throw new UnsupportedOperationException();
423 * Returns the {@code Class} representing the superclass of the entity
424 * (class, interface, primitive type or void) represented by this
425 * {@code Class}. If this {@code Class} represents either the
426 * {@code Object} class, an interface, a primitive type, or void, then
427 * null is returned. If this object represents an array class then the
428 * {@code Class} object representing the {@code Object} class is
431 * @return the superclass of the class represented by this object.
433 @JavaScriptBody(args = "self", body = "return self.superclass;")
434 public native Class<? super T> getSuperclass();
437 * Returns the Java language modifiers for this class or interface, encoded
438 * in an integer. The modifiers consist of the Java Virtual Machine's
439 * constants for {@code public}, {@code protected},
440 * {@code private}, {@code final}, {@code static},
441 * {@code abstract} and {@code interface}; they should be decoded
442 * using the methods of class {@code Modifier}.
444 * <p> If the underlying class is an array class, then its
445 * {@code public}, {@code private} and {@code protected}
446 * modifiers are the same as those of its component type. If this
447 * {@code Class} represents a primitive type or void, its
448 * {@code public} modifier is always {@code true}, and its
449 * {@code protected} and {@code private} modifiers are always
450 * {@code false}. If this object represents an array class, a
451 * primitive type or void, then its {@code final} modifier is always
452 * {@code true} and its interface modifier is always
453 * {@code false}. The values of its other modifiers are not determined
454 * by this specification.
456 * <p> The modifier encodings are defined in <em>The Java Virtual Machine
457 * Specification</em>, table 4.1.
459 * @return the {@code int} representing the modifiers for this class
460 * @see java.lang.reflect.Modifier
463 public native int getModifiers();
467 * Returns the simple name of the underlying class as given in the
468 * source code. Returns an empty string if the underlying class is
471 * <p>The simple name of an array is the simple name of the
472 * component type with "[]" appended. In particular the simple
473 * name of an array whose component type is anonymous is "[]".
475 * @return the simple name of the underlying class
478 public String getSimpleName() {
480 return getComponentType().getSimpleName()+"[]";
482 String simpleName = getSimpleBinaryName();
483 if (simpleName == null) { // top level class
484 simpleName = getName();
485 return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
487 // According to JLS3 "Binary Compatibility" (13.1) the binary
488 // name of non-package classes (not top level) is the binary
489 // name of the immediately enclosing class followed by a '$' followed by:
490 // (for nested and inner classes): the simple name.
491 // (for local classes): 1 or more digits followed by the simple name.
492 // (for anonymous classes): 1 or more digits.
494 // Since getSimpleBinaryName() will strip the binary name of
495 // the immediatly enclosing class, we are now looking at a
496 // string that matches the regular expression "\$[0-9]*"
497 // followed by a simple name (considering the simple of an
498 // anonymous class to be the empty string).
500 // Remove leading "\$[0-9]*" from the name
501 int length = simpleName.length();
502 if (length < 1 || simpleName.charAt(0) != '$')
503 throw new IllegalStateException("Malformed class name");
505 while (index < length && isAsciiDigit(simpleName.charAt(index)))
507 // Eventually, this is the empty string iff this is an anonymous class
508 return simpleName.substring(index);
512 * Returns the "simple binary name" of the underlying class, i.e.,
513 * the binary name without the leading enclosing class name.
514 * Returns {@code null} if the underlying class is a top level
517 private String getSimpleBinaryName() {
518 Class<?> enclosingClass = null; // XXX getEnclosingClass();
519 if (enclosingClass == null) // top level class
521 // Otherwise, strip the enclosing class' name
523 return getName().substring(enclosingClass.getName().length());
524 } catch (IndexOutOfBoundsException ex) {
525 throw new IllegalStateException("Malformed class name");
530 * Returns an array containing {@code Field} objects reflecting all
531 * the accessible public fields of the class or interface represented by
532 * this {@code Class} object. The elements in the array returned are
533 * not sorted and are not in any particular order. This method returns an
534 * array of length 0 if the class or interface has no accessible public
535 * fields, or if it represents an array class, a primitive type, or void.
537 * <p> Specifically, if this {@code Class} object represents a class,
538 * this method returns the public fields of this class and of all its
539 * superclasses. If this {@code Class} object represents an
540 * interface, this method returns the fields of this interface and of all
541 * its superinterfaces.
543 * <p> The implicit length field for array class is not reflected by this
544 * method. User code should use the methods of class {@code Array} to
547 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
549 * @return the array of {@code Field} objects representing the
551 * @exception SecurityException
552 * If a security manager, <i>s</i>, is present and any of the
553 * following conditions is met:
558 * {@link SecurityManager#checkMemberAccess
559 * s.checkMemberAccess(this, Member.PUBLIC)} denies
560 * access to the fields within this class
562 * <li> the caller's class loader is not the same as or an
563 * ancestor of the class loader for the current class and
564 * invocation of {@link SecurityManager#checkPackageAccess
565 * s.checkPackageAccess()} denies access to the package
572 public Field[] getFields() throws SecurityException {
573 throw new SecurityException();
577 * Returns an array containing {@code Method} objects reflecting all
578 * the public <em>member</em> methods of the class or interface represented
579 * by this {@code Class} object, including those declared by the class
580 * or interface and those inherited from superclasses and
581 * superinterfaces. Array classes return all the (public) member methods
582 * inherited from the {@code Object} class. The elements in the array
583 * returned are not sorted and are not in any particular order. This
584 * method returns an array of length 0 if this {@code Class} object
585 * represents a class or interface that has no public member methods, or if
586 * this {@code Class} object represents a primitive type or void.
588 * <p> The class initialization method {@code <clinit>} is not
589 * included in the returned array. If the class declares multiple public
590 * member methods with the same parameter types, they are all included in
591 * the returned array.
593 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
595 * @return the array of {@code Method} objects representing the
596 * public methods of this class
597 * @exception SecurityException
598 * If a security manager, <i>s</i>, is present and any of the
599 * following conditions is met:
604 * {@link SecurityManager#checkMemberAccess
605 * s.checkMemberAccess(this, Member.PUBLIC)} denies
606 * access to the methods within this class
608 * <li> the caller's class loader is not the same as or an
609 * ancestor of the class loader for the current class and
610 * invocation of {@link SecurityManager#checkPackageAccess
611 * s.checkPackageAccess()} denies access to the package
618 public Method[] getMethods() throws SecurityException {
619 throw new SecurityException();
623 * Returns a {@code Field} object that reflects the specified public
624 * member field of the class or interface represented by this
625 * {@code Class} object. The {@code name} parameter is a
626 * {@code String} specifying the simple name of the desired field.
628 * <p> The field to be reflected is determined by the algorithm that
629 * follows. Let C be the class represented by this object:
631 * <LI> If C declares a public field with the name specified, that is the
632 * field to be reflected.</LI>
633 * <LI> If no field was found in step 1 above, this algorithm is applied
634 * recursively to each direct superinterface of C. The direct
635 * superinterfaces are searched in the order they were declared.</LI>
636 * <LI> If no field was found in steps 1 and 2 above, and C has a
637 * superclass S, then this algorithm is invoked recursively upon S.
638 * If C has no superclass, then a {@code NoSuchFieldException}
642 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
644 * @param name the field name
645 * @return the {@code Field} object of this class specified by
647 * @exception NoSuchFieldException if a field with the specified name is
649 * @exception NullPointerException if {@code name} is {@code null}
650 * @exception SecurityException
651 * If a security manager, <i>s</i>, is present and any of the
652 * following conditions is met:
657 * {@link SecurityManager#checkMemberAccess
658 * s.checkMemberAccess(this, Member.PUBLIC)} denies
659 * access to the field
661 * <li> the caller's class loader is not the same as or an
662 * ancestor of the class loader for the current class and
663 * invocation of {@link SecurityManager#checkPackageAccess
664 * s.checkPackageAccess()} denies access to the package
671 public Field getField(String name)
672 throws SecurityException {
673 throw new SecurityException();
678 * Returns a {@code Method} object that reflects the specified public
679 * member method of the class or interface represented by this
680 * {@code Class} object. The {@code name} parameter is a
681 * {@code String} specifying the simple name of the desired method. The
682 * {@code parameterTypes} parameter is an array of {@code Class}
683 * objects that identify the method's formal parameter types, in declared
684 * order. If {@code parameterTypes} is {@code null}, it is
685 * treated as if it were an empty array.
687 * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
688 * {@code NoSuchMethodException} is raised. Otherwise, the method to
689 * be reflected is determined by the algorithm that follows. Let C be the
690 * class represented by this object:
692 * <LI> C is searched for any <I>matching methods</I>. If no matching
693 * method is found, the algorithm of step 1 is invoked recursively on
694 * the superclass of C.</LI>
695 * <LI> If no method was found in step 1 above, the superinterfaces of C
696 * are searched for a matching method. If any such method is found, it
700 * To find a matching method in a class C: If C declares exactly one
701 * public method with the specified name and exactly the same formal
702 * parameter types, that is the method reflected. If more than one such
703 * method is found in C, and one of these methods has a return type that is
704 * more specific than any of the others, that method is reflected;
705 * otherwise one of the methods is chosen arbitrarily.
707 * <p>Note that there may be more than one matching method in a
708 * class because while the Java language forbids a class to
709 * declare multiple methods with the same signature but different
710 * return types, the Java virtual machine does not. This
711 * increased flexibility in the virtual machine can be used to
712 * implement various language features. For example, covariant
713 * returns can be implemented with {@linkplain
714 * java.lang.reflect.Method#isBridge bridge methods}; the bridge
715 * method and the method being overridden would have the same
716 * signature but different return types.
718 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
720 * @param name the name of the method
721 * @param parameterTypes the list of parameters
722 * @return the {@code Method} object that matches the specified
723 * {@code name} and {@code parameterTypes}
724 * @exception NoSuchMethodException if a matching method is not found
725 * or if the name is "<init>"or "<clinit>".
726 * @exception NullPointerException if {@code name} is {@code null}
727 * @exception SecurityException
728 * If a security manager, <i>s</i>, is present and any of the
729 * following conditions is met:
734 * {@link SecurityManager#checkMemberAccess
735 * s.checkMemberAccess(this, Member.PUBLIC)} denies
736 * access to the method
738 * <li> the caller's class loader is not the same as or an
739 * ancestor of the class loader for the current class and
740 * invocation of {@link SecurityManager#checkPackageAccess
741 * s.checkPackageAccess()} denies access to the package
748 public Method getMethod(String name, Class<?>... parameterTypes)
749 throws SecurityException {
750 throw new SecurityException();
754 * Character.isDigit answers {@code true} to some non-ascii
755 * digits. This one does not.
757 private static boolean isAsciiDigit(char c) {
758 return '0' <= c && c <= '9';
762 * Returns the canonical name of the underlying class as
763 * defined by the Java Language Specification. Returns null if
764 * the underlying class does not have a canonical name (i.e., if
765 * it is a local or anonymous class or an array whose component
766 * type does not have a canonical name).
767 * @return the canonical name of the underlying class if it exists, and
768 * {@code null} otherwise.
771 public String getCanonicalName() {
773 String canonicalName = getComponentType().getCanonicalName();
774 if (canonicalName != null)
775 return canonicalName + "[]";
779 // if (isLocalOrAnonymousClass())
781 // Class<?> enclosingClass = getEnclosingClass();
782 Class<?> enclosingClass = null;
783 if (enclosingClass == null) { // top level class
786 String enclosingName = enclosingClass.getCanonicalName();
787 if (enclosingName == null)
789 return enclosingName + "." + getSimpleName();
794 * Finds a resource with a given name. The rules for searching resources
795 * associated with a given class are implemented by the defining
796 * {@linkplain ClassLoader class loader} of the class. This method
797 * delegates to this object's class loader. If this object was loaded by
798 * the bootstrap class loader, the method delegates to {@link
799 * ClassLoader#getSystemResourceAsStream}.
801 * <p> Before delegation, an absolute resource name is constructed from the
802 * given resource name using this algorithm:
806 * <li> If the {@code name} begins with a {@code '/'}
807 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
808 * portion of the {@code name} following the {@code '/'}.
810 * <li> Otherwise, the absolute name is of the following form:
813 * {@code modified_package_name/name}
816 * <p> Where the {@code modified_package_name} is the package name of this
817 * object with {@code '/'} substituted for {@code '.'}
818 * (<tt>'\u002e'</tt>).
822 * @param name name of the desired resource
823 * @return A {@link java.io.InputStream} object or {@code null} if
824 * no resource with this name is found
825 * @throws NullPointerException If {@code name} is {@code null}
828 public InputStream getResourceAsStream(String name) {
829 name = resolveName(name);
830 ClassLoader cl = getClassLoader0();
833 return ClassLoader.getSystemResourceAsStream(name);
835 return cl.getResourceAsStream(name);
839 * Finds a resource with a given name. The rules for searching resources
840 * associated with a given class are implemented by the defining
841 * {@linkplain ClassLoader class loader} of the class. This method
842 * delegates to this object's class loader. If this object was loaded by
843 * the bootstrap class loader, the method delegates to {@link
844 * ClassLoader#getSystemResource}.
846 * <p> Before delegation, an absolute resource name is constructed from the
847 * given resource name using this algorithm:
851 * <li> If the {@code name} begins with a {@code '/'}
852 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
853 * portion of the {@code name} following the {@code '/'}.
855 * <li> Otherwise, the absolute name is of the following form:
858 * {@code modified_package_name/name}
861 * <p> Where the {@code modified_package_name} is the package name of this
862 * object with {@code '/'} substituted for {@code '.'}
863 * (<tt>'\u002e'</tt>).
867 * @param name name of the desired resource
868 * @return A {@link java.net.URL} object or {@code null} if no
869 * resource with this name is found
872 public java.net.URL getResource(String name) {
873 name = resolveName(name);
874 ClassLoader cl = getClassLoader0();
877 return ClassLoader.getSystemResource(name);
879 return cl.getResource(name);
884 * Add a package name prefix if the name is not absolute Remove leading "/"
885 * if name is absolute
887 private String resolveName(String name) {
891 if (!name.startsWith("/")) {
893 while (c.isArray()) {
894 c = c.getComponentType();
896 String baseName = c.getName();
897 int index = baseName.lastIndexOf('.');
899 name = baseName.substring(0, index).replace('.', '/')
903 name = name.substring(1);
909 * Returns the class loader for the class. Some implementations may use
910 * null to represent the bootstrap class loader. This method will return
911 * null in such implementations if this class was loaded by the bootstrap
914 * <p> If a security manager is present, and the caller's class loader is
915 * not null and the caller's class loader is not the same as or an ancestor of
916 * the class loader for the class whose class loader is requested, then
917 * this method calls the security manager's {@code checkPermission}
918 * method with a {@code RuntimePermission("getClassLoader")}
919 * permission to ensure it's ok to access the class loader for the class.
922 * represents a primitive type or void, null is returned.
924 * @return the class loader that loaded the class or interface
925 * represented by this object.
926 * @throws SecurityException
927 * if a security manager exists and its
928 * {@code checkPermission} method denies
929 * access to the class loader for the class.
930 * @see java.lang.ClassLoader
931 * @see SecurityManager#checkPermission
932 * @see java.lang.RuntimePermission
934 public ClassLoader getClassLoader() {
935 throw new SecurityException();
938 // Package-private to allow ClassLoader access
939 native ClassLoader getClassLoader0();
942 * Returns the {@code Class} representing the component type of an
943 * array. If this class does not represent an array class this method
946 * @return the {@code Class} representing the component type of this
947 * class if this class is an array
948 * @see java.lang.reflect.Array
951 public Class<?> getComponentType() {
956 * Returns true if and only if this class was declared as an enum in the
959 * @return true if and only if this class was declared as an enum in the
963 public boolean isEnum() {
964 // An enum must both directly extend java.lang.Enum and have
965 // the ENUM bit set; classes for specialized enum constants
966 // don't do the former.
967 return (this.getModifiers() & ENUM) != 0 &&
968 this.getSuperclass() == java.lang.Enum.class;
972 * Casts an object to the class or interface represented
973 * by this {@code Class} object.
975 * @param obj the object to be cast
976 * @return the object after casting, or null if obj is null
978 * @throws ClassCastException if the object is not
979 * null and is not assignable to the type T.
983 public T cast(Object obj) {
984 if (obj != null && !isInstance(obj))
985 throw new ClassCastException(cannotCastMsg(obj));
989 private String cannotCastMsg(Object obj) {
990 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
994 * Casts this {@code Class} object to represent a subclass of the class
995 * represented by the specified class object. Checks that that the cast
996 * is valid, and throws a {@code ClassCastException} if it is not. If
997 * this method succeeds, it always returns a reference to this class object.
999 * <p>This method is useful when a client needs to "narrow" the type of
1000 * a {@code Class} object to pass it to an API that restricts the
1001 * {@code Class} objects that it is willing to accept. A cast would
1002 * generate a compile-time warning, as the correctness of the cast
1003 * could not be checked at runtime (because generic types are implemented
1006 * @return this {@code Class} object, cast to represent a subclass of
1007 * the specified class object.
1008 * @throws ClassCastException if this {@code Class} object does not
1009 * represent a subclass of the specified class (here "subclass" includes
1010 * the class itself).
1013 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
1014 if (clazz.isAssignableFrom(this))
1015 return (Class<? extends U>) this;
1017 throw new ClassCastException(this.toString());
1020 @JavaScriptBody(args = { "self", "ac" },
1023 + " return self.anno['L' + ac.jvmName + ';'];"
1026 private Object getAnnotationData(Class<?> annotationClass) {
1027 throw new UnsupportedOperationException();
1030 * @throws NullPointerException {@inheritDoc}
1033 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
1034 Object data = getAnnotationData(annotationClass);
1035 return data == null ? null : AnnotationImpl.create(annotationClass, data);
1039 * @throws NullPointerException {@inheritDoc}
1042 @JavaScriptBody(args = { "self", "ac" },
1043 body = "if (self.anno && self.anno['L' + ac.jvmName + ';']) { return true; }"
1044 + "else return false;"
1046 public boolean isAnnotationPresent(
1047 Class<? extends Annotation> annotationClass) {
1048 if (annotationClass == null)
1049 throw new NullPointerException();
1051 return getAnnotation(annotationClass) != null;
1054 @JavaScriptBody(args = "self", body = "return self.anno;")
1055 private Object getAnnotationData() {
1056 throw new UnsupportedOperationException();
1062 public Annotation[] getAnnotations() {
1063 Object data = getAnnotationData();
1064 return data == null ? new Annotation[0] : AnnotationImpl.create(data);
1070 public Annotation[] getDeclaredAnnotations() {
1071 throw new UnsupportedOperationException();
1074 static Class getPrimitiveClass(String type) {
1076 return Object.class;
1079 public boolean desiredAssertionStatus() {