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;
35 import org.apidesign.bck2brwsr.emul.MethodImpl;
38 * Instances of the class {@code Class} represent classes and
39 * interfaces in a running Java application. An enum is a kind of
40 * class and an annotation is a kind of interface. Every array also
41 * belongs to a class that is reflected as a {@code Class} object
42 * that is shared by all arrays with the same element type and number
43 * of dimensions. The primitive Java types ({@code boolean},
44 * {@code byte}, {@code char}, {@code short},
45 * {@code int}, {@code long}, {@code float}, and
46 * {@code double}), and the keyword {@code void} are also
47 * represented as {@code Class} objects.
49 * <p> {@code Class} has no public constructor. Instead {@code Class}
50 * objects are constructed automatically by the Java Virtual Machine as classes
51 * are loaded and by calls to the {@code defineClass} method in the class
54 * <p> The following example uses a {@code Class} object to print the
55 * class name of an object:
57 * <p> <blockquote><pre>
58 * void printClassName(Object obj) {
59 * System.out.println("The class of " + obj +
60 * " is " + obj.getClass().getName());
64 * <p> It is also possible to get the {@code Class} object for a named
65 * type (or for void) using a class literal. See Section 15.8.2 of
66 * <cite>The Java™ Language Specification</cite>.
70 * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
73 * @param <T> the type of the class modeled by this {@code Class}
74 * object. For example, the type of {@code String.class} is {@code
75 * Class<String>}. Use {@code Class<?>} if the class being modeled is
79 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
83 class Class<T> implements java.io.Serializable,
84 java.lang.reflect.GenericDeclaration,
85 java.lang.reflect.Type,
86 java.lang.reflect.AnnotatedElement {
87 private static final int ANNOTATION= 0x00002000;
88 private static final int ENUM = 0x00004000;
89 private static final int SYNTHETIC = 0x00001000;
92 * Constructor. Only the Java Virtual Machine creates Class
99 * Converts the object to a string. The string representation is the
100 * string "class" or "interface", followed by a space, and then by the
101 * fully qualified name of the class in the format returned by
102 * {@code getName}. If this {@code Class} object represents a
103 * primitive type, this method returns the name of the primitive type. If
104 * this {@code Class} object represents void this method returns
107 * @return a string representation of this class object.
109 public String toString() {
110 return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
116 * Returns the {@code Class} object associated with the class or
117 * interface with the given string name. Invoking this method is
121 * {@code Class.forName(className, true, currentLoader)}
124 * where {@code currentLoader} denotes the defining class loader of
127 * <p> For example, the following code fragment returns the
128 * runtime {@code Class} descriptor for the class named
129 * {@code java.lang.Thread}:
132 * {@code Class t = Class.forName("java.lang.Thread")}
135 * A call to {@code forName("X")} causes the class named
136 * {@code X} to be initialized.
138 * @param className the fully qualified name of the desired class.
139 * @return the {@code Class} object for the class with the
141 * @exception LinkageError if the linkage fails
142 * @exception ExceptionInInitializerError if the initialization provoked
143 * by this method fails
144 * @exception ClassNotFoundException if the class cannot be located
146 public static Class<?> forName(String className)
147 throws ClassNotFoundException {
148 Class<?> c = loadCls(className, className.replace('.', '_'));
150 throw new ClassNotFoundException(className);
155 @JavaScriptBody(args = {"n", "c" }, body =
156 "if (vm[c]) return vm[c].$class;\n"
157 + "if (vm.loadClass) {\n"
158 + " vm.loadClass(n);\n"
159 + " if (vm[c]) return vm[c].$class;\n"
163 private static native Class<?> loadCls(String n, String c);
167 * Creates a new instance of the class represented by this {@code Class}
168 * object. The class is instantiated as if by a {@code new}
169 * expression with an empty argument list. The class is initialized if it
170 * has not already been initialized.
172 * <p>Note that this method propagates any exception thrown by the
173 * nullary constructor, including a checked exception. Use of
174 * this method effectively bypasses the compile-time exception
175 * checking that would otherwise be performed by the compiler.
177 * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
178 * Constructor.newInstance} method avoids this problem by wrapping
179 * any exception thrown by the constructor in a (checked) {@link
180 * java.lang.reflect.InvocationTargetException}.
182 * @return a newly allocated instance of the class represented by this
184 * @exception IllegalAccessException if the class or its nullary
185 * constructor is not accessible.
186 * @exception InstantiationException
187 * if this {@code Class} represents an abstract class,
188 * an interface, an array class, a primitive type, or void;
189 * or if the class has no nullary constructor;
190 * or if the instantiation fails for some other reason.
191 * @exception ExceptionInInitializerError if the initialization
192 * provoked by this method fails.
193 * @exception SecurityException
194 * If a security manager, <i>s</i>, is present and any of the
195 * following conditions is met:
200 * {@link SecurityManager#checkMemberAccess
201 * s.checkMemberAccess(this, Member.PUBLIC)} denies
202 * creation of new instances of this class
204 * <li> the caller's class loader is not the same as or an
205 * ancestor of the class loader for the current class and
206 * invocation of {@link SecurityManager#checkPackageAccess
207 * s.checkPackageAccess()} denies access to the package
213 @JavaScriptBody(args = { "self", "illegal" }, body =
214 "\nvar c = self.cnstr;"
215 + "\nif (c['cons__V']) {"
216 + "\n if ((c.cons__V.access & 0x1) != 0) {"
217 + "\n var inst = c();"
218 + "\n c.cons__V(inst);"
221 + "\n return illegal;"
225 private static native Object newInstance0(Class<?> self, Object illegal);
227 public T newInstance()
228 throws InstantiationException, IllegalAccessException
230 Object illegal = new Object();
231 Object inst = newInstance0(this, illegal);
233 throw new InstantiationException(getName());
235 if (inst == illegal) {
236 throw new IllegalAccessException();
242 * Determines if the specified {@code Object} is assignment-compatible
243 * with the object represented by this {@code Class}. This method is
244 * the dynamic equivalent of the Java language {@code instanceof}
245 * operator. The method returns {@code true} if the specified
246 * {@code Object} argument is non-null and can be cast to the
247 * reference type represented by this {@code Class} object without
248 * raising a {@code ClassCastException.} It returns {@code false}
251 * <p> Specifically, if this {@code Class} object represents a
252 * declared class, this method returns {@code true} if the specified
253 * {@code Object} argument is an instance of the represented class (or
254 * of any of its subclasses); it returns {@code false} otherwise. If
255 * this {@code Class} object represents an array class, this method
256 * returns {@code true} if the specified {@code Object} argument
257 * can be converted to an object of the array class by an identity
258 * conversion or by a widening reference conversion; it returns
259 * {@code false} otherwise. If this {@code Class} object
260 * represents an interface, this method returns {@code true} if the
261 * class or any superclass of the specified {@code Object} argument
262 * implements this interface; it returns {@code false} otherwise. If
263 * this {@code Class} object represents a primitive type, this method
264 * returns {@code false}.
266 * @param obj the object to check
267 * @return true if {@code obj} is an instance of this class
271 public native boolean isInstance(Object obj);
275 * Determines if the class or interface represented by this
276 * {@code Class} object is either the same as, or is a superclass or
277 * superinterface of, the class or interface represented by the specified
278 * {@code Class} parameter. It returns {@code true} if so;
279 * otherwise it returns {@code false}. If this {@code Class}
280 * object represents a primitive type, this method returns
281 * {@code true} if the specified {@code Class} parameter is
282 * exactly this {@code Class} object; otherwise it returns
285 * <p> Specifically, this method tests whether the type represented by the
286 * specified {@code Class} parameter can be converted to the type
287 * represented by this {@code Class} object via an identity conversion
288 * or via a widening reference conversion. See <em>The Java Language
289 * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
291 * @param cls the {@code Class} object to be checked
292 * @return the {@code boolean} value indicating whether objects of the
293 * type {@code cls} can be assigned to objects of this class
294 * @exception NullPointerException if the specified Class parameter is
298 public native boolean isAssignableFrom(Class<?> cls);
302 * Determines if the specified {@code Class} object represents an
305 * @return {@code true} if this object represents an interface;
306 * {@code false} otherwise.
308 public boolean isInterface() {
309 return (getAccess() & 0x200) != 0;
312 @JavaScriptBody(args = "self", body = "return self.access;")
313 private native int getAccess();
317 * Determines if this {@code Class} object represents an array class.
319 * @return {@code true} if this object represents an array class;
320 * {@code false} otherwise.
323 public boolean isArray() {
329 * Determines if the specified {@code Class} object represents a
332 * <p> There are nine predefined {@code Class} objects to represent
333 * the eight primitive types and void. These are created by the Java
334 * Virtual Machine, and have the same names as the primitive types that
335 * they represent, namely {@code boolean}, {@code byte},
336 * {@code char}, {@code short}, {@code int},
337 * {@code long}, {@code float}, and {@code double}.
339 * <p> These objects may only be accessed via the following public static
340 * final variables, and are the only {@code Class} objects for which
341 * this method returns {@code true}.
343 * @return true if and only if this class represents a primitive type
345 * @see java.lang.Boolean#TYPE
346 * @see java.lang.Character#TYPE
347 * @see java.lang.Byte#TYPE
348 * @see java.lang.Short#TYPE
349 * @see java.lang.Integer#TYPE
350 * @see java.lang.Long#TYPE
351 * @see java.lang.Float#TYPE
352 * @see java.lang.Double#TYPE
353 * @see java.lang.Void#TYPE
356 @JavaScriptBody(args = "self", body =
357 "if (self.primitive) return true;"
358 + "else return false;"
360 public native boolean isPrimitive();
363 * Returns true if this {@code Class} object represents an annotation
364 * type. Note that if this method returns true, {@link #isInterface()}
365 * would also return true, as all annotation types are also interfaces.
367 * @return {@code true} if this class object represents an annotation
368 * type; {@code false} otherwise
371 public boolean isAnnotation() {
372 return (getModifiers() & ANNOTATION) != 0;
376 * Returns {@code true} if this class is a synthetic class;
377 * returns {@code false} otherwise.
378 * @return {@code true} if and only if this class is a synthetic class as
379 * defined by the Java Language Specification.
382 public boolean isSynthetic() {
383 return (getModifiers() & SYNTHETIC) != 0;
387 * Returns the name of the entity (class, interface, array class,
388 * primitive type, or void) represented by this {@code Class} object,
389 * as a {@code String}.
391 * <p> If this class object represents a reference type that is not an
392 * array type then the binary name of the class is returned, as specified
394 * <cite>The Java™ Language Specification</cite>.
396 * <p> If this class object represents a primitive type or void, then the
397 * name returned is a {@code String} equal to the Java language
398 * keyword corresponding to the primitive type or void.
400 * <p> If this class object represents a class of arrays, then the internal
401 * form of the name consists of the name of the element type preceded by
402 * one or more '{@code [}' characters representing the depth of the array
403 * nesting. The encoding of element type names is as follows:
405 * <blockquote><table summary="Element types and encodings">
406 * <tr><th> Element Type <th> <th> Encoding
407 * <tr><td> boolean <td> <td align=center> Z
408 * <tr><td> byte <td> <td align=center> B
409 * <tr><td> char <td> <td align=center> C
410 * <tr><td> class or interface
411 * <td> <td align=center> L<i>classname</i>;
412 * <tr><td> double <td> <td align=center> D
413 * <tr><td> float <td> <td align=center> F
414 * <tr><td> int <td> <td align=center> I
415 * <tr><td> long <td> <td align=center> J
416 * <tr><td> short <td> <td align=center> S
417 * </table></blockquote>
419 * <p> The class or interface name <i>classname</i> is the binary name of
420 * the class specified above.
424 * String.class.getName()
425 * returns "java.lang.String"
426 * byte.class.getName()
428 * (new Object[3]).getClass().getName()
429 * returns "[Ljava.lang.Object;"
430 * (new int[3][4][5][6][7][8][9]).getClass().getName()
432 * </pre></blockquote>
434 * @return the name of the class or interface
435 * represented by this object.
437 public String getName() {
438 return jvmName().replace('/', '.');
441 @JavaScriptBody(args = "self", body = "return self.jvmName;")
442 private native String jvmName();
446 * Returns an array of {@code TypeVariable} objects that represent the
447 * type variables declared by the generic declaration represented by this
448 * {@code GenericDeclaration} object, in declaration order. Returns an
449 * array of length 0 if the underlying generic declaration declares no type
452 * @return an array of {@code TypeVariable} objects that represent
453 * the type variables declared by this generic declaration
454 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
455 * signature of this generic declaration does not conform to
456 * the format specified in
457 * <cite>The Java™ Virtual Machine Specification</cite>
460 public TypeVariable<Class<T>>[] getTypeParameters() {
461 throw new UnsupportedOperationException();
465 * Returns the {@code Class} representing the superclass of the entity
466 * (class, interface, primitive type or void) represented by this
467 * {@code Class}. If this {@code Class} represents either the
468 * {@code Object} class, an interface, a primitive type, or void, then
469 * null is returned. If this object represents an array class then the
470 * {@code Class} object representing the {@code Object} class is
473 * @return the superclass of the class represented by this object.
475 @JavaScriptBody(args = "self", body = "return self.superclass;")
476 public native Class<? super T> getSuperclass();
479 * Returns the Java language modifiers for this class or interface, encoded
480 * in an integer. The modifiers consist of the Java Virtual Machine's
481 * constants for {@code public}, {@code protected},
482 * {@code private}, {@code final}, {@code static},
483 * {@code abstract} and {@code interface}; they should be decoded
484 * using the methods of class {@code Modifier}.
486 * <p> If the underlying class is an array class, then its
487 * {@code public}, {@code private} and {@code protected}
488 * modifiers are the same as those of its component type. If this
489 * {@code Class} represents a primitive type or void, its
490 * {@code public} modifier is always {@code true}, and its
491 * {@code protected} and {@code private} modifiers are always
492 * {@code false}. If this object represents an array class, a
493 * primitive type or void, then its {@code final} modifier is always
494 * {@code true} and its interface modifier is always
495 * {@code false}. The values of its other modifiers are not determined
496 * by this specification.
498 * <p> The modifier encodings are defined in <em>The Java Virtual Machine
499 * Specification</em>, table 4.1.
501 * @return the {@code int} representing the modifiers for this class
502 * @see java.lang.reflect.Modifier
505 public native int getModifiers();
509 * Returns the simple name of the underlying class as given in the
510 * source code. Returns an empty string if the underlying class is
513 * <p>The simple name of an array is the simple name of the
514 * component type with "[]" appended. In particular the simple
515 * name of an array whose component type is anonymous is "[]".
517 * @return the simple name of the underlying class
520 public String getSimpleName() {
522 return getComponentType().getSimpleName()+"[]";
524 String simpleName = getSimpleBinaryName();
525 if (simpleName == null) { // top level class
526 simpleName = getName();
527 return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
529 // According to JLS3 "Binary Compatibility" (13.1) the binary
530 // name of non-package classes (not top level) is the binary
531 // name of the immediately enclosing class followed by a '$' followed by:
532 // (for nested and inner classes): the simple name.
533 // (for local classes): 1 or more digits followed by the simple name.
534 // (for anonymous classes): 1 or more digits.
536 // Since getSimpleBinaryName() will strip the binary name of
537 // the immediatly enclosing class, we are now looking at a
538 // string that matches the regular expression "\$[0-9]*"
539 // followed by a simple name (considering the simple of an
540 // anonymous class to be the empty string).
542 // Remove leading "\$[0-9]*" from the name
543 int length = simpleName.length();
544 if (length < 1 || simpleName.charAt(0) != '$')
545 throw new IllegalStateException("Malformed class name");
547 while (index < length && isAsciiDigit(simpleName.charAt(index)))
549 // Eventually, this is the empty string iff this is an anonymous class
550 return simpleName.substring(index);
554 * Returns the "simple binary name" of the underlying class, i.e.,
555 * the binary name without the leading enclosing class name.
556 * Returns {@code null} if the underlying class is a top level
559 private String getSimpleBinaryName() {
560 Class<?> enclosingClass = null; // XXX getEnclosingClass();
561 if (enclosingClass == null) // top level class
563 // Otherwise, strip the enclosing class' name
565 return getName().substring(enclosingClass.getName().length());
566 } catch (IndexOutOfBoundsException ex) {
567 throw new IllegalStateException("Malformed class name");
572 * Returns an array containing {@code Field} objects reflecting all
573 * the accessible public fields of the class or interface represented by
574 * this {@code Class} object. The elements in the array returned are
575 * not sorted and are not in any particular order. This method returns an
576 * array of length 0 if the class or interface has no accessible public
577 * fields, or if it represents an array class, a primitive type, or void.
579 * <p> Specifically, if this {@code Class} object represents a class,
580 * this method returns the public fields of this class and of all its
581 * superclasses. If this {@code Class} object represents an
582 * interface, this method returns the fields of this interface and of all
583 * its superinterfaces.
585 * <p> The implicit length field for array class is not reflected by this
586 * method. User code should use the methods of class {@code Array} to
589 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
591 * @return the array of {@code Field} objects representing the
593 * @exception SecurityException
594 * If a security manager, <i>s</i>, is present and any of the
595 * following conditions is met:
600 * {@link SecurityManager#checkMemberAccess
601 * s.checkMemberAccess(this, Member.PUBLIC)} denies
602 * access to the fields within this class
604 * <li> the caller's class loader is not the same as or an
605 * ancestor of the class loader for the current class and
606 * invocation of {@link SecurityManager#checkPackageAccess
607 * s.checkPackageAccess()} denies access to the package
614 public Field[] getFields() throws SecurityException {
615 throw new SecurityException();
619 * Returns an array containing {@code Method} objects reflecting all
620 * the public <em>member</em> methods of the class or interface represented
621 * by this {@code Class} object, including those declared by the class
622 * or interface and those inherited from superclasses and
623 * superinterfaces. Array classes return all the (public) member methods
624 * inherited from the {@code Object} class. The elements in the array
625 * returned are not sorted and are not in any particular order. This
626 * method returns an array of length 0 if this {@code Class} object
627 * represents a class or interface that has no public member methods, or if
628 * this {@code Class} object represents a primitive type or void.
630 * <p> The class initialization method {@code <clinit>} is not
631 * included in the returned array. If the class declares multiple public
632 * member methods with the same parameter types, they are all included in
633 * the returned array.
635 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
637 * @return the array of {@code Method} objects representing the
638 * public methods of this class
639 * @exception SecurityException
640 * If a security manager, <i>s</i>, is present and any of the
641 * following conditions is met:
646 * {@link SecurityManager#checkMemberAccess
647 * s.checkMemberAccess(this, Member.PUBLIC)} denies
648 * access to the methods within this class
650 * <li> the caller's class loader is not the same as or an
651 * ancestor of the class loader for the current class and
652 * invocation of {@link SecurityManager#checkPackageAccess
653 * s.checkPackageAccess()} denies access to the package
660 public Method[] getMethods() throws SecurityException {
661 return MethodImpl.findMethods(this, 0x01);
665 * Returns a {@code Field} object that reflects the specified public
666 * member field of the class or interface represented by this
667 * {@code Class} object. The {@code name} parameter is a
668 * {@code String} specifying the simple name of the desired field.
670 * <p> The field to be reflected is determined by the algorithm that
671 * follows. Let C be the class represented by this object:
673 * <LI> If C declares a public field with the name specified, that is the
674 * field to be reflected.</LI>
675 * <LI> If no field was found in step 1 above, this algorithm is applied
676 * recursively to each direct superinterface of C. The direct
677 * superinterfaces are searched in the order they were declared.</LI>
678 * <LI> If no field was found in steps 1 and 2 above, and C has a
679 * superclass S, then this algorithm is invoked recursively upon S.
680 * If C has no superclass, then a {@code NoSuchFieldException}
684 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
686 * @param name the field name
687 * @return the {@code Field} object of this class specified by
689 * @exception NoSuchFieldException if a field with the specified name is
691 * @exception NullPointerException if {@code name} is {@code null}
692 * @exception SecurityException
693 * If a security manager, <i>s</i>, is present and any of the
694 * following conditions is met:
699 * {@link SecurityManager#checkMemberAccess
700 * s.checkMemberAccess(this, Member.PUBLIC)} denies
701 * access to the field
703 * <li> the caller's class loader is not the same as or an
704 * ancestor of the class loader for the current class and
705 * invocation of {@link SecurityManager#checkPackageAccess
706 * s.checkPackageAccess()} denies access to the package
713 public Field getField(String name)
714 throws SecurityException {
715 throw new SecurityException();
720 * Returns a {@code Method} object that reflects the specified public
721 * member method of the class or interface represented by this
722 * {@code Class} object. The {@code name} parameter is a
723 * {@code String} specifying the simple name of the desired method. The
724 * {@code parameterTypes} parameter is an array of {@code Class}
725 * objects that identify the method's formal parameter types, in declared
726 * order. If {@code parameterTypes} is {@code null}, it is
727 * treated as if it were an empty array.
729 * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
730 * {@code NoSuchMethodException} is raised. Otherwise, the method to
731 * be reflected is determined by the algorithm that follows. Let C be the
732 * class represented by this object:
734 * <LI> C is searched for any <I>matching methods</I>. If no matching
735 * method is found, the algorithm of step 1 is invoked recursively on
736 * the superclass of C.</LI>
737 * <LI> If no method was found in step 1 above, the superinterfaces of C
738 * are searched for a matching method. If any such method is found, it
742 * To find a matching method in a class C: If C declares exactly one
743 * public method with the specified name and exactly the same formal
744 * parameter types, that is the method reflected. If more than one such
745 * method is found in C, and one of these methods has a return type that is
746 * more specific than any of the others, that method is reflected;
747 * otherwise one of the methods is chosen arbitrarily.
749 * <p>Note that there may be more than one matching method in a
750 * class because while the Java language forbids a class to
751 * declare multiple methods with the same signature but different
752 * return types, the Java virtual machine does not. This
753 * increased flexibility in the virtual machine can be used to
754 * implement various language features. For example, covariant
755 * returns can be implemented with {@linkplain
756 * java.lang.reflect.Method#isBridge bridge methods}; the bridge
757 * method and the method being overridden would have the same
758 * signature but different return types.
760 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
762 * @param name the name of the method
763 * @param parameterTypes the list of parameters
764 * @return the {@code Method} object that matches the specified
765 * {@code name} and {@code parameterTypes}
766 * @exception NoSuchMethodException if a matching method is not found
767 * or if the name is "<init>"or "<clinit>".
768 * @exception NullPointerException if {@code name} is {@code null}
769 * @exception SecurityException
770 * If a security manager, <i>s</i>, is present and any of the
771 * following conditions is met:
776 * {@link SecurityManager#checkMemberAccess
777 * s.checkMemberAccess(this, Member.PUBLIC)} denies
778 * access to the method
780 * <li> the caller's class loader is not the same as or an
781 * ancestor of the class loader for the current class and
782 * invocation of {@link SecurityManager#checkPackageAccess
783 * s.checkPackageAccess()} denies access to the package
790 public Method getMethod(String name, Class<?>... parameterTypes)
791 throws SecurityException, NoSuchMethodException {
792 Method m = MethodImpl.findMethod(this, name, parameterTypes);
794 StringBuilder sb = new StringBuilder();
795 sb.append(getName()).append('.').append(name).append('(');
797 for (int i = 0; i < parameterTypes.length; i++) {
798 sb.append(sep).append(parameterTypes[i].getName());
802 throw new NoSuchMethodException(sb.toString());
808 * Character.isDigit answers {@code true} to some non-ascii
809 * digits. This one does not.
811 private static boolean isAsciiDigit(char c) {
812 return '0' <= c && c <= '9';
816 * Returns the canonical name of the underlying class as
817 * defined by the Java Language Specification. Returns null if
818 * the underlying class does not have a canonical name (i.e., if
819 * it is a local or anonymous class or an array whose component
820 * type does not have a canonical name).
821 * @return the canonical name of the underlying class if it exists, and
822 * {@code null} otherwise.
825 public String getCanonicalName() {
827 String canonicalName = getComponentType().getCanonicalName();
828 if (canonicalName != null)
829 return canonicalName + "[]";
833 // if (isLocalOrAnonymousClass())
835 // Class<?> enclosingClass = getEnclosingClass();
836 Class<?> enclosingClass = null;
837 if (enclosingClass == null) { // top level class
840 String enclosingName = enclosingClass.getCanonicalName();
841 if (enclosingName == null)
843 return enclosingName + "." + getSimpleName();
848 * Finds a resource with a given name. The rules for searching resources
849 * associated with a given class are implemented by the defining
850 * {@linkplain ClassLoader class loader} of the class. This method
851 * delegates to this object's class loader. If this object was loaded by
852 * the bootstrap class loader, the method delegates to {@link
853 * ClassLoader#getSystemResourceAsStream}.
855 * <p> Before delegation, an absolute resource name is constructed from the
856 * given resource name using this algorithm:
860 * <li> If the {@code name} begins with a {@code '/'}
861 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
862 * portion of the {@code name} following the {@code '/'}.
864 * <li> Otherwise, the absolute name is of the following form:
867 * {@code modified_package_name/name}
870 * <p> Where the {@code modified_package_name} is the package name of this
871 * object with {@code '/'} substituted for {@code '.'}
872 * (<tt>'\u002e'</tt>).
876 * @param name name of the desired resource
877 * @return A {@link java.io.InputStream} object or {@code null} if
878 * no resource with this name is found
879 * @throws NullPointerException If {@code name} is {@code null}
882 public InputStream getResourceAsStream(String name) {
883 name = resolveName(name);
884 ClassLoader cl = getClassLoader0();
887 return ClassLoader.getSystemResourceAsStream(name);
889 return cl.getResourceAsStream(name);
893 * Finds a resource with a given name. The rules for searching resources
894 * associated with a given class are implemented by the defining
895 * {@linkplain ClassLoader class loader} of the class. This method
896 * delegates to this object's class loader. If this object was loaded by
897 * the bootstrap class loader, the method delegates to {@link
898 * ClassLoader#getSystemResource}.
900 * <p> Before delegation, an absolute resource name is constructed from the
901 * given resource name using this algorithm:
905 * <li> If the {@code name} begins with a {@code '/'}
906 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
907 * portion of the {@code name} following the {@code '/'}.
909 * <li> Otherwise, the absolute name is of the following form:
912 * {@code modified_package_name/name}
915 * <p> Where the {@code modified_package_name} is the package name of this
916 * object with {@code '/'} substituted for {@code '.'}
917 * (<tt>'\u002e'</tt>).
921 * @param name name of the desired resource
922 * @return A {@link java.net.URL} object or {@code null} if no
923 * resource with this name is found
926 public java.net.URL getResource(String name) {
927 name = resolveName(name);
928 ClassLoader cl = getClassLoader0();
931 return ClassLoader.getSystemResource(name);
933 return cl.getResource(name);
938 * Add a package name prefix if the name is not absolute Remove leading "/"
939 * if name is absolute
941 private String resolveName(String name) {
945 if (!name.startsWith("/")) {
947 while (c.isArray()) {
948 c = c.getComponentType();
950 String baseName = c.getName();
951 int index = baseName.lastIndexOf('.');
953 name = baseName.substring(0, index).replace('.', '/')
957 name = name.substring(1);
963 * Returns the class loader for the class. Some implementations may use
964 * null to represent the bootstrap class loader. This method will return
965 * null in such implementations if this class was loaded by the bootstrap
968 * <p> If a security manager is present, and the caller's class loader is
969 * not null and the caller's class loader is not the same as or an ancestor of
970 * the class loader for the class whose class loader is requested, then
971 * this method calls the security manager's {@code checkPermission}
972 * method with a {@code RuntimePermission("getClassLoader")}
973 * permission to ensure it's ok to access the class loader for the class.
976 * represents a primitive type or void, null is returned.
978 * @return the class loader that loaded the class or interface
979 * represented by this object.
980 * @throws SecurityException
981 * if a security manager exists and its
982 * {@code checkPermission} method denies
983 * access to the class loader for the class.
984 * @see java.lang.ClassLoader
985 * @see SecurityManager#checkPermission
986 * @see java.lang.RuntimePermission
988 public ClassLoader getClassLoader() {
989 throw new SecurityException();
992 // Package-private to allow ClassLoader access
993 native ClassLoader getClassLoader0();
996 * Returns the {@code Class} representing the component type of an
997 * array. If this class does not represent an array class this method
1000 * @return the {@code Class} representing the component type of this
1001 * class if this class is an array
1002 * @see java.lang.reflect.Array
1005 public Class<?> getComponentType() {
1010 * Returns true if and only if this class was declared as an enum in the
1013 * @return true if and only if this class was declared as an enum in the
1017 public boolean isEnum() {
1018 // An enum must both directly extend java.lang.Enum and have
1019 // the ENUM bit set; classes for specialized enum constants
1020 // don't do the former.
1021 return (this.getModifiers() & ENUM) != 0 &&
1022 this.getSuperclass() == java.lang.Enum.class;
1026 * Casts an object to the class or interface represented
1027 * by this {@code Class} object.
1029 * @param obj the object to be cast
1030 * @return the object after casting, or null if obj is null
1032 * @throws ClassCastException if the object is not
1033 * null and is not assignable to the type T.
1037 public T cast(Object obj) {
1038 if (obj != null && !isInstance(obj))
1039 throw new ClassCastException(cannotCastMsg(obj));
1043 private String cannotCastMsg(Object obj) {
1044 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
1048 * Casts this {@code Class} object to represent a subclass of the class
1049 * represented by the specified class object. Checks that that the cast
1050 * is valid, and throws a {@code ClassCastException} if it is not. If
1051 * this method succeeds, it always returns a reference to this class object.
1053 * <p>This method is useful when a client needs to "narrow" the type of
1054 * a {@code Class} object to pass it to an API that restricts the
1055 * {@code Class} objects that it is willing to accept. A cast would
1056 * generate a compile-time warning, as the correctness of the cast
1057 * could not be checked at runtime (because generic types are implemented
1060 * @return this {@code Class} object, cast to represent a subclass of
1061 * the specified class object.
1062 * @throws ClassCastException if this {@code Class} object does not
1063 * represent a subclass of the specified class (here "subclass" includes
1064 * the class itself).
1067 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
1068 if (clazz.isAssignableFrom(this))
1069 return (Class<? extends U>) this;
1071 throw new ClassCastException(this.toString());
1074 @JavaScriptBody(args = { "self", "ac" },
1077 + " return self.anno['L' + ac.jvmName + ';'];"
1078 + "} else return null;"
1080 private Object getAnnotationData(Class<?> annotationClass) {
1081 throw new UnsupportedOperationException();
1084 * @throws NullPointerException {@inheritDoc}
1087 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
1088 Object data = getAnnotationData(annotationClass);
1089 return data == null ? null : AnnotationImpl.create(annotationClass, data);
1093 * @throws NullPointerException {@inheritDoc}
1096 @JavaScriptBody(args = { "self", "ac" },
1097 body = "if (self.anno && self.anno['L' + ac.jvmName + ';']) { return true; }"
1098 + "else return false;"
1100 public boolean isAnnotationPresent(
1101 Class<? extends Annotation> annotationClass) {
1102 if (annotationClass == null)
1103 throw new NullPointerException();
1105 return getAnnotation(annotationClass) != null;
1108 @JavaScriptBody(args = "self", body = "return self.anno;")
1109 private Object getAnnotationData() {
1110 throw new UnsupportedOperationException();
1116 public Annotation[] getAnnotations() {
1117 Object data = getAnnotationData();
1118 return data == null ? new Annotation[0] : AnnotationImpl.create(data);
1124 public Annotation[] getDeclaredAnnotations() {
1125 throw new UnsupportedOperationException();
1128 @JavaScriptBody(args = "type", body = ""
1129 + "var c = vm.java_lang_Class(true);"
1130 + "c.jvmName = type;"
1131 + "c.primitive = true;"
1134 native static Class getPrimitiveClass(String type);
1136 public boolean desiredAssertionStatus() {