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.ByteArrayInputStream;
29 import org.apidesign.bck2brwsr.emul.reflect.AnnotationImpl;
30 import java.io.InputStream;
31 import java.lang.annotation.Annotation;
32 import java.lang.reflect.Constructor;
33 import java.lang.reflect.Field;
34 import java.lang.reflect.Method;
35 import java.lang.reflect.TypeVariable;
37 import org.apidesign.bck2brwsr.core.JavaScriptBody;
38 import org.apidesign.bck2brwsr.emul.reflect.MethodImpl;
41 * Instances of the class {@code Class} represent classes and
42 * interfaces in a running Java application. An enum is a kind of
43 * class and an annotation is a kind of interface. Every array also
44 * belongs to a class that is reflected as a {@code Class} object
45 * that is shared by all arrays with the same element type and number
46 * of dimensions. The primitive Java types ({@code boolean},
47 * {@code byte}, {@code char}, {@code short},
48 * {@code int}, {@code long}, {@code float}, and
49 * {@code double}), and the keyword {@code void} are also
50 * represented as {@code Class} objects.
52 * <p> {@code Class} has no public constructor. Instead {@code Class}
53 * objects are constructed automatically by the Java Virtual Machine as classes
54 * are loaded and by calls to the {@code defineClass} method in the class
57 * <p> The following example uses a {@code Class} object to print the
58 * class name of an object:
60 * <p> <blockquote><pre>
61 * void printClassName(Object obj) {
62 * System.out.println("The class of " + obj +
63 * " is " + obj.getClass().getName());
67 * <p> It is also possible to get the {@code Class} object for a named
68 * type (or for void) using a class literal. See Section 15.8.2 of
69 * <cite>The Java™ Language Specification</cite>.
73 * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
76 * @param <T> the type of the class modeled by this {@code Class}
77 * object. For example, the type of {@code String.class} is {@code
78 * Class<String>}. Use {@code Class<?>} if the class being modeled is
82 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
86 class Class<T> implements java.io.Serializable,
87 java.lang.reflect.GenericDeclaration,
88 java.lang.reflect.Type,
89 java.lang.reflect.AnnotatedElement {
90 private static final int ANNOTATION= 0x00002000;
91 private static final int ENUM = 0x00004000;
92 private static final int SYNTHETIC = 0x00001000;
95 * Constructor. Only the Java Virtual Machine creates Class
102 * Converts the object to a string. The string representation is the
103 * string "class" or "interface", followed by a space, and then by the
104 * fully qualified name of the class in the format returned by
105 * {@code getName}. If this {@code Class} object represents a
106 * primitive type, this method returns the name of the primitive type. If
107 * this {@code Class} object represents void this method returns
110 * @return a string representation of this class object.
112 public String toString() {
113 return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
119 * Returns the {@code Class} object associated with the class or
120 * interface with the given string name. Invoking this method is
124 * {@code Class.forName(className, true, currentLoader)}
127 * where {@code currentLoader} denotes the defining class loader of
130 * <p> For example, the following code fragment returns the
131 * runtime {@code Class} descriptor for the class named
132 * {@code java.lang.Thread}:
135 * {@code Class t = Class.forName("java.lang.Thread")}
138 * A call to {@code forName("X")} causes the class named
139 * {@code X} to be initialized.
141 * @param className the fully qualified name of the desired class.
142 * @return the {@code Class} object for the class with the
144 * @exception LinkageError if the linkage fails
145 * @exception ExceptionInInitializerError if the initialization provoked
146 * by this method fails
147 * @exception ClassNotFoundException if the class cannot be located
149 public static Class<?> forName(String className)
150 throws ClassNotFoundException {
151 if (className.startsWith("[")) {
152 Class<?> arrType = defineArray(className);
153 Class<?> c = arrType;
154 while (c != null && c.isArray()) {
155 c = c.getComponentType0(); // verify component type is sane
160 Class<?> c = loadCls(className, className.replace('.', '_'));
162 throw new ClassNotFoundException(className);
165 } catch (Throwable ex) {
166 throw new ClassNotFoundException(className, ex);
172 * Returns the {@code Class} object associated with the class or
173 * interface with the given string name, using the given class loader.
174 * Given the fully qualified name for a class or interface (in the same
175 * format returned by {@code getName}) this method attempts to
176 * locate, load, and link the class or interface. The specified class
177 * loader is used to load the class or interface. If the parameter
178 * {@code loader} is null, the class is loaded through the bootstrap
179 * class loader. The class is initialized only if the
180 * {@code initialize} parameter is {@code true} and if it has
181 * not been initialized earlier.
183 * <p> If {@code name} denotes a primitive type or void, an attempt
184 * will be made to locate a user-defined class in the unnamed package whose
185 * name is {@code name}. Therefore, this method cannot be used to
186 * obtain any of the {@code Class} objects representing primitive
189 * <p> If {@code name} denotes an array class, the component type of
190 * the array class is loaded but not initialized.
192 * <p> For example, in an instance method the expression:
195 * {@code Class.forName("Foo")}
201 * {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
204 * Note that this method throws errors related to loading, linking or
205 * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
206 * Java Language Specification</em>.
207 * Note that this method does not check whether the requested class
208 * is accessible to its caller.
210 * <p> If the {@code loader} is {@code null}, and a security
211 * manager is present, and the caller's class loader is not null, then this
212 * method calls the security manager's {@code checkPermission} method
213 * with a {@code RuntimePermission("getClassLoader")} permission to
214 * ensure it's ok to access the bootstrap class loader.
216 * @param name fully qualified name of the desired class
217 * @param initialize whether the class must be initialized
218 * @param loader class loader from which the class must be loaded
219 * @return class object representing the desired class
221 * @exception LinkageError if the linkage fails
222 * @exception ExceptionInInitializerError if the initialization provoked
223 * by this method fails
224 * @exception ClassNotFoundException if the class cannot be located by
225 * the specified class loader
227 * @see java.lang.Class#forName(String)
228 * @see java.lang.ClassLoader
231 public static Class<?> forName(String name, boolean initialize,
233 throws ClassNotFoundException
235 return forName(name);
238 @JavaScriptBody(args = {"n", "c" }, body =
240 + " if (vm.loadClass) {\n"
241 + " vm.loadClass(n);\n"
243 + " if (!vm[c]) return null;\n"
246 + "return vm[c].$class;"
248 private static native Class<?> loadCls(String n, String c);
252 * Creates a new instance of the class represented by this {@code Class}
253 * object. The class is instantiated as if by a {@code new}
254 * expression with an empty argument list. The class is initialized if it
255 * has not already been initialized.
257 * <p>Note that this method propagates any exception thrown by the
258 * nullary constructor, including a checked exception. Use of
259 * this method effectively bypasses the compile-time exception
260 * checking that would otherwise be performed by the compiler.
262 * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
263 * Constructor.newInstance} method avoids this problem by wrapping
264 * any exception thrown by the constructor in a (checked) {@link
265 * java.lang.reflect.InvocationTargetException}.
267 * @return a newly allocated instance of the class represented by this
269 * @exception IllegalAccessException if the class or its nullary
270 * constructor is not accessible.
271 * @exception InstantiationException
272 * if this {@code Class} represents an abstract class,
273 * an interface, an array class, a primitive type, or void;
274 * or if the class has no nullary constructor;
275 * or if the instantiation fails for some other reason.
276 * @exception ExceptionInInitializerError if the initialization
277 * provoked by this method fails.
278 * @exception SecurityException
279 * If a security manager, <i>s</i>, is present and any of the
280 * following conditions is met:
285 * {@link SecurityManager#checkMemberAccess
286 * s.checkMemberAccess(this, Member.PUBLIC)} denies
287 * creation of new instances of this class
289 * <li> the caller's class loader is not the same as or an
290 * ancestor of the class loader for the current class and
291 * invocation of {@link SecurityManager#checkPackageAccess
292 * s.checkPackageAccess()} denies access to the package
298 @JavaScriptBody(args = { "self", "illegal" }, body =
299 "\nvar c = self.cnstr;"
300 + "\nif (c['cons__V']) {"
301 + "\n if ((c.cons__V.access & 0x1) != 0) {"
302 + "\n var inst = c();"
303 + "\n c.cons__V.call(inst);"
306 + "\n return illegal;"
310 private static native Object newInstance0(Class<?> self, Object illegal);
312 public T newInstance()
313 throws InstantiationException, IllegalAccessException
315 Object illegal = new Object();
316 Object inst = newInstance0(this, illegal);
318 throw new InstantiationException(getName());
320 if (inst == illegal) {
321 throw new IllegalAccessException();
327 * Determines if the specified {@code Object} is assignment-compatible
328 * with the object represented by this {@code Class}. This method is
329 * the dynamic equivalent of the Java language {@code instanceof}
330 * operator. The method returns {@code true} if the specified
331 * {@code Object} argument is non-null and can be cast to the
332 * reference type represented by this {@code Class} object without
333 * raising a {@code ClassCastException.} It returns {@code false}
336 * <p> Specifically, if this {@code Class} object represents a
337 * declared class, this method returns {@code true} if the specified
338 * {@code Object} argument is an instance of the represented class (or
339 * of any of its subclasses); it returns {@code false} otherwise. If
340 * this {@code Class} object represents an array class, this method
341 * returns {@code true} if the specified {@code Object} argument
342 * can be converted to an object of the array class by an identity
343 * conversion or by a widening reference conversion; it returns
344 * {@code false} otherwise. If this {@code Class} object
345 * represents an interface, this method returns {@code true} if the
346 * class or any superclass of the specified {@code Object} argument
347 * implements this interface; it returns {@code false} otherwise. If
348 * this {@code Class} object represents a primitive type, this method
349 * returns {@code false}.
351 * @param obj the object to check
352 * @return true if {@code obj} is an instance of this class
356 public boolean isInstance(Object obj) {
361 return isAssignableFrom(obj.getClass());
364 String prop = "$instOf_" + getName().replace('.', '_');
365 return hasProperty(obj, prop);
368 @JavaScriptBody(args = { "who", "prop" }, body =
369 "if (who[prop]) return true; else return false;"
371 private static native boolean hasProperty(Object who, String prop);
375 * Determines if the class or interface represented by this
376 * {@code Class} object is either the same as, or is a superclass or
377 * superinterface of, the class or interface represented by the specified
378 * {@code Class} parameter. It returns {@code true} if so;
379 * otherwise it returns {@code false}. If this {@code Class}
380 * object represents a primitive type, this method returns
381 * {@code true} if the specified {@code Class} parameter is
382 * exactly this {@code Class} object; otherwise it returns
385 * <p> Specifically, this method tests whether the type represented by the
386 * specified {@code Class} parameter can be converted to the type
387 * represented by this {@code Class} object via an identity conversion
388 * or via a widening reference conversion. See <em>The Java Language
389 * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
391 * @param cls the {@code Class} object to be checked
392 * @return the {@code boolean} value indicating whether objects of the
393 * type {@code cls} can be assigned to objects of this class
394 * @exception NullPointerException if the specified Class parameter is
398 public boolean isAssignableFrom(Class<?> cls) {
404 final Class<?> cmpType = cls.getComponentType();
406 return this == cmpType;
408 return cmpType != null && getComponentType().isAssignableFrom(cmpType);
413 if (cls.isPrimitive()) {
416 String prop = "$instOf_" + getName().replace('.', '_');
417 return hasCnstrProperty(cls, prop);
421 @JavaScriptBody(args = { "who", "prop" }, body =
422 "if (who.cnstr.prototype[prop]) return true; else return false;"
424 private static native boolean hasCnstrProperty(Object who, String prop);
428 * Determines if the specified {@code Class} object represents an
431 * @return {@code true} if this object represents an interface;
432 * {@code false} otherwise.
434 public boolean isInterface() {
435 return (getAccess() & 0x200) != 0;
438 @JavaScriptBody(args = {}, body = "return this.access;")
439 private native int getAccess();
443 * Determines if this {@code Class} object represents an array class.
445 * @return {@code true} if this object represents an array class;
446 * {@code false} otherwise.
449 public boolean isArray() {
450 return hasProperty(this, "array"); // NOI18N
455 * Determines if the specified {@code Class} object represents a
458 * <p> There are nine predefined {@code Class} objects to represent
459 * the eight primitive types and void. These are created by the Java
460 * Virtual Machine, and have the same names as the primitive types that
461 * they represent, namely {@code boolean}, {@code byte},
462 * {@code char}, {@code short}, {@code int},
463 * {@code long}, {@code float}, and {@code double}.
465 * <p> These objects may only be accessed via the following public static
466 * final variables, and are the only {@code Class} objects for which
467 * this method returns {@code true}.
469 * @return true if and only if this class represents a primitive type
471 * @see java.lang.Boolean#TYPE
472 * @see java.lang.Character#TYPE
473 * @see java.lang.Byte#TYPE
474 * @see java.lang.Short#TYPE
475 * @see java.lang.Integer#TYPE
476 * @see java.lang.Long#TYPE
477 * @see java.lang.Float#TYPE
478 * @see java.lang.Double#TYPE
479 * @see java.lang.Void#TYPE
482 @JavaScriptBody(args = {}, body =
483 "if (this.primitive) return true;"
484 + "else return false;"
486 public native boolean isPrimitive();
489 * Returns true if this {@code Class} object represents an annotation
490 * type. Note that if this method returns true, {@link #isInterface()}
491 * would also return true, as all annotation types are also interfaces.
493 * @return {@code true} if this class object represents an annotation
494 * type; {@code false} otherwise
497 public boolean isAnnotation() {
498 return (getModifiers() & ANNOTATION) != 0;
502 * Returns {@code true} if this class is a synthetic class;
503 * returns {@code false} otherwise.
504 * @return {@code true} if and only if this class is a synthetic class as
505 * defined by the Java Language Specification.
508 public boolean isSynthetic() {
509 return (getModifiers() & SYNTHETIC) != 0;
513 * Returns the name of the entity (class, interface, array class,
514 * primitive type, or void) represented by this {@code Class} object,
515 * as a {@code String}.
517 * <p> If this class object represents a reference type that is not an
518 * array type then the binary name of the class is returned, as specified
520 * <cite>The Java™ Language Specification</cite>.
522 * <p> If this class object represents a primitive type or void, then the
523 * name returned is a {@code String} equal to the Java language
524 * keyword corresponding to the primitive type or void.
526 * <p> If this class object represents a class of arrays, then the internal
527 * form of the name consists of the name of the element type preceded by
528 * one or more '{@code [}' characters representing the depth of the array
529 * nesting. The encoding of element type names is as follows:
531 * <blockquote><table summary="Element types and encodings">
532 * <tr><th> Element Type <th> <th> Encoding
533 * <tr><td> boolean <td> <td align=center> Z
534 * <tr><td> byte <td> <td align=center> B
535 * <tr><td> char <td> <td align=center> C
536 * <tr><td> class or interface
537 * <td> <td align=center> L<i>classname</i>;
538 * <tr><td> double <td> <td align=center> D
539 * <tr><td> float <td> <td align=center> F
540 * <tr><td> int <td> <td align=center> I
541 * <tr><td> long <td> <td align=center> J
542 * <tr><td> short <td> <td align=center> S
543 * </table></blockquote>
545 * <p> The class or interface name <i>classname</i> is the binary name of
546 * the class specified above.
550 * String.class.getName()
551 * returns "java.lang.String"
552 * byte.class.getName()
554 * (new Object[3]).getClass().getName()
555 * returns "[Ljava.lang.Object;"
556 * (new int[3][4][5][6][7][8][9]).getClass().getName()
558 * </pre></blockquote>
560 * @return the name of the class or interface
561 * represented by this object.
563 public String getName() {
564 return jvmName().replace('/', '.');
567 @JavaScriptBody(args = {}, body = "return this.jvmName;")
568 private native String jvmName();
572 * Returns an array of {@code TypeVariable} objects that represent the
573 * type variables declared by the generic declaration represented by this
574 * {@code GenericDeclaration} object, in declaration order. Returns an
575 * array of length 0 if the underlying generic declaration declares no type
578 * @return an array of {@code TypeVariable} objects that represent
579 * the type variables declared by this generic declaration
580 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
581 * signature of this generic declaration does not conform to
582 * the format specified in
583 * <cite>The Java™ Virtual Machine Specification</cite>
586 public TypeVariable<Class<T>>[] getTypeParameters() {
587 throw new UnsupportedOperationException();
591 * Returns the {@code Class} representing the superclass of the entity
592 * (class, interface, primitive type or void) represented by this
593 * {@code Class}. If this {@code Class} represents either the
594 * {@code Object} class, an interface, a primitive type, or void, then
595 * null is returned. If this object represents an array class then the
596 * {@code Class} object representing the {@code Object} class is
599 * @return the superclass of the class represented by this object.
601 @JavaScriptBody(args = {}, body = "return this.superclass;")
602 public native Class<? super T> getSuperclass();
605 * Returns the Java language modifiers for this class or interface, encoded
606 * in an integer. The modifiers consist of the Java Virtual Machine's
607 * constants for {@code public}, {@code protected},
608 * {@code private}, {@code final}, {@code static},
609 * {@code abstract} and {@code interface}; they should be decoded
610 * using the methods of class {@code Modifier}.
612 * <p> If the underlying class is an array class, then its
613 * {@code public}, {@code private} and {@code protected}
614 * modifiers are the same as those of its component type. If this
615 * {@code Class} represents a primitive type or void, its
616 * {@code public} modifier is always {@code true}, and its
617 * {@code protected} and {@code private} modifiers are always
618 * {@code false}. If this object represents an array class, a
619 * primitive type or void, then its {@code final} modifier is always
620 * {@code true} and its interface modifier is always
621 * {@code false}. The values of its other modifiers are not determined
622 * by this specification.
624 * <p> The modifier encodings are defined in <em>The Java Virtual Machine
625 * Specification</em>, table 4.1.
627 * @return the {@code int} representing the modifiers for this class
628 * @see java.lang.reflect.Modifier
631 public int getModifiers() {
637 * Returns the simple name of the underlying class as given in the
638 * source code. Returns an empty string if the underlying class is
641 * <p>The simple name of an array is the simple name of the
642 * component type with "[]" appended. In particular the simple
643 * name of an array whose component type is anonymous is "[]".
645 * @return the simple name of the underlying class
648 public String getSimpleName() {
650 return getComponentType().getSimpleName()+"[]";
652 String simpleName = getSimpleBinaryName();
653 if (simpleName == null) { // top level class
654 simpleName = getName();
655 return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
657 // According to JLS3 "Binary Compatibility" (13.1) the binary
658 // name of non-package classes (not top level) is the binary
659 // name of the immediately enclosing class followed by a '$' followed by:
660 // (for nested and inner classes): the simple name.
661 // (for local classes): 1 or more digits followed by the simple name.
662 // (for anonymous classes): 1 or more digits.
664 // Since getSimpleBinaryName() will strip the binary name of
665 // the immediatly enclosing class, we are now looking at a
666 // string that matches the regular expression "\$[0-9]*"
667 // followed by a simple name (considering the simple of an
668 // anonymous class to be the empty string).
670 // Remove leading "\$[0-9]*" from the name
671 int length = simpleName.length();
672 if (length < 1 || simpleName.charAt(0) != '$')
673 throw new IllegalStateException("Malformed class name");
675 while (index < length && isAsciiDigit(simpleName.charAt(index)))
677 // Eventually, this is the empty string iff this is an anonymous class
678 return simpleName.substring(index);
682 * Returns the "simple binary name" of the underlying class, i.e.,
683 * the binary name without the leading enclosing class name.
684 * Returns {@code null} if the underlying class is a top level
687 private String getSimpleBinaryName() {
688 Class<?> enclosingClass = null; // XXX getEnclosingClass();
689 if (enclosingClass == null) // top level class
691 // Otherwise, strip the enclosing class' name
693 return getName().substring(enclosingClass.getName().length());
694 } catch (IndexOutOfBoundsException ex) {
695 throw new IllegalStateException("Malformed class name");
700 * Returns an array containing {@code Field} objects reflecting all
701 * the accessible public fields of the class or interface represented by
702 * this {@code Class} object. The elements in the array returned are
703 * not sorted and are not in any particular order. This method returns an
704 * array of length 0 if the class or interface has no accessible public
705 * fields, or if it represents an array class, a primitive type, or void.
707 * <p> Specifically, if this {@code Class} object represents a class,
708 * this method returns the public fields of this class and of all its
709 * superclasses. If this {@code Class} object represents an
710 * interface, this method returns the fields of this interface and of all
711 * its superinterfaces.
713 * <p> The implicit length field for array class is not reflected by this
714 * method. User code should use the methods of class {@code Array} to
717 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
719 * @return the array of {@code Field} objects representing the
721 * @exception SecurityException
722 * If a security manager, <i>s</i>, is present and any of the
723 * following conditions is met:
728 * {@link SecurityManager#checkMemberAccess
729 * s.checkMemberAccess(this, Member.PUBLIC)} denies
730 * access to the fields within this class
732 * <li> the caller's class loader is not the same as or an
733 * ancestor of the class loader for the current class and
734 * invocation of {@link SecurityManager#checkPackageAccess
735 * s.checkPackageAccess()} denies access to the package
742 public Field[] getFields() throws SecurityException {
743 throw new SecurityException();
747 * Returns an array containing {@code Method} objects reflecting all
748 * the public <em>member</em> methods of the class or interface represented
749 * by this {@code Class} object, including those declared by the class
750 * or interface and those inherited from superclasses and
751 * superinterfaces. Array classes return all the (public) member methods
752 * inherited from the {@code Object} class. The elements in the array
753 * returned are not sorted and are not in any particular order. This
754 * method returns an array of length 0 if this {@code Class} object
755 * represents a class or interface that has no public member methods, or if
756 * this {@code Class} object represents a primitive type or void.
758 * <p> The class initialization method {@code <clinit>} is not
759 * included in the returned array. If the class declares multiple public
760 * member methods with the same parameter types, they are all included in
761 * the returned array.
763 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
765 * @return the array of {@code Method} objects representing the
766 * public methods of this class
767 * @exception SecurityException
768 * If a security manager, <i>s</i>, is present and any of the
769 * following conditions is met:
774 * {@link SecurityManager#checkMemberAccess
775 * s.checkMemberAccess(this, Member.PUBLIC)} denies
776 * access to the methods within this class
778 * <li> the caller's class loader is not the same as or an
779 * ancestor of the class loader for the current class and
780 * invocation of {@link SecurityManager#checkPackageAccess
781 * s.checkPackageAccess()} denies access to the package
788 public Method[] getMethods() throws SecurityException {
789 return MethodImpl.findMethods(this, 0x01);
793 * Returns a {@code Field} object that reflects the specified public
794 * member field of the class or interface represented by this
795 * {@code Class} object. The {@code name} parameter is a
796 * {@code String} specifying the simple name of the desired field.
798 * <p> The field to be reflected is determined by the algorithm that
799 * follows. Let C be the class represented by this object:
801 * <LI> If C declares a public field with the name specified, that is the
802 * field to be reflected.</LI>
803 * <LI> If no field was found in step 1 above, this algorithm is applied
804 * recursively to each direct superinterface of C. The direct
805 * superinterfaces are searched in the order they were declared.</LI>
806 * <LI> If no field was found in steps 1 and 2 above, and C has a
807 * superclass S, then this algorithm is invoked recursively upon S.
808 * If C has no superclass, then a {@code NoSuchFieldException}
812 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
814 * @param name the field name
815 * @return the {@code Field} object of this class specified by
817 * @exception NoSuchFieldException if a field with the specified name is
819 * @exception NullPointerException if {@code name} is {@code null}
820 * @exception SecurityException
821 * If a security manager, <i>s</i>, is present and any of the
822 * following conditions is met:
827 * {@link SecurityManager#checkMemberAccess
828 * s.checkMemberAccess(this, Member.PUBLIC)} denies
829 * access to the field
831 * <li> the caller's class loader is not the same as or an
832 * ancestor of the class loader for the current class and
833 * invocation of {@link SecurityManager#checkPackageAccess
834 * s.checkPackageAccess()} denies access to the package
841 public Field getField(String name)
842 throws SecurityException {
843 throw new SecurityException();
848 * Returns a {@code Method} object that reflects the specified public
849 * member method of the class or interface represented by this
850 * {@code Class} object. The {@code name} parameter is a
851 * {@code String} specifying the simple name of the desired method. The
852 * {@code parameterTypes} parameter is an array of {@code Class}
853 * objects that identify the method's formal parameter types, in declared
854 * order. If {@code parameterTypes} is {@code null}, it is
855 * treated as if it were an empty array.
857 * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
858 * {@code NoSuchMethodException} is raised. Otherwise, the method to
859 * be reflected is determined by the algorithm that follows. Let C be the
860 * class represented by this object:
862 * <LI> C is searched for any <I>matching methods</I>. If no matching
863 * method is found, the algorithm of step 1 is invoked recursively on
864 * the superclass of C.</LI>
865 * <LI> If no method was found in step 1 above, the superinterfaces of C
866 * are searched for a matching method. If any such method is found, it
870 * To find a matching method in a class C: If C declares exactly one
871 * public method with the specified name and exactly the same formal
872 * parameter types, that is the method reflected. If more than one such
873 * method is found in C, and one of these methods has a return type that is
874 * more specific than any of the others, that method is reflected;
875 * otherwise one of the methods is chosen arbitrarily.
877 * <p>Note that there may be more than one matching method in a
878 * class because while the Java language forbids a class to
879 * declare multiple methods with the same signature but different
880 * return types, the Java virtual machine does not. This
881 * increased flexibility in the virtual machine can be used to
882 * implement various language features. For example, covariant
883 * returns can be implemented with {@linkplain
884 * java.lang.reflect.Method#isBridge bridge methods}; the bridge
885 * method and the method being overridden would have the same
886 * signature but different return types.
888 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
890 * @param name the name of the method
891 * @param parameterTypes the list of parameters
892 * @return the {@code Method} object that matches the specified
893 * {@code name} and {@code parameterTypes}
894 * @exception NoSuchMethodException if a matching method is not found
895 * or if the name is "<init>"or "<clinit>".
896 * @exception NullPointerException if {@code name} is {@code null}
897 * @exception SecurityException
898 * If a security manager, <i>s</i>, is present and any of the
899 * following conditions is met:
904 * {@link SecurityManager#checkMemberAccess
905 * s.checkMemberAccess(this, Member.PUBLIC)} denies
906 * access to the method
908 * <li> the caller's class loader is not the same as or an
909 * ancestor of the class loader for the current class and
910 * invocation of {@link SecurityManager#checkPackageAccess
911 * s.checkPackageAccess()} denies access to the package
918 public Method getMethod(String name, Class<?>... parameterTypes)
919 throws SecurityException, NoSuchMethodException {
920 Method m = MethodImpl.findMethod(this, name, parameterTypes);
922 StringBuilder sb = new StringBuilder();
923 sb.append(getName()).append('.').append(name).append('(');
925 for (int i = 0; i < parameterTypes.length; i++) {
926 sb.append(sep).append(parameterTypes[i].getName());
930 throw new NoSuchMethodException(sb.toString());
936 * Returns an array of {@code Method} objects reflecting all the
937 * methods declared by the class or interface represented by this
938 * {@code Class} object. This includes public, protected, default
939 * (package) access, and private methods, but excludes inherited methods.
940 * The elements in the array returned are not sorted and are not in any
941 * particular order. This method returns an array of length 0 if the class
942 * or interface declares no methods, or if this {@code Class} object
943 * represents a primitive type, an array class, or void. The class
944 * initialization method {@code <clinit>} is not included in the
945 * returned array. If the class declares multiple public member methods
946 * with the same parameter types, they are all included in the returned
949 * <p> See <em>The Java Language Specification</em>, section 8.2.
951 * @return the array of {@code Method} objects representing all the
952 * declared methods of this class
953 * @exception SecurityException
954 * If a security manager, <i>s</i>, is present and any of the
955 * following conditions is met:
960 * {@link SecurityManager#checkMemberAccess
961 * s.checkMemberAccess(this, Member.DECLARED)} denies
962 * access to the declared methods within this class
964 * <li> the caller's class loader is not the same as or an
965 * ancestor of the class loader for the current class and
966 * invocation of {@link SecurityManager#checkPackageAccess
967 * s.checkPackageAccess()} denies access to the package
974 public Method[] getDeclaredMethods() throws SecurityException {
975 throw new SecurityException();
979 * Returns an array of {@code Field} objects reflecting all the fields
980 * declared by the class or interface represented by this
981 * {@code Class} object. This includes public, protected, default
982 * (package) access, and private fields, but excludes inherited fields.
983 * The elements in the array returned are not sorted and are not in any
984 * particular order. This method returns an array of length 0 if the class
985 * or interface declares no fields, or if this {@code Class} object
986 * represents a primitive type, an array class, or void.
988 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
990 * @return the array of {@code Field} objects representing all the
991 * declared fields of this class
992 * @exception SecurityException
993 * If a security manager, <i>s</i>, is present and any of the
994 * following conditions is met:
999 * {@link SecurityManager#checkMemberAccess
1000 * s.checkMemberAccess(this, Member.DECLARED)} denies
1001 * access to the declared fields within this class
1003 * <li> the caller's class loader is not the same as or an
1004 * ancestor of the class loader for the current class and
1005 * invocation of {@link SecurityManager#checkPackageAccess
1006 * s.checkPackageAccess()} denies access to the package
1013 public Field[] getDeclaredFields() throws SecurityException {
1014 throw new SecurityException();
1018 * <b>Bck2Brwsr</b> emulation can only seek public methods, otherwise it
1019 * throws a {@code SecurityException}.
1021 * Returns a {@code Method} object that reflects the specified
1022 * declared method of the class or interface represented by this
1023 * {@code Class} object. The {@code name} parameter is a
1024 * {@code String} that specifies the simple name of the desired
1025 * method, and the {@code parameterTypes} parameter is an array of
1026 * {@code Class} objects that identify the method's formal parameter
1027 * types, in declared order. If more than one method with the same
1028 * parameter types is declared in a class, and one of these methods has a
1029 * return type that is more specific than any of the others, that method is
1030 * returned; otherwise one of the methods is chosen arbitrarily. If the
1031 * name is "<init>"or "<clinit>" a {@code NoSuchMethodException}
1034 * @param name the name of the method
1035 * @param parameterTypes the parameter array
1036 * @return the {@code Method} object for the method of this class
1037 * matching the specified name and parameters
1038 * @exception NoSuchMethodException if a matching method is not found.
1039 * @exception NullPointerException if {@code name} is {@code null}
1040 * @exception SecurityException
1041 * If a security manager, <i>s</i>, is present and any of the
1042 * following conditions is met:
1046 * <li> invocation of
1047 * {@link SecurityManager#checkMemberAccess
1048 * s.checkMemberAccess(this, Member.DECLARED)} denies
1049 * access to the declared method
1051 * <li> the caller's class loader is not the same as or an
1052 * ancestor of the class loader for the current class and
1053 * invocation of {@link SecurityManager#checkPackageAccess
1054 * s.checkPackageAccess()} denies access to the package
1061 public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
1062 throws NoSuchMethodException, SecurityException {
1064 return getMethod(name, parameterTypes);
1065 } catch (NoSuchMethodException ex) {
1066 throw new SecurityException();
1071 * Returns a {@code Field} object that reflects the specified declared
1072 * field of the class or interface represented by this {@code Class}
1073 * object. The {@code name} parameter is a {@code String} that
1074 * specifies the simple name of the desired field. Note that this method
1075 * will not reflect the {@code length} field of an array class.
1077 * @param name the name of the field
1078 * @return the {@code Field} object for the specified field in this
1080 * @exception NoSuchFieldException if a field with the specified name is
1082 * @exception NullPointerException if {@code name} is {@code null}
1083 * @exception SecurityException
1084 * If a security manager, <i>s</i>, is present and any of the
1085 * following conditions is met:
1089 * <li> invocation of
1090 * {@link SecurityManager#checkMemberAccess
1091 * s.checkMemberAccess(this, Member.DECLARED)} denies
1092 * access to the declared field
1094 * <li> the caller's class loader is not the same as or an
1095 * ancestor of the class loader for the current class and
1096 * invocation of {@link SecurityManager#checkPackageAccess
1097 * s.checkPackageAccess()} denies access to the package
1104 public Field getDeclaredField(String name)
1105 throws SecurityException {
1106 throw new SecurityException();
1110 * Returns an array containing {@code Constructor} objects reflecting
1111 * all the public constructors of the class represented by this
1112 * {@code Class} object. An array of length 0 is returned if the
1113 * class has no public constructors, or if the class is an array class, or
1114 * if the class reflects a primitive type or void.
1116 * Note that while this method returns an array of {@code
1117 * Constructor<T>} objects (that is an array of constructors from
1118 * this class), the return type of this method is {@code
1119 * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
1120 * might be expected. This less informative return type is
1121 * necessary since after being returned from this method, the
1122 * array could be modified to hold {@code Constructor} objects for
1123 * different classes, which would violate the type guarantees of
1124 * {@code Constructor<T>[]}.
1126 * @return the array of {@code Constructor} objects representing the
1127 * public constructors of this class
1128 * @exception SecurityException
1129 * If a security manager, <i>s</i>, is present and any of the
1130 * following conditions is met:
1134 * <li> invocation of
1135 * {@link SecurityManager#checkMemberAccess
1136 * s.checkMemberAccess(this, Member.PUBLIC)} denies
1137 * access to the constructors within this class
1139 * <li> the caller's class loader is not the same as or an
1140 * ancestor of the class loader for the current class and
1141 * invocation of {@link SecurityManager#checkPackageAccess
1142 * s.checkPackageAccess()} denies access to the package
1149 public Constructor<?>[] getConstructors() throws SecurityException {
1150 return MethodImpl.findConstructors(this, 0x01);
1154 * Returns a {@code Constructor} object that reflects the specified
1155 * public constructor of the class represented by this {@code Class}
1156 * object. The {@code parameterTypes} parameter is an array of
1157 * {@code Class} objects that identify the constructor's formal
1158 * parameter types, in declared order.
1160 * If this {@code Class} object represents an inner class
1161 * declared in a non-static context, the formal parameter types
1162 * include the explicit enclosing instance as the first parameter.
1164 * <p> The constructor to reflect is the public constructor of the class
1165 * represented by this {@code Class} object whose formal parameter
1166 * types match those specified by {@code parameterTypes}.
1168 * @param parameterTypes the parameter array
1169 * @return the {@code Constructor} object of the public constructor that
1170 * matches the specified {@code parameterTypes}
1171 * @exception NoSuchMethodException if a matching method is not found.
1172 * @exception SecurityException
1173 * If a security manager, <i>s</i>, is present and any of the
1174 * following conditions is met:
1178 * <li> invocation of
1179 * {@link SecurityManager#checkMemberAccess
1180 * s.checkMemberAccess(this, Member.PUBLIC)} denies
1181 * access to the constructor
1183 * <li> the caller's class loader is not the same as or an
1184 * ancestor of the class loader for the current class and
1185 * invocation of {@link SecurityManager#checkPackageAccess
1186 * s.checkPackageAccess()} denies access to the package
1193 public Constructor<T> getConstructor(Class<?>... parameterTypes)
1194 throws NoSuchMethodException, SecurityException {
1195 Constructor c = MethodImpl.findConstructor(this, parameterTypes);
1197 StringBuilder sb = new StringBuilder();
1198 sb.append(getName()).append('(');
1200 for (int i = 0; i < parameterTypes.length; i++) {
1201 sb.append(sep).append(parameterTypes[i].getName());
1205 throw new NoSuchMethodException(sb.toString());
1211 * Returns an array of {@code Constructor} objects reflecting all the
1212 * constructors declared by the class represented by this
1213 * {@code Class} object. These are public, protected, default
1214 * (package) access, and private constructors. The elements in the array
1215 * returned are not sorted and are not in any particular order. If the
1216 * class has a default constructor, it is included in the returned array.
1217 * This method returns an array of length 0 if this {@code Class}
1218 * object represents an interface, a primitive type, an array class, or
1221 * <p> See <em>The Java Language Specification</em>, section 8.2.
1223 * @return the array of {@code Constructor} objects representing all the
1224 * declared constructors of this class
1225 * @exception SecurityException
1226 * If a security manager, <i>s</i>, is present and any of the
1227 * following conditions is met:
1231 * <li> invocation of
1232 * {@link SecurityManager#checkMemberAccess
1233 * s.checkMemberAccess(this, Member.DECLARED)} denies
1234 * access to the declared constructors within this class
1236 * <li> the caller's class loader is not the same as or an
1237 * ancestor of the class loader for the current class and
1238 * invocation of {@link SecurityManager#checkPackageAccess
1239 * s.checkPackageAccess()} denies access to the package
1246 public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
1247 throw new SecurityException();
1250 * Returns a {@code Constructor} object that reflects the specified
1251 * constructor of the class or interface represented by this
1252 * {@code Class} object. The {@code parameterTypes} parameter is
1253 * an array of {@code Class} objects that identify the constructor's
1254 * formal parameter types, in declared order.
1256 * If this {@code Class} object represents an inner class
1257 * declared in a non-static context, the formal parameter types
1258 * include the explicit enclosing instance as the first parameter.
1260 * @param parameterTypes the parameter array
1261 * @return The {@code Constructor} object for the constructor with the
1262 * specified parameter list
1263 * @exception NoSuchMethodException if a matching method is not found.
1264 * @exception SecurityException
1265 * If a security manager, <i>s</i>, is present and any of the
1266 * following conditions is met:
1270 * <li> invocation of
1271 * {@link SecurityManager#checkMemberAccess
1272 * s.checkMemberAccess(this, Member.DECLARED)} denies
1273 * access to the declared constructor
1275 * <li> the caller's class loader is not the same as or an
1276 * ancestor of the class loader for the current class and
1277 * invocation of {@link SecurityManager#checkPackageAccess
1278 * s.checkPackageAccess()} denies access to the package
1285 public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
1286 throws NoSuchMethodException, SecurityException {
1287 return getConstructor(parameterTypes);
1292 * Character.isDigit answers {@code true} to some non-ascii
1293 * digits. This one does not.
1295 private static boolean isAsciiDigit(char c) {
1296 return '0' <= c && c <= '9';
1300 * Returns the canonical name of the underlying class as
1301 * defined by the Java Language Specification. Returns null if
1302 * the underlying class does not have a canonical name (i.e., if
1303 * it is a local or anonymous class or an array whose component
1304 * type does not have a canonical name).
1305 * @return the canonical name of the underlying class if it exists, and
1306 * {@code null} otherwise.
1309 public String getCanonicalName() {
1311 String canonicalName = getComponentType().getCanonicalName();
1312 if (canonicalName != null)
1313 return canonicalName + "[]";
1317 // if (isLocalOrAnonymousClass())
1319 // Class<?> enclosingClass = getEnclosingClass();
1320 Class<?> enclosingClass = null;
1321 if (enclosingClass == null) { // top level class
1324 String enclosingName = enclosingClass.getCanonicalName();
1325 if (enclosingName == null)
1327 return enclosingName + "." + getSimpleName();
1332 * Finds a resource with a given name. The rules for searching resources
1333 * associated with a given class are implemented by the defining
1334 * {@linkplain ClassLoader class loader} of the class. This method
1335 * delegates to this object's class loader. If this object was loaded by
1336 * the bootstrap class loader, the method delegates to {@link
1337 * ClassLoader#getSystemResourceAsStream}.
1339 * <p> Before delegation, an absolute resource name is constructed from the
1340 * given resource name using this algorithm:
1344 * <li> If the {@code name} begins with a {@code '/'}
1345 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
1346 * portion of the {@code name} following the {@code '/'}.
1348 * <li> Otherwise, the absolute name is of the following form:
1351 * {@code modified_package_name/name}
1354 * <p> Where the {@code modified_package_name} is the package name of this
1355 * object with {@code '/'} substituted for {@code '.'}
1356 * (<tt>'\u002e'</tt>).
1360 * @param name name of the desired resource
1361 * @return A {@link java.io.InputStream} object or {@code null} if
1362 * no resource with this name is found
1363 * @throws NullPointerException If {@code name} is {@code null}
1366 public InputStream getResourceAsStream(String name) {
1367 name = resolveName(name);
1368 byte[] arr = getResourceAsStream0(name);
1369 return arr == null ? null : new ByteArrayInputStream(arr);
1372 @JavaScriptBody(args = "name", body =
1373 "return (vm.loadBytes) ? vm.loadBytes(name) : null;"
1375 private static native byte[] getResourceAsStream0(String name);
1378 * Finds a resource with a given name. The rules for searching resources
1379 * associated with a given class are implemented by the defining
1380 * {@linkplain ClassLoader class loader} of the class. This method
1381 * delegates to this object's class loader. If this object was loaded by
1382 * the bootstrap class loader, the method delegates to {@link
1383 * ClassLoader#getSystemResource}.
1385 * <p> Before delegation, an absolute resource name is constructed from the
1386 * given resource name using this algorithm:
1390 * <li> If the {@code name} begins with a {@code '/'}
1391 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
1392 * portion of the {@code name} following the {@code '/'}.
1394 * <li> Otherwise, the absolute name is of the following form:
1397 * {@code modified_package_name/name}
1400 * <p> Where the {@code modified_package_name} is the package name of this
1401 * object with {@code '/'} substituted for {@code '.'}
1402 * (<tt>'\u002e'</tt>).
1406 * @param name name of the desired resource
1407 * @return A {@link java.net.URL} object or {@code null} if no
1408 * resource with this name is found
1411 public java.net.URL getResource(String name) {
1412 InputStream is = getResourceAsStream(name);
1413 return is == null ? null : newResourceURL(URL.class, "res:/" + name, is);
1416 @JavaScriptBody(args = { "url", "spec", "is" }, body =
1417 "var u = url.cnstr(true);\n"
1418 + "u.constructor.cons__VLjava_lang_String_2Ljava_io_InputStream_2.call(u, spec, is);\n"
1421 private static native URL newResourceURL(Class<URL> url, String spec, InputStream is);
1424 * Add a package name prefix if the name is not absolute Remove leading "/"
1425 * if name is absolute
1427 private String resolveName(String name) {
1431 if (!name.startsWith("/")) {
1433 while (c.isArray()) {
1434 c = c.getComponentType();
1436 String baseName = c.getName();
1437 int index = baseName.lastIndexOf('.');
1439 name = baseName.substring(0, index).replace('.', '/')
1443 name = name.substring(1);
1449 * Returns the class loader for the class. Some implementations may use
1450 * null to represent the bootstrap class loader. This method will return
1451 * null in such implementations if this class was loaded by the bootstrap
1454 * <p> If a security manager is present, and the caller's class loader is
1455 * not null and the caller's class loader is not the same as or an ancestor of
1456 * the class loader for the class whose class loader is requested, then
1457 * this method calls the security manager's {@code checkPermission}
1458 * method with a {@code RuntimePermission("getClassLoader")}
1459 * permission to ensure it's ok to access the class loader for the class.
1462 * represents a primitive type or void, null is returned.
1464 * @return the class loader that loaded the class or interface
1465 * represented by this object.
1466 * @throws SecurityException
1467 * if a security manager exists and its
1468 * {@code checkPermission} method denies
1469 * access to the class loader for the class.
1470 * @see java.lang.ClassLoader
1471 * @see SecurityManager#checkPermission
1472 * @see java.lang.RuntimePermission
1474 public ClassLoader getClassLoader() {
1475 return ClassLoader.getSystemClassLoader();
1479 * Determines the interfaces implemented by the class or interface
1480 * represented by this object.
1482 * <p> If this object represents a class, the return value is an array
1483 * containing objects representing all interfaces implemented by the
1484 * class. The order of the interface objects in the array corresponds to
1485 * the order of the interface names in the {@code implements} clause
1486 * of the declaration of the class represented by this object. For
1487 * example, given the declaration:
1489 * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
1491 * suppose the value of {@code s} is an instance of
1492 * {@code Shimmer}; the value of the expression:
1494 * {@code s.getClass().getInterfaces()[0]}
1496 * is the {@code Class} object that represents interface
1497 * {@code FloorWax}; and the value of:
1499 * {@code s.getClass().getInterfaces()[1]}
1501 * is the {@code Class} object that represents interface
1502 * {@code DessertTopping}.
1504 * <p> If this object represents an interface, the array contains objects
1505 * representing all interfaces extended by the interface. The order of the
1506 * interface objects in the array corresponds to the order of the interface
1507 * names in the {@code extends} clause of the declaration of the
1508 * interface represented by this object.
1510 * <p> If this object represents a class or interface that implements no
1511 * interfaces, the method returns an array of length 0.
1513 * <p> If this object represents a primitive type or void, the method
1514 * returns an array of length 0.
1516 * @return an array of interfaces implemented by this class.
1518 public native Class<?>[] getInterfaces();
1521 * Returns the {@code Class} representing the component type of an
1522 * array. If this class does not represent an array class this method
1525 * @return the {@code Class} representing the component type of this
1526 * class if this class is an array
1527 * @see java.lang.reflect.Array
1530 public Class<?> getComponentType() {
1533 return getComponentType0();
1534 } catch (ClassNotFoundException cnfe) {
1535 throw new IllegalStateException(cnfe);
1541 private Class<?> getComponentType0() throws ClassNotFoundException {
1542 String n = getName().substring(1);
1543 switch (n.charAt(0)) {
1545 n = n.substring(1, n.length() - 1);
1546 return Class.forName(n);
1548 return Integer.TYPE;
1558 return Boolean.TYPE;
1564 return Character.TYPE;
1566 return defineArray(n);
1568 throw new ClassNotFoundException("Unknown component type of " + getName());
1572 @JavaScriptBody(args = { "sig" }, body =
1573 "if (!sig) sig = '[Ljava/lang/Object;';\n" +
1574 "var c = Array[sig];\n" +
1575 "if (c) return c;\n" +
1576 "c = vm.java_lang_Class(true);\n" +
1577 "c.jvmName = sig;\n" +
1578 "c.superclass = vm.java_lang_Object(false).$class;\n" +
1579 "c.array = true;\n" +
1580 "Array[sig] = c;\n" +
1583 private static native Class<?> defineArray(String sig);
1586 * Returns true if and only if this class was declared as an enum in the
1589 * @return true if and only if this class was declared as an enum in the
1593 public boolean isEnum() {
1594 // An enum must both directly extend java.lang.Enum and have
1595 // the ENUM bit set; classes for specialized enum constants
1596 // don't do the former.
1597 return (this.getModifiers() & ENUM) != 0 &&
1598 this.getSuperclass() == java.lang.Enum.class;
1602 * Casts an object to the class or interface represented
1603 * by this {@code Class} object.
1605 * @param obj the object to be cast
1606 * @return the object after casting, or null if obj is null
1608 * @throws ClassCastException if the object is not
1609 * null and is not assignable to the type T.
1613 public T cast(Object obj) {
1614 if (obj != null && !isInstance(obj))
1615 throw new ClassCastException(cannotCastMsg(obj));
1619 private String cannotCastMsg(Object obj) {
1620 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
1624 * Casts this {@code Class} object to represent a subclass of the class
1625 * represented by the specified class object. Checks that that the cast
1626 * is valid, and throws a {@code ClassCastException} if it is not. If
1627 * this method succeeds, it always returns a reference to this class object.
1629 * <p>This method is useful when a client needs to "narrow" the type of
1630 * a {@code Class} object to pass it to an API that restricts the
1631 * {@code Class} objects that it is willing to accept. A cast would
1632 * generate a compile-time warning, as the correctness of the cast
1633 * could not be checked at runtime (because generic types are implemented
1636 * @return this {@code Class} object, cast to represent a subclass of
1637 * the specified class object.
1638 * @throws ClassCastException if this {@code Class} object does not
1639 * represent a subclass of the specified class (here "subclass" includes
1640 * the class itself).
1643 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
1644 if (clazz.isAssignableFrom(this))
1645 return (Class<? extends U>) this;
1647 throw new ClassCastException(this.toString());
1650 @JavaScriptBody(args = { "ac" },
1653 + " return this.anno['L' + ac.jvmName + ';'];"
1654 + "} else return null;"
1656 private Object getAnnotationData(Class<?> annotationClass) {
1657 throw new UnsupportedOperationException();
1660 * @throws NullPointerException {@inheritDoc}
1663 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
1664 Object data = getAnnotationData(annotationClass);
1665 return data == null ? null : AnnotationImpl.create(annotationClass, data);
1669 * @throws NullPointerException {@inheritDoc}
1672 @JavaScriptBody(args = { "ac" },
1673 body = "if (this.anno && this.anno['L' + ac.jvmName + ';']) { return true; }"
1674 + "else return false;"
1676 public boolean isAnnotationPresent(
1677 Class<? extends Annotation> annotationClass) {
1678 if (annotationClass == null)
1679 throw new NullPointerException();
1681 return getAnnotation(annotationClass) != null;
1684 @JavaScriptBody(args = {}, body = "return this.anno;")
1685 private Object getAnnotationData() {
1686 throw new UnsupportedOperationException();
1692 public Annotation[] getAnnotations() {
1693 Object data = getAnnotationData();
1694 return data == null ? new Annotation[0] : AnnotationImpl.create(data);
1700 public Annotation[] getDeclaredAnnotations() {
1701 throw new UnsupportedOperationException();
1704 @JavaScriptBody(args = "type", body = ""
1705 + "var c = vm.java_lang_Class(true);"
1706 + "c.jvmName = type;"
1707 + "c.primitive = true;"
1710 native static Class getPrimitiveClass(String type);
1712 @JavaScriptBody(args = {}, body =
1713 "return vm.desiredAssertionStatus ? vm.desiredAssertionStatus : false;"
1715 public native boolean desiredAssertionStatus();