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.AnnotationImpl;
30 import java.io.InputStream;
31 import java.lang.annotation.Annotation;
32 import java.lang.reflect.Field;
33 import java.lang.reflect.Method;
34 import java.lang.reflect.TypeVariable;
35 import org.apidesign.bck2brwsr.core.JavaScriptBody;
36 import org.apidesign.bck2brwsr.emul.MethodImpl;
39 * Instances of the class {@code Class} represent classes and
40 * interfaces in a running Java application. An enum is a kind of
41 * class and an annotation is a kind of interface. Every array also
42 * belongs to a class that is reflected as a {@code Class} object
43 * that is shared by all arrays with the same element type and number
44 * of dimensions. The primitive Java types ({@code boolean},
45 * {@code byte}, {@code char}, {@code short},
46 * {@code int}, {@code long}, {@code float}, and
47 * {@code double}), and the keyword {@code void} are also
48 * represented as {@code Class} objects.
50 * <p> {@code Class} has no public constructor. Instead {@code Class}
51 * objects are constructed automatically by the Java Virtual Machine as classes
52 * are loaded and by calls to the {@code defineClass} method in the class
55 * <p> The following example uses a {@code Class} object to print the
56 * class name of an object:
58 * <p> <blockquote><pre>
59 * void printClassName(Object obj) {
60 * System.out.println("The class of " + obj +
61 * " is " + obj.getClass().getName());
65 * <p> It is also possible to get the {@code Class} object for a named
66 * type (or for void) using a class literal. See Section 15.8.2 of
67 * <cite>The Java™ Language Specification</cite>.
71 * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
74 * @param <T> the type of the class modeled by this {@code Class}
75 * object. For example, the type of {@code String.class} is {@code
76 * Class<String>}. Use {@code Class<?>} if the class being modeled is
80 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
84 class Class<T> implements java.io.Serializable,
85 java.lang.reflect.GenericDeclaration,
86 java.lang.reflect.Type,
87 java.lang.reflect.AnnotatedElement {
88 private static final int ANNOTATION= 0x00002000;
89 private static final int ENUM = 0x00004000;
90 private static final int SYNTHETIC = 0x00001000;
93 * Constructor. Only the Java Virtual Machine creates Class
100 * Converts the object to a string. The string representation is the
101 * string "class" or "interface", followed by a space, and then by the
102 * fully qualified name of the class in the format returned by
103 * {@code getName}. If this {@code Class} object represents a
104 * primitive type, this method returns the name of the primitive type. If
105 * this {@code Class} object represents void this method returns
108 * @return a string representation of this class object.
110 public String toString() {
111 return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
117 * Returns the {@code Class} object associated with the class or
118 * interface with the given string name. Invoking this method is
122 * {@code Class.forName(className, true, currentLoader)}
125 * where {@code currentLoader} denotes the defining class loader of
128 * <p> For example, the following code fragment returns the
129 * runtime {@code Class} descriptor for the class named
130 * {@code java.lang.Thread}:
133 * {@code Class t = Class.forName("java.lang.Thread")}
136 * A call to {@code forName("X")} causes the class named
137 * {@code X} to be initialized.
139 * @param className the fully qualified name of the desired class.
140 * @return the {@code Class} object for the class with the
142 * @exception LinkageError if the linkage fails
143 * @exception ExceptionInInitializerError if the initialization provoked
144 * by this method fails
145 * @exception ClassNotFoundException if the class cannot be located
147 public static Class<?> forName(String className)
148 throws ClassNotFoundException {
149 if (className.startsWith("[")) {
150 Class<?> arrType = defineArray(className);
151 Class<?> c = arrType;
152 while (c != null && c.isArray()) {
153 c = c.getComponentType0(); // verify component type is sane
157 Class<?> c = loadCls(className, className.replace('.', '_'));
159 throw new ClassNotFoundException(className);
164 @JavaScriptBody(args = {"n", "c" }, body =
165 "if (vm[c]) return vm[c].$class;\n"
166 + "if (vm.loadClass) {\n"
167 + " vm.loadClass(n);\n"
168 + " if (vm[c]) return vm[c].$class;\n"
172 private static native Class<?> loadCls(String n, String c);
176 * Creates a new instance of the class represented by this {@code Class}
177 * object. The class is instantiated as if by a {@code new}
178 * expression with an empty argument list. The class is initialized if it
179 * has not already been initialized.
181 * <p>Note that this method propagates any exception thrown by the
182 * nullary constructor, including a checked exception. Use of
183 * this method effectively bypasses the compile-time exception
184 * checking that would otherwise be performed by the compiler.
186 * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
187 * Constructor.newInstance} method avoids this problem by wrapping
188 * any exception thrown by the constructor in a (checked) {@link
189 * java.lang.reflect.InvocationTargetException}.
191 * @return a newly allocated instance of the class represented by this
193 * @exception IllegalAccessException if the class or its nullary
194 * constructor is not accessible.
195 * @exception InstantiationException
196 * if this {@code Class} represents an abstract class,
197 * an interface, an array class, a primitive type, or void;
198 * or if the class has no nullary constructor;
199 * or if the instantiation fails for some other reason.
200 * @exception ExceptionInInitializerError if the initialization
201 * provoked by this method fails.
202 * @exception SecurityException
203 * If a security manager, <i>s</i>, is present and any of the
204 * following conditions is met:
209 * {@link SecurityManager#checkMemberAccess
210 * s.checkMemberAccess(this, Member.PUBLIC)} denies
211 * creation of new instances of this class
213 * <li> the caller's class loader is not the same as or an
214 * ancestor of the class loader for the current class and
215 * invocation of {@link SecurityManager#checkPackageAccess
216 * s.checkPackageAccess()} denies access to the package
222 @JavaScriptBody(args = { "self", "illegal" }, body =
223 "\nvar c = self.cnstr;"
224 + "\nif (c['cons__V']) {"
225 + "\n if ((c.cons__V.access & 0x1) != 0) {"
226 + "\n var inst = c();"
227 + "\n c.cons__V.call(inst);"
230 + "\n return illegal;"
234 private static native Object newInstance0(Class<?> self, Object illegal);
236 public T newInstance()
237 throws InstantiationException, IllegalAccessException
239 Object illegal = new Object();
240 Object inst = newInstance0(this, illegal);
242 throw new InstantiationException(getName());
244 if (inst == illegal) {
245 throw new IllegalAccessException();
251 * Determines if the specified {@code Object} is assignment-compatible
252 * with the object represented by this {@code Class}. This method is
253 * the dynamic equivalent of the Java language {@code instanceof}
254 * operator. The method returns {@code true} if the specified
255 * {@code Object} argument is non-null and can be cast to the
256 * reference type represented by this {@code Class} object without
257 * raising a {@code ClassCastException.} It returns {@code false}
260 * <p> Specifically, if this {@code Class} object represents a
261 * declared class, this method returns {@code true} if the specified
262 * {@code Object} argument is an instance of the represented class (or
263 * of any of its subclasses); it returns {@code false} otherwise. If
264 * this {@code Class} object represents an array class, this method
265 * returns {@code true} if the specified {@code Object} argument
266 * can be converted to an object of the array class by an identity
267 * conversion or by a widening reference conversion; it returns
268 * {@code false} otherwise. If this {@code Class} object
269 * represents an interface, this method returns {@code true} if the
270 * class or any superclass of the specified {@code Object} argument
271 * implements this interface; it returns {@code false} otherwise. If
272 * this {@code Class} object represents a primitive type, this method
273 * returns {@code false}.
275 * @param obj the object to check
276 * @return true if {@code obj} is an instance of this class
280 public boolean isInstance(Object obj) {
281 String prop = "$instOf_" + getName().replace('.', '_');
282 return hasProperty(obj, prop);
285 @JavaScriptBody(args = { "who", "prop" }, body =
286 "if (who[prop]) return true; else return false;"
288 private static native boolean hasProperty(Object who, String prop);
292 * Determines if the class or interface represented by this
293 * {@code Class} object is either the same as, or is a superclass or
294 * superinterface of, the class or interface represented by the specified
295 * {@code Class} parameter. It returns {@code true} if so;
296 * otherwise it returns {@code false}. If this {@code Class}
297 * object represents a primitive type, this method returns
298 * {@code true} if the specified {@code Class} parameter is
299 * exactly this {@code Class} object; otherwise it returns
302 * <p> Specifically, this method tests whether the type represented by the
303 * specified {@code Class} parameter can be converted to the type
304 * represented by this {@code Class} object via an identity conversion
305 * or via a widening reference conversion. See <em>The Java Language
306 * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
308 * @param cls the {@code Class} object to be checked
309 * @return the {@code boolean} value indicating whether objects of the
310 * type {@code cls} can be assigned to objects of this class
311 * @exception NullPointerException if the specified Class parameter is
315 public native boolean isAssignableFrom(Class<?> cls);
319 * Determines if the specified {@code Class} object represents an
322 * @return {@code true} if this object represents an interface;
323 * {@code false} otherwise.
325 public boolean isInterface() {
326 return (getAccess() & 0x200) != 0;
329 @JavaScriptBody(args = {}, body = "return this.access;")
330 private native int getAccess();
334 * Determines if this {@code Class} object represents an array class.
336 * @return {@code true} if this object represents an array class;
337 * {@code false} otherwise.
340 public boolean isArray() {
341 return hasProperty(this, "array"); // NOI18N
346 * Determines if the specified {@code Class} object represents a
349 * <p> There are nine predefined {@code Class} objects to represent
350 * the eight primitive types and void. These are created by the Java
351 * Virtual Machine, and have the same names as the primitive types that
352 * they represent, namely {@code boolean}, {@code byte},
353 * {@code char}, {@code short}, {@code int},
354 * {@code long}, {@code float}, and {@code double}.
356 * <p> These objects may only be accessed via the following public static
357 * final variables, and are the only {@code Class} objects for which
358 * this method returns {@code true}.
360 * @return true if and only if this class represents a primitive type
362 * @see java.lang.Boolean#TYPE
363 * @see java.lang.Character#TYPE
364 * @see java.lang.Byte#TYPE
365 * @see java.lang.Short#TYPE
366 * @see java.lang.Integer#TYPE
367 * @see java.lang.Long#TYPE
368 * @see java.lang.Float#TYPE
369 * @see java.lang.Double#TYPE
370 * @see java.lang.Void#TYPE
373 @JavaScriptBody(args = {}, body =
374 "if (this.primitive) return true;"
375 + "else return false;"
377 public native boolean isPrimitive();
380 * Returns true if this {@code Class} object represents an annotation
381 * type. Note that if this method returns true, {@link #isInterface()}
382 * would also return true, as all annotation types are also interfaces.
384 * @return {@code true} if this class object represents an annotation
385 * type; {@code false} otherwise
388 public boolean isAnnotation() {
389 return (getModifiers() & ANNOTATION) != 0;
393 * Returns {@code true} if this class is a synthetic class;
394 * returns {@code false} otherwise.
395 * @return {@code true} if and only if this class is a synthetic class as
396 * defined by the Java Language Specification.
399 public boolean isSynthetic() {
400 return (getModifiers() & SYNTHETIC) != 0;
404 * Returns the name of the entity (class, interface, array class,
405 * primitive type, or void) represented by this {@code Class} object,
406 * as a {@code String}.
408 * <p> If this class object represents a reference type that is not an
409 * array type then the binary name of the class is returned, as specified
411 * <cite>The Java™ Language Specification</cite>.
413 * <p> If this class object represents a primitive type or void, then the
414 * name returned is a {@code String} equal to the Java language
415 * keyword corresponding to the primitive type or void.
417 * <p> If this class object represents a class of arrays, then the internal
418 * form of the name consists of the name of the element type preceded by
419 * one or more '{@code [}' characters representing the depth of the array
420 * nesting. The encoding of element type names is as follows:
422 * <blockquote><table summary="Element types and encodings">
423 * <tr><th> Element Type <th> <th> Encoding
424 * <tr><td> boolean <td> <td align=center> Z
425 * <tr><td> byte <td> <td align=center> B
426 * <tr><td> char <td> <td align=center> C
427 * <tr><td> class or interface
428 * <td> <td align=center> L<i>classname</i>;
429 * <tr><td> double <td> <td align=center> D
430 * <tr><td> float <td> <td align=center> F
431 * <tr><td> int <td> <td align=center> I
432 * <tr><td> long <td> <td align=center> J
433 * <tr><td> short <td> <td align=center> S
434 * </table></blockquote>
436 * <p> The class or interface name <i>classname</i> is the binary name of
437 * the class specified above.
441 * String.class.getName()
442 * returns "java.lang.String"
443 * byte.class.getName()
445 * (new Object[3]).getClass().getName()
446 * returns "[Ljava.lang.Object;"
447 * (new int[3][4][5][6][7][8][9]).getClass().getName()
449 * </pre></blockquote>
451 * @return the name of the class or interface
452 * represented by this object.
454 public String getName() {
455 return jvmName().replace('/', '.');
458 @JavaScriptBody(args = {}, body = "return this.jvmName;")
459 private native String jvmName();
463 * Returns an array of {@code TypeVariable} objects that represent the
464 * type variables declared by the generic declaration represented by this
465 * {@code GenericDeclaration} object, in declaration order. Returns an
466 * array of length 0 if the underlying generic declaration declares no type
469 * @return an array of {@code TypeVariable} objects that represent
470 * the type variables declared by this generic declaration
471 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
472 * signature of this generic declaration does not conform to
473 * the format specified in
474 * <cite>The Java™ Virtual Machine Specification</cite>
477 public TypeVariable<Class<T>>[] getTypeParameters() {
478 throw new UnsupportedOperationException();
482 * Returns the {@code Class} representing the superclass of the entity
483 * (class, interface, primitive type or void) represented by this
484 * {@code Class}. If this {@code Class} represents either the
485 * {@code Object} class, an interface, a primitive type, or void, then
486 * null is returned. If this object represents an array class then the
487 * {@code Class} object representing the {@code Object} class is
490 * @return the superclass of the class represented by this object.
492 @JavaScriptBody(args = {}, body = "return this.superclass;")
493 public native Class<? super T> getSuperclass();
496 * Returns the Java language modifiers for this class or interface, encoded
497 * in an integer. The modifiers consist of the Java Virtual Machine's
498 * constants for {@code public}, {@code protected},
499 * {@code private}, {@code final}, {@code static},
500 * {@code abstract} and {@code interface}; they should be decoded
501 * using the methods of class {@code Modifier}.
503 * <p> If the underlying class is an array class, then its
504 * {@code public}, {@code private} and {@code protected}
505 * modifiers are the same as those of its component type. If this
506 * {@code Class} represents a primitive type or void, its
507 * {@code public} modifier is always {@code true}, and its
508 * {@code protected} and {@code private} modifiers are always
509 * {@code false}. If this object represents an array class, a
510 * primitive type or void, then its {@code final} modifier is always
511 * {@code true} and its interface modifier is always
512 * {@code false}. The values of its other modifiers are not determined
513 * by this specification.
515 * <p> The modifier encodings are defined in <em>The Java Virtual Machine
516 * Specification</em>, table 4.1.
518 * @return the {@code int} representing the modifiers for this class
519 * @see java.lang.reflect.Modifier
522 public native int getModifiers();
526 * Returns the simple name of the underlying class as given in the
527 * source code. Returns an empty string if the underlying class is
530 * <p>The simple name of an array is the simple name of the
531 * component type with "[]" appended. In particular the simple
532 * name of an array whose component type is anonymous is "[]".
534 * @return the simple name of the underlying class
537 public String getSimpleName() {
539 return getComponentType().getSimpleName()+"[]";
541 String simpleName = getSimpleBinaryName();
542 if (simpleName == null) { // top level class
543 simpleName = getName();
544 return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
546 // According to JLS3 "Binary Compatibility" (13.1) the binary
547 // name of non-package classes (not top level) is the binary
548 // name of the immediately enclosing class followed by a '$' followed by:
549 // (for nested and inner classes): the simple name.
550 // (for local classes): 1 or more digits followed by the simple name.
551 // (for anonymous classes): 1 or more digits.
553 // Since getSimpleBinaryName() will strip the binary name of
554 // the immediatly enclosing class, we are now looking at a
555 // string that matches the regular expression "\$[0-9]*"
556 // followed by a simple name (considering the simple of an
557 // anonymous class to be the empty string).
559 // Remove leading "\$[0-9]*" from the name
560 int length = simpleName.length();
561 if (length < 1 || simpleName.charAt(0) != '$')
562 throw new IllegalStateException("Malformed class name");
564 while (index < length && isAsciiDigit(simpleName.charAt(index)))
566 // Eventually, this is the empty string iff this is an anonymous class
567 return simpleName.substring(index);
571 * Returns the "simple binary name" of the underlying class, i.e.,
572 * the binary name without the leading enclosing class name.
573 * Returns {@code null} if the underlying class is a top level
576 private String getSimpleBinaryName() {
577 Class<?> enclosingClass = null; // XXX getEnclosingClass();
578 if (enclosingClass == null) // top level class
580 // Otherwise, strip the enclosing class' name
582 return getName().substring(enclosingClass.getName().length());
583 } catch (IndexOutOfBoundsException ex) {
584 throw new IllegalStateException("Malformed class name");
589 * Returns an array containing {@code Field} objects reflecting all
590 * the accessible public fields of the class or interface represented by
591 * this {@code Class} object. The elements in the array returned are
592 * not sorted and are not in any particular order. This method returns an
593 * array of length 0 if the class or interface has no accessible public
594 * fields, or if it represents an array class, a primitive type, or void.
596 * <p> Specifically, if this {@code Class} object represents a class,
597 * this method returns the public fields of this class and of all its
598 * superclasses. If this {@code Class} object represents an
599 * interface, this method returns the fields of this interface and of all
600 * its superinterfaces.
602 * <p> The implicit length field for array class is not reflected by this
603 * method. User code should use the methods of class {@code Array} to
606 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
608 * @return the array of {@code Field} objects representing the
610 * @exception SecurityException
611 * If a security manager, <i>s</i>, is present and any of the
612 * following conditions is met:
617 * {@link SecurityManager#checkMemberAccess
618 * s.checkMemberAccess(this, Member.PUBLIC)} denies
619 * access to the fields within this class
621 * <li> the caller's class loader is not the same as or an
622 * ancestor of the class loader for the current class and
623 * invocation of {@link SecurityManager#checkPackageAccess
624 * s.checkPackageAccess()} denies access to the package
631 public Field[] getFields() throws SecurityException {
632 throw new SecurityException();
636 * Returns an array containing {@code Method} objects reflecting all
637 * the public <em>member</em> methods of the class or interface represented
638 * by this {@code Class} object, including those declared by the class
639 * or interface and those inherited from superclasses and
640 * superinterfaces. Array classes return all the (public) member methods
641 * inherited from the {@code Object} class. The elements in the array
642 * returned are not sorted and are not in any particular order. This
643 * method returns an array of length 0 if this {@code Class} object
644 * represents a class or interface that has no public member methods, or if
645 * this {@code Class} object represents a primitive type or void.
647 * <p> The class initialization method {@code <clinit>} is not
648 * included in the returned array. If the class declares multiple public
649 * member methods with the same parameter types, they are all included in
650 * the returned array.
652 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
654 * @return the array of {@code Method} objects representing the
655 * public methods of this class
656 * @exception SecurityException
657 * If a security manager, <i>s</i>, is present and any of the
658 * following conditions is met:
663 * {@link SecurityManager#checkMemberAccess
664 * s.checkMemberAccess(this, Member.PUBLIC)} denies
665 * access to the methods within this class
667 * <li> the caller's class loader is not the same as or an
668 * ancestor of the class loader for the current class and
669 * invocation of {@link SecurityManager#checkPackageAccess
670 * s.checkPackageAccess()} denies access to the package
677 public Method[] getMethods() throws SecurityException {
678 return MethodImpl.findMethods(this, 0x01);
682 * Returns a {@code Field} object that reflects the specified public
683 * member field of the class or interface represented by this
684 * {@code Class} object. The {@code name} parameter is a
685 * {@code String} specifying the simple name of the desired field.
687 * <p> The field to be reflected is determined by the algorithm that
688 * follows. Let C be the class represented by this object:
690 * <LI> If C declares a public field with the name specified, that is the
691 * field to be reflected.</LI>
692 * <LI> If no field was found in step 1 above, this algorithm is applied
693 * recursively to each direct superinterface of C. The direct
694 * superinterfaces are searched in the order they were declared.</LI>
695 * <LI> If no field was found in steps 1 and 2 above, and C has a
696 * superclass S, then this algorithm is invoked recursively upon S.
697 * If C has no superclass, then a {@code NoSuchFieldException}
701 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
703 * @param name the field name
704 * @return the {@code Field} object of this class specified by
706 * @exception NoSuchFieldException if a field with the specified name is
708 * @exception NullPointerException if {@code name} is {@code null}
709 * @exception SecurityException
710 * If a security manager, <i>s</i>, is present and any of the
711 * following conditions is met:
716 * {@link SecurityManager#checkMemberAccess
717 * s.checkMemberAccess(this, Member.PUBLIC)} denies
718 * access to the field
720 * <li> the caller's class loader is not the same as or an
721 * ancestor of the class loader for the current class and
722 * invocation of {@link SecurityManager#checkPackageAccess
723 * s.checkPackageAccess()} denies access to the package
730 public Field getField(String name)
731 throws SecurityException {
732 throw new SecurityException();
737 * Returns a {@code Method} object that reflects the specified public
738 * member method of the class or interface represented by this
739 * {@code Class} object. The {@code name} parameter is a
740 * {@code String} specifying the simple name of the desired method. The
741 * {@code parameterTypes} parameter is an array of {@code Class}
742 * objects that identify the method's formal parameter types, in declared
743 * order. If {@code parameterTypes} is {@code null}, it is
744 * treated as if it were an empty array.
746 * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
747 * {@code NoSuchMethodException} is raised. Otherwise, the method to
748 * be reflected is determined by the algorithm that follows. Let C be the
749 * class represented by this object:
751 * <LI> C is searched for any <I>matching methods</I>. If no matching
752 * method is found, the algorithm of step 1 is invoked recursively on
753 * the superclass of C.</LI>
754 * <LI> If no method was found in step 1 above, the superinterfaces of C
755 * are searched for a matching method. If any such method is found, it
759 * To find a matching method in a class C: If C declares exactly one
760 * public method with the specified name and exactly the same formal
761 * parameter types, that is the method reflected. If more than one such
762 * method is found in C, and one of these methods has a return type that is
763 * more specific than any of the others, that method is reflected;
764 * otherwise one of the methods is chosen arbitrarily.
766 * <p>Note that there may be more than one matching method in a
767 * class because while the Java language forbids a class to
768 * declare multiple methods with the same signature but different
769 * return types, the Java virtual machine does not. This
770 * increased flexibility in the virtual machine can be used to
771 * implement various language features. For example, covariant
772 * returns can be implemented with {@linkplain
773 * java.lang.reflect.Method#isBridge bridge methods}; the bridge
774 * method and the method being overridden would have the same
775 * signature but different return types.
777 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
779 * @param name the name of the method
780 * @param parameterTypes the list of parameters
781 * @return the {@code Method} object that matches the specified
782 * {@code name} and {@code parameterTypes}
783 * @exception NoSuchMethodException if a matching method is not found
784 * or if the name is "<init>"or "<clinit>".
785 * @exception NullPointerException if {@code name} is {@code null}
786 * @exception SecurityException
787 * If a security manager, <i>s</i>, is present and any of the
788 * following conditions is met:
793 * {@link SecurityManager#checkMemberAccess
794 * s.checkMemberAccess(this, Member.PUBLIC)} denies
795 * access to the method
797 * <li> the caller's class loader is not the same as or an
798 * ancestor of the class loader for the current class and
799 * invocation of {@link SecurityManager#checkPackageAccess
800 * s.checkPackageAccess()} denies access to the package
807 public Method getMethod(String name, Class<?>... parameterTypes)
808 throws SecurityException, NoSuchMethodException {
809 Method m = MethodImpl.findMethod(this, name, parameterTypes);
811 StringBuilder sb = new StringBuilder();
812 sb.append(getName()).append('.').append(name).append('(');
814 for (int i = 0; i < parameterTypes.length; i++) {
815 sb.append(sep).append(parameterTypes[i].getName());
819 throw new NoSuchMethodException(sb.toString());
825 * Character.isDigit answers {@code true} to some non-ascii
826 * digits. This one does not.
828 private static boolean isAsciiDigit(char c) {
829 return '0' <= c && c <= '9';
833 * Returns the canonical name of the underlying class as
834 * defined by the Java Language Specification. Returns null if
835 * the underlying class does not have a canonical name (i.e., if
836 * it is a local or anonymous class or an array whose component
837 * type does not have a canonical name).
838 * @return the canonical name of the underlying class if it exists, and
839 * {@code null} otherwise.
842 public String getCanonicalName() {
844 String canonicalName = getComponentType().getCanonicalName();
845 if (canonicalName != null)
846 return canonicalName + "[]";
850 // if (isLocalOrAnonymousClass())
852 // Class<?> enclosingClass = getEnclosingClass();
853 Class<?> enclosingClass = null;
854 if (enclosingClass == null) { // top level class
857 String enclosingName = enclosingClass.getCanonicalName();
858 if (enclosingName == null)
860 return enclosingName + "." + getSimpleName();
865 * Finds a resource with a given name. The rules for searching resources
866 * associated with a given class are implemented by the defining
867 * {@linkplain ClassLoader class loader} of the class. This method
868 * delegates to this object's class loader. If this object was loaded by
869 * the bootstrap class loader, the method delegates to {@link
870 * ClassLoader#getSystemResourceAsStream}.
872 * <p> Before delegation, an absolute resource name is constructed from the
873 * given resource name using this algorithm:
877 * <li> If the {@code name} begins with a {@code '/'}
878 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
879 * portion of the {@code name} following the {@code '/'}.
881 * <li> Otherwise, the absolute name is of the following form:
884 * {@code modified_package_name/name}
887 * <p> Where the {@code modified_package_name} is the package name of this
888 * object with {@code '/'} substituted for {@code '.'}
889 * (<tt>'\u002e'</tt>).
893 * @param name name of the desired resource
894 * @return A {@link java.io.InputStream} object or {@code null} if
895 * no resource with this name is found
896 * @throws NullPointerException If {@code name} is {@code null}
899 public InputStream getResourceAsStream(String name) {
900 name = resolveName(name);
901 byte[] arr = getResourceAsStream0(name);
902 return arr == null ? null : new ByteArrayInputStream(arr);
905 @JavaScriptBody(args = "name", body =
906 "return (vm.loadBytes) ? vm.loadBytes(name) : null;"
908 private static native byte[] getResourceAsStream0(String name);
911 * Finds a resource with a given name. The rules for searching resources
912 * associated with a given class are implemented by the defining
913 * {@linkplain ClassLoader class loader} of the class. This method
914 * delegates to this object's class loader. If this object was loaded by
915 * the bootstrap class loader, the method delegates to {@link
916 * ClassLoader#getSystemResource}.
918 * <p> Before delegation, an absolute resource name is constructed from the
919 * given resource name using this algorithm:
923 * <li> If the {@code name} begins with a {@code '/'}
924 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
925 * portion of the {@code name} following the {@code '/'}.
927 * <li> Otherwise, the absolute name is of the following form:
930 * {@code modified_package_name/name}
933 * <p> Where the {@code modified_package_name} is the package name of this
934 * object with {@code '/'} substituted for {@code '.'}
935 * (<tt>'\u002e'</tt>).
939 * @param name name of the desired resource
940 * @return A {@link java.net.URL} object or {@code null} if no
941 * resource with this name is found
944 public java.net.URL getResource(String name) {
945 name = resolveName(name);
946 ClassLoader cl = null;
949 return ClassLoader.getSystemResource(name);
951 return cl.getResource(name);
956 * Add a package name prefix if the name is not absolute Remove leading "/"
957 * if name is absolute
959 private String resolveName(String name) {
963 if (!name.startsWith("/")) {
965 while (c.isArray()) {
966 c = c.getComponentType();
968 String baseName = c.getName();
969 int index = baseName.lastIndexOf('.');
971 name = baseName.substring(0, index).replace('.', '/')
975 name = name.substring(1);
981 * Returns the class loader for the class. Some implementations may use
982 * null to represent the bootstrap class loader. This method will return
983 * null in such implementations if this class was loaded by the bootstrap
986 * <p> If a security manager is present, and the caller's class loader is
987 * not null and the caller's class loader is not the same as or an ancestor of
988 * the class loader for the class whose class loader is requested, then
989 * this method calls the security manager's {@code checkPermission}
990 * method with a {@code RuntimePermission("getClassLoader")}
991 * permission to ensure it's ok to access the class loader for the class.
994 * represents a primitive type or void, null is returned.
996 * @return the class loader that loaded the class or interface
997 * represented by this object.
998 * @throws SecurityException
999 * if a security manager exists and its
1000 * {@code checkPermission} method denies
1001 * access to the class loader for the class.
1002 * @see java.lang.ClassLoader
1003 * @see SecurityManager#checkPermission
1004 * @see java.lang.RuntimePermission
1006 public ClassLoader getClassLoader() {
1007 throw new SecurityException();
1011 * Returns the {@code Class} representing the component type of an
1012 * array. If this class does not represent an array class this method
1015 * @return the {@code Class} representing the component type of this
1016 * class if this class is an array
1017 * @see java.lang.reflect.Array
1020 public Class<?> getComponentType() {
1023 return getComponentType0();
1024 } catch (ClassNotFoundException cnfe) {
1025 throw new IllegalStateException(cnfe);
1031 private Class<?> getComponentType0() throws ClassNotFoundException {
1032 String n = getName().substring(1);
1033 switch (n.charAt(0)) {
1035 n = n.substring(1, n.length() - 1);
1036 return Class.forName(n);
1038 return Integer.TYPE;
1048 return Boolean.TYPE;
1054 return Character.TYPE;
1056 return defineArray(n);
1058 throw new ClassNotFoundException("Unknown component type of " + getName());
1062 @JavaScriptBody(args = { "sig" }, body =
1063 "var c = Array[sig];\n" +
1064 "if (c) return c;\n" +
1065 "c = vm.java_lang_Class(true);\n" +
1066 "c.jvmName = sig;\n" +
1067 "c.superclass = vm.java_lang_Object(false).$class;\n" +
1068 "c.array = true;\n" +
1069 "Array[sig] = c;\n" +
1072 private static native Class<?> defineArray(String sig);
1075 * Returns true if and only if this class was declared as an enum in the
1078 * @return true if and only if this class was declared as an enum in the
1082 public boolean isEnum() {
1083 // An enum must both directly extend java.lang.Enum and have
1084 // the ENUM bit set; classes for specialized enum constants
1085 // don't do the former.
1086 return (this.getModifiers() & ENUM) != 0 &&
1087 this.getSuperclass() == java.lang.Enum.class;
1091 * Casts an object to the class or interface represented
1092 * by this {@code Class} object.
1094 * @param obj the object to be cast
1095 * @return the object after casting, or null if obj is null
1097 * @throws ClassCastException if the object is not
1098 * null and is not assignable to the type T.
1102 public T cast(Object obj) {
1103 if (obj != null && !isInstance(obj))
1104 throw new ClassCastException(cannotCastMsg(obj));
1108 private String cannotCastMsg(Object obj) {
1109 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
1113 * Casts this {@code Class} object to represent a subclass of the class
1114 * represented by the specified class object. Checks that that the cast
1115 * is valid, and throws a {@code ClassCastException} if it is not. If
1116 * this method succeeds, it always returns a reference to this class object.
1118 * <p>This method is useful when a client needs to "narrow" the type of
1119 * a {@code Class} object to pass it to an API that restricts the
1120 * {@code Class} objects that it is willing to accept. A cast would
1121 * generate a compile-time warning, as the correctness of the cast
1122 * could not be checked at runtime (because generic types are implemented
1125 * @return this {@code Class} object, cast to represent a subclass of
1126 * the specified class object.
1127 * @throws ClassCastException if this {@code Class} object does not
1128 * represent a subclass of the specified class (here "subclass" includes
1129 * the class itself).
1132 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
1133 if (clazz.isAssignableFrom(this))
1134 return (Class<? extends U>) this;
1136 throw new ClassCastException(this.toString());
1139 @JavaScriptBody(args = { "ac" },
1142 + " return this.anno['L' + ac.jvmName + ';'];"
1143 + "} else return null;"
1145 private Object getAnnotationData(Class<?> annotationClass) {
1146 throw new UnsupportedOperationException();
1149 * @throws NullPointerException {@inheritDoc}
1152 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
1153 Object data = getAnnotationData(annotationClass);
1154 return data == null ? null : AnnotationImpl.create(annotationClass, data);
1158 * @throws NullPointerException {@inheritDoc}
1161 @JavaScriptBody(args = { "ac" },
1162 body = "if (this.anno && this.anno['L' + ac.jvmName + ';']) { return true; }"
1163 + "else return false;"
1165 public boolean isAnnotationPresent(
1166 Class<? extends Annotation> annotationClass) {
1167 if (annotationClass == null)
1168 throw new NullPointerException();
1170 return getAnnotation(annotationClass) != null;
1173 @JavaScriptBody(args = {}, body = "return this.anno;")
1174 private Object getAnnotationData() {
1175 throw new UnsupportedOperationException();
1181 public Annotation[] getAnnotations() {
1182 Object data = getAnnotationData();
1183 return data == null ? new Annotation[0] : AnnotationImpl.create(data);
1189 public Annotation[] getDeclaredAnnotations() {
1190 throw new UnsupportedOperationException();
1193 @JavaScriptBody(args = "type", body = ""
1194 + "var c = vm.java_lang_Class(true);"
1195 + "c.jvmName = type;"
1196 + "c.primitive = true;"
1199 native static Class getPrimitiveClass(String type);
1201 @JavaScriptBody(args = {}, body =
1202 "return vm.desiredAssertionStatus ? vm.desiredAssertionStatus : false;"
1204 public native boolean desiredAssertionStatus();