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) {
282 return isAssignableFrom(obj.getClass());
285 String prop = "$instOf_" + getName().replace('.', '_');
286 return hasProperty(obj, prop);
289 @JavaScriptBody(args = { "who", "prop" }, body =
290 "if (who[prop]) return true; else return false;"
292 private static native boolean hasProperty(Object who, String prop);
296 * Determines if the class or interface represented by this
297 * {@code Class} object is either the same as, or is a superclass or
298 * superinterface of, the class or interface represented by the specified
299 * {@code Class} parameter. It returns {@code true} if so;
300 * otherwise it returns {@code false}. If this {@code Class}
301 * object represents a primitive type, this method returns
302 * {@code true} if the specified {@code Class} parameter is
303 * exactly this {@code Class} object; otherwise it returns
306 * <p> Specifically, this method tests whether the type represented by the
307 * specified {@code Class} parameter can be converted to the type
308 * represented by this {@code Class} object via an identity conversion
309 * or via a widening reference conversion. See <em>The Java Language
310 * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
312 * @param cls the {@code Class} object to be checked
313 * @return the {@code boolean} value indicating whether objects of the
314 * type {@code cls} can be assigned to objects of this class
315 * @exception NullPointerException if the specified Class parameter is
319 public boolean isAssignableFrom(Class<?> cls) {
325 final Class<?> cmpType = cls.getComponentType();
327 return this == cmpType;
329 return cmpType != null && getComponentType().isAssignableFrom(cmpType);
331 String prop = "$instOf_" + getName().replace('.', '_');
332 return hasProperty(cls, prop);
337 * Determines if the specified {@code Class} object represents an
340 * @return {@code true} if this object represents an interface;
341 * {@code false} otherwise.
343 public boolean isInterface() {
344 return (getAccess() & 0x200) != 0;
347 @JavaScriptBody(args = {}, body = "return this.access;")
348 private native int getAccess();
352 * Determines if this {@code Class} object represents an array class.
354 * @return {@code true} if this object represents an array class;
355 * {@code false} otherwise.
358 public boolean isArray() {
359 return hasProperty(this, "array"); // NOI18N
364 * Determines if the specified {@code Class} object represents a
367 * <p> There are nine predefined {@code Class} objects to represent
368 * the eight primitive types and void. These are created by the Java
369 * Virtual Machine, and have the same names as the primitive types that
370 * they represent, namely {@code boolean}, {@code byte},
371 * {@code char}, {@code short}, {@code int},
372 * {@code long}, {@code float}, and {@code double}.
374 * <p> These objects may only be accessed via the following public static
375 * final variables, and are the only {@code Class} objects for which
376 * this method returns {@code true}.
378 * @return true if and only if this class represents a primitive type
380 * @see java.lang.Boolean#TYPE
381 * @see java.lang.Character#TYPE
382 * @see java.lang.Byte#TYPE
383 * @see java.lang.Short#TYPE
384 * @see java.lang.Integer#TYPE
385 * @see java.lang.Long#TYPE
386 * @see java.lang.Float#TYPE
387 * @see java.lang.Double#TYPE
388 * @see java.lang.Void#TYPE
391 @JavaScriptBody(args = {}, body =
392 "if (this.primitive) return true;"
393 + "else return false;"
395 public native boolean isPrimitive();
398 * Returns true if this {@code Class} object represents an annotation
399 * type. Note that if this method returns true, {@link #isInterface()}
400 * would also return true, as all annotation types are also interfaces.
402 * @return {@code true} if this class object represents an annotation
403 * type; {@code false} otherwise
406 public boolean isAnnotation() {
407 return (getModifiers() & ANNOTATION) != 0;
411 * Returns {@code true} if this class is a synthetic class;
412 * returns {@code false} otherwise.
413 * @return {@code true} if and only if this class is a synthetic class as
414 * defined by the Java Language Specification.
417 public boolean isSynthetic() {
418 return (getModifiers() & SYNTHETIC) != 0;
422 * Returns the name of the entity (class, interface, array class,
423 * primitive type, or void) represented by this {@code Class} object,
424 * as a {@code String}.
426 * <p> If this class object represents a reference type that is not an
427 * array type then the binary name of the class is returned, as specified
429 * <cite>The Java™ Language Specification</cite>.
431 * <p> If this class object represents a primitive type or void, then the
432 * name returned is a {@code String} equal to the Java language
433 * keyword corresponding to the primitive type or void.
435 * <p> If this class object represents a class of arrays, then the internal
436 * form of the name consists of the name of the element type preceded by
437 * one or more '{@code [}' characters representing the depth of the array
438 * nesting. The encoding of element type names is as follows:
440 * <blockquote><table summary="Element types and encodings">
441 * <tr><th> Element Type <th> <th> Encoding
442 * <tr><td> boolean <td> <td align=center> Z
443 * <tr><td> byte <td> <td align=center> B
444 * <tr><td> char <td> <td align=center> C
445 * <tr><td> class or interface
446 * <td> <td align=center> L<i>classname</i>;
447 * <tr><td> double <td> <td align=center> D
448 * <tr><td> float <td> <td align=center> F
449 * <tr><td> int <td> <td align=center> I
450 * <tr><td> long <td> <td align=center> J
451 * <tr><td> short <td> <td align=center> S
452 * </table></blockquote>
454 * <p> The class or interface name <i>classname</i> is the binary name of
455 * the class specified above.
459 * String.class.getName()
460 * returns "java.lang.String"
461 * byte.class.getName()
463 * (new Object[3]).getClass().getName()
464 * returns "[Ljava.lang.Object;"
465 * (new int[3][4][5][6][7][8][9]).getClass().getName()
467 * </pre></blockquote>
469 * @return the name of the class or interface
470 * represented by this object.
472 public String getName() {
473 return jvmName().replace('/', '.');
476 @JavaScriptBody(args = {}, body = "return this.jvmName;")
477 private native String jvmName();
481 * Returns an array of {@code TypeVariable} objects that represent the
482 * type variables declared by the generic declaration represented by this
483 * {@code GenericDeclaration} object, in declaration order. Returns an
484 * array of length 0 if the underlying generic declaration declares no type
487 * @return an array of {@code TypeVariable} objects that represent
488 * the type variables declared by this generic declaration
489 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
490 * signature of this generic declaration does not conform to
491 * the format specified in
492 * <cite>The Java™ Virtual Machine Specification</cite>
495 public TypeVariable<Class<T>>[] getTypeParameters() {
496 throw new UnsupportedOperationException();
500 * Returns the {@code Class} representing the superclass of the entity
501 * (class, interface, primitive type or void) represented by this
502 * {@code Class}. If this {@code Class} represents either the
503 * {@code Object} class, an interface, a primitive type, or void, then
504 * null is returned. If this object represents an array class then the
505 * {@code Class} object representing the {@code Object} class is
508 * @return the superclass of the class represented by this object.
510 @JavaScriptBody(args = {}, body = "return this.superclass;")
511 public native Class<? super T> getSuperclass();
514 * Returns the Java language modifiers for this class or interface, encoded
515 * in an integer. The modifiers consist of the Java Virtual Machine's
516 * constants for {@code public}, {@code protected},
517 * {@code private}, {@code final}, {@code static},
518 * {@code abstract} and {@code interface}; they should be decoded
519 * using the methods of class {@code Modifier}.
521 * <p> If the underlying class is an array class, then its
522 * {@code public}, {@code private} and {@code protected}
523 * modifiers are the same as those of its component type. If this
524 * {@code Class} represents a primitive type or void, its
525 * {@code public} modifier is always {@code true}, and its
526 * {@code protected} and {@code private} modifiers are always
527 * {@code false}. If this object represents an array class, a
528 * primitive type or void, then its {@code final} modifier is always
529 * {@code true} and its interface modifier is always
530 * {@code false}. The values of its other modifiers are not determined
531 * by this specification.
533 * <p> The modifier encodings are defined in <em>The Java Virtual Machine
534 * Specification</em>, table 4.1.
536 * @return the {@code int} representing the modifiers for this class
537 * @see java.lang.reflect.Modifier
540 public native int getModifiers();
544 * Returns the simple name of the underlying class as given in the
545 * source code. Returns an empty string if the underlying class is
548 * <p>The simple name of an array is the simple name of the
549 * component type with "[]" appended. In particular the simple
550 * name of an array whose component type is anonymous is "[]".
552 * @return the simple name of the underlying class
555 public String getSimpleName() {
557 return getComponentType().getSimpleName()+"[]";
559 String simpleName = getSimpleBinaryName();
560 if (simpleName == null) { // top level class
561 simpleName = getName();
562 return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
564 // According to JLS3 "Binary Compatibility" (13.1) the binary
565 // name of non-package classes (not top level) is the binary
566 // name of the immediately enclosing class followed by a '$' followed by:
567 // (for nested and inner classes): the simple name.
568 // (for local classes): 1 or more digits followed by the simple name.
569 // (for anonymous classes): 1 or more digits.
571 // Since getSimpleBinaryName() will strip the binary name of
572 // the immediatly enclosing class, we are now looking at a
573 // string that matches the regular expression "\$[0-9]*"
574 // followed by a simple name (considering the simple of an
575 // anonymous class to be the empty string).
577 // Remove leading "\$[0-9]*" from the name
578 int length = simpleName.length();
579 if (length < 1 || simpleName.charAt(0) != '$')
580 throw new IllegalStateException("Malformed class name");
582 while (index < length && isAsciiDigit(simpleName.charAt(index)))
584 // Eventually, this is the empty string iff this is an anonymous class
585 return simpleName.substring(index);
589 * Returns the "simple binary name" of the underlying class, i.e.,
590 * the binary name without the leading enclosing class name.
591 * Returns {@code null} if the underlying class is a top level
594 private String getSimpleBinaryName() {
595 Class<?> enclosingClass = null; // XXX getEnclosingClass();
596 if (enclosingClass == null) // top level class
598 // Otherwise, strip the enclosing class' name
600 return getName().substring(enclosingClass.getName().length());
601 } catch (IndexOutOfBoundsException ex) {
602 throw new IllegalStateException("Malformed class name");
607 * Returns an array containing {@code Field} objects reflecting all
608 * the accessible public fields of the class or interface represented by
609 * this {@code Class} object. The elements in the array returned are
610 * not sorted and are not in any particular order. This method returns an
611 * array of length 0 if the class or interface has no accessible public
612 * fields, or if it represents an array class, a primitive type, or void.
614 * <p> Specifically, if this {@code Class} object represents a class,
615 * this method returns the public fields of this class and of all its
616 * superclasses. If this {@code Class} object represents an
617 * interface, this method returns the fields of this interface and of all
618 * its superinterfaces.
620 * <p> The implicit length field for array class is not reflected by this
621 * method. User code should use the methods of class {@code Array} to
624 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
626 * @return the array of {@code Field} objects representing the
628 * @exception SecurityException
629 * If a security manager, <i>s</i>, is present and any of the
630 * following conditions is met:
635 * {@link SecurityManager#checkMemberAccess
636 * s.checkMemberAccess(this, Member.PUBLIC)} denies
637 * access to the fields within this class
639 * <li> the caller's class loader is not the same as or an
640 * ancestor of the class loader for the current class and
641 * invocation of {@link SecurityManager#checkPackageAccess
642 * s.checkPackageAccess()} denies access to the package
649 public Field[] getFields() throws SecurityException {
650 throw new SecurityException();
654 * Returns an array containing {@code Method} objects reflecting all
655 * the public <em>member</em> methods of the class or interface represented
656 * by this {@code Class} object, including those declared by the class
657 * or interface and those inherited from superclasses and
658 * superinterfaces. Array classes return all the (public) member methods
659 * inherited from the {@code Object} class. The elements in the array
660 * returned are not sorted and are not in any particular order. This
661 * method returns an array of length 0 if this {@code Class} object
662 * represents a class or interface that has no public member methods, or if
663 * this {@code Class} object represents a primitive type or void.
665 * <p> The class initialization method {@code <clinit>} is not
666 * included in the returned array. If the class declares multiple public
667 * member methods with the same parameter types, they are all included in
668 * the returned array.
670 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
672 * @return the array of {@code Method} objects representing the
673 * public methods of this class
674 * @exception SecurityException
675 * If a security manager, <i>s</i>, is present and any of the
676 * following conditions is met:
681 * {@link SecurityManager#checkMemberAccess
682 * s.checkMemberAccess(this, Member.PUBLIC)} denies
683 * access to the methods within this class
685 * <li> the caller's class loader is not the same as or an
686 * ancestor of the class loader for the current class and
687 * invocation of {@link SecurityManager#checkPackageAccess
688 * s.checkPackageAccess()} denies access to the package
695 public Method[] getMethods() throws SecurityException {
696 return MethodImpl.findMethods(this, 0x01);
700 * Returns a {@code Field} object that reflects the specified public
701 * member field of the class or interface represented by this
702 * {@code Class} object. The {@code name} parameter is a
703 * {@code String} specifying the simple name of the desired field.
705 * <p> The field to be reflected is determined by the algorithm that
706 * follows. Let C be the class represented by this object:
708 * <LI> If C declares a public field with the name specified, that is the
709 * field to be reflected.</LI>
710 * <LI> If no field was found in step 1 above, this algorithm is applied
711 * recursively to each direct superinterface of C. The direct
712 * superinterfaces are searched in the order they were declared.</LI>
713 * <LI> If no field was found in steps 1 and 2 above, and C has a
714 * superclass S, then this algorithm is invoked recursively upon S.
715 * If C has no superclass, then a {@code NoSuchFieldException}
719 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
721 * @param name the field name
722 * @return the {@code Field} object of this class specified by
724 * @exception NoSuchFieldException if a field with the specified name is
726 * @exception NullPointerException if {@code name} is {@code null}
727 * @exception SecurityException
728 * If a security manager, <i>s</i>, is present and any of the
729 * following conditions is met:
734 * {@link SecurityManager#checkMemberAccess
735 * s.checkMemberAccess(this, Member.PUBLIC)} denies
736 * access to the field
738 * <li> the caller's class loader is not the same as or an
739 * ancestor of the class loader for the current class and
740 * invocation of {@link SecurityManager#checkPackageAccess
741 * s.checkPackageAccess()} denies access to the package
748 public Field getField(String name)
749 throws SecurityException {
750 throw new SecurityException();
755 * Returns a {@code Method} object that reflects the specified public
756 * member method of the class or interface represented by this
757 * {@code Class} object. The {@code name} parameter is a
758 * {@code String} specifying the simple name of the desired method. The
759 * {@code parameterTypes} parameter is an array of {@code Class}
760 * objects that identify the method's formal parameter types, in declared
761 * order. If {@code parameterTypes} is {@code null}, it is
762 * treated as if it were an empty array.
764 * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
765 * {@code NoSuchMethodException} is raised. Otherwise, the method to
766 * be reflected is determined by the algorithm that follows. Let C be the
767 * class represented by this object:
769 * <LI> C is searched for any <I>matching methods</I>. If no matching
770 * method is found, the algorithm of step 1 is invoked recursively on
771 * the superclass of C.</LI>
772 * <LI> If no method was found in step 1 above, the superinterfaces of C
773 * are searched for a matching method. If any such method is found, it
777 * To find a matching method in a class C: If C declares exactly one
778 * public method with the specified name and exactly the same formal
779 * parameter types, that is the method reflected. If more than one such
780 * method is found in C, and one of these methods has a return type that is
781 * more specific than any of the others, that method is reflected;
782 * otherwise one of the methods is chosen arbitrarily.
784 * <p>Note that there may be more than one matching method in a
785 * class because while the Java language forbids a class to
786 * declare multiple methods with the same signature but different
787 * return types, the Java virtual machine does not. This
788 * increased flexibility in the virtual machine can be used to
789 * implement various language features. For example, covariant
790 * returns can be implemented with {@linkplain
791 * java.lang.reflect.Method#isBridge bridge methods}; the bridge
792 * method and the method being overridden would have the same
793 * signature but different return types.
795 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
797 * @param name the name of the method
798 * @param parameterTypes the list of parameters
799 * @return the {@code Method} object that matches the specified
800 * {@code name} and {@code parameterTypes}
801 * @exception NoSuchMethodException if a matching method is not found
802 * or if the name is "<init>"or "<clinit>".
803 * @exception NullPointerException if {@code name} is {@code null}
804 * @exception SecurityException
805 * If a security manager, <i>s</i>, is present and any of the
806 * following conditions is met:
811 * {@link SecurityManager#checkMemberAccess
812 * s.checkMemberAccess(this, Member.PUBLIC)} denies
813 * access to the method
815 * <li> the caller's class loader is not the same as or an
816 * ancestor of the class loader for the current class and
817 * invocation of {@link SecurityManager#checkPackageAccess
818 * s.checkPackageAccess()} denies access to the package
825 public Method getMethod(String name, Class<?>... parameterTypes)
826 throws SecurityException, NoSuchMethodException {
827 Method m = MethodImpl.findMethod(this, name, parameterTypes);
829 StringBuilder sb = new StringBuilder();
830 sb.append(getName()).append('.').append(name).append('(');
832 for (int i = 0; i < parameterTypes.length; i++) {
833 sb.append(sep).append(parameterTypes[i].getName());
837 throw new NoSuchMethodException(sb.toString());
843 * Character.isDigit answers {@code true} to some non-ascii
844 * digits. This one does not.
846 private static boolean isAsciiDigit(char c) {
847 return '0' <= c && c <= '9';
851 * Returns the canonical name of the underlying class as
852 * defined by the Java Language Specification. Returns null if
853 * the underlying class does not have a canonical name (i.e., if
854 * it is a local or anonymous class or an array whose component
855 * type does not have a canonical name).
856 * @return the canonical name of the underlying class if it exists, and
857 * {@code null} otherwise.
860 public String getCanonicalName() {
862 String canonicalName = getComponentType().getCanonicalName();
863 if (canonicalName != null)
864 return canonicalName + "[]";
868 // if (isLocalOrAnonymousClass())
870 // Class<?> enclosingClass = getEnclosingClass();
871 Class<?> enclosingClass = null;
872 if (enclosingClass == null) { // top level class
875 String enclosingName = enclosingClass.getCanonicalName();
876 if (enclosingName == null)
878 return enclosingName + "." + getSimpleName();
883 * Finds a resource with a given name. The rules for searching resources
884 * associated with a given class are implemented by the defining
885 * {@linkplain ClassLoader class loader} of the class. This method
886 * delegates to this object's class loader. If this object was loaded by
887 * the bootstrap class loader, the method delegates to {@link
888 * ClassLoader#getSystemResourceAsStream}.
890 * <p> Before delegation, an absolute resource name is constructed from the
891 * given resource name using this algorithm:
895 * <li> If the {@code name} begins with a {@code '/'}
896 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
897 * portion of the {@code name} following the {@code '/'}.
899 * <li> Otherwise, the absolute name is of the following form:
902 * {@code modified_package_name/name}
905 * <p> Where the {@code modified_package_name} is the package name of this
906 * object with {@code '/'} substituted for {@code '.'}
907 * (<tt>'\u002e'</tt>).
911 * @param name name of the desired resource
912 * @return A {@link java.io.InputStream} object or {@code null} if
913 * no resource with this name is found
914 * @throws NullPointerException If {@code name} is {@code null}
917 public InputStream getResourceAsStream(String name) {
918 name = resolveName(name);
919 byte[] arr = getResourceAsStream0(name);
920 return arr == null ? null : new ByteArrayInputStream(arr);
923 @JavaScriptBody(args = "name", body =
924 "return (vm.loadBytes) ? vm.loadBytes(name) : null;"
926 private static native byte[] getResourceAsStream0(String name);
929 * Finds a resource with a given name. The rules for searching resources
930 * associated with a given class are implemented by the defining
931 * {@linkplain ClassLoader class loader} of the class. This method
932 * delegates to this object's class loader. If this object was loaded by
933 * the bootstrap class loader, the method delegates to {@link
934 * ClassLoader#getSystemResource}.
936 * <p> Before delegation, an absolute resource name is constructed from the
937 * given resource name using this algorithm:
941 * <li> If the {@code name} begins with a {@code '/'}
942 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
943 * portion of the {@code name} following the {@code '/'}.
945 * <li> Otherwise, the absolute name is of the following form:
948 * {@code modified_package_name/name}
951 * <p> Where the {@code modified_package_name} is the package name of this
952 * object with {@code '/'} substituted for {@code '.'}
953 * (<tt>'\u002e'</tt>).
957 * @param name name of the desired resource
958 * @return A {@link java.net.URL} object or {@code null} if no
959 * resource with this name is found
962 public java.net.URL getResource(String name) {
963 name = resolveName(name);
964 ClassLoader cl = null;
967 return ClassLoader.getSystemResource(name);
969 return cl.getResource(name);
974 * Add a package name prefix if the name is not absolute Remove leading "/"
975 * if name is absolute
977 private String resolveName(String name) {
981 if (!name.startsWith("/")) {
983 while (c.isArray()) {
984 c = c.getComponentType();
986 String baseName = c.getName();
987 int index = baseName.lastIndexOf('.');
989 name = baseName.substring(0, index).replace('.', '/')
993 name = name.substring(1);
999 * Returns the class loader for the class. Some implementations may use
1000 * null to represent the bootstrap class loader. This method will return
1001 * null in such implementations if this class was loaded by the bootstrap
1004 * <p> If a security manager is present, and the caller's class loader is
1005 * not null and the caller's class loader is not the same as or an ancestor of
1006 * the class loader for the class whose class loader is requested, then
1007 * this method calls the security manager's {@code checkPermission}
1008 * method with a {@code RuntimePermission("getClassLoader")}
1009 * permission to ensure it's ok to access the class loader for the class.
1012 * represents a primitive type or void, null is returned.
1014 * @return the class loader that loaded the class or interface
1015 * represented by this object.
1016 * @throws SecurityException
1017 * if a security manager exists and its
1018 * {@code checkPermission} method denies
1019 * access to the class loader for the class.
1020 * @see java.lang.ClassLoader
1021 * @see SecurityManager#checkPermission
1022 * @see java.lang.RuntimePermission
1024 public ClassLoader getClassLoader() {
1025 throw new SecurityException();
1029 * Returns the {@code Class} representing the component type of an
1030 * array. If this class does not represent an array class this method
1033 * @return the {@code Class} representing the component type of this
1034 * class if this class is an array
1035 * @see java.lang.reflect.Array
1038 public Class<?> getComponentType() {
1041 return getComponentType0();
1042 } catch (ClassNotFoundException cnfe) {
1043 throw new IllegalStateException(cnfe);
1049 private Class<?> getComponentType0() throws ClassNotFoundException {
1050 String n = getName().substring(1);
1051 switch (n.charAt(0)) {
1053 n = n.substring(1, n.length() - 1);
1054 return Class.forName(n);
1056 return Integer.TYPE;
1066 return Boolean.TYPE;
1072 return Character.TYPE;
1074 return defineArray(n);
1076 throw new ClassNotFoundException("Unknown component type of " + getName());
1080 @JavaScriptBody(args = { "sig" }, body =
1081 "var c = Array[sig];\n" +
1082 "if (c) return c;\n" +
1083 "c = vm.java_lang_Class(true);\n" +
1084 "c.jvmName = sig;\n" +
1085 "c.superclass = vm.java_lang_Object(false).$class;\n" +
1086 "c.array = true;\n" +
1087 "Array[sig] = c;\n" +
1090 private static native Class<?> defineArray(String sig);
1093 * Returns true if and only if this class was declared as an enum in the
1096 * @return true if and only if this class was declared as an enum in the
1100 public boolean isEnum() {
1101 // An enum must both directly extend java.lang.Enum and have
1102 // the ENUM bit set; classes for specialized enum constants
1103 // don't do the former.
1104 return (this.getModifiers() & ENUM) != 0 &&
1105 this.getSuperclass() == java.lang.Enum.class;
1109 * Casts an object to the class or interface represented
1110 * by this {@code Class} object.
1112 * @param obj the object to be cast
1113 * @return the object after casting, or null if obj is null
1115 * @throws ClassCastException if the object is not
1116 * null and is not assignable to the type T.
1120 public T cast(Object obj) {
1121 if (obj != null && !isInstance(obj))
1122 throw new ClassCastException(cannotCastMsg(obj));
1126 private String cannotCastMsg(Object obj) {
1127 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
1131 * Casts this {@code Class} object to represent a subclass of the class
1132 * represented by the specified class object. Checks that that the cast
1133 * is valid, and throws a {@code ClassCastException} if it is not. If
1134 * this method succeeds, it always returns a reference to this class object.
1136 * <p>This method is useful when a client needs to "narrow" the type of
1137 * a {@code Class} object to pass it to an API that restricts the
1138 * {@code Class} objects that it is willing to accept. A cast would
1139 * generate a compile-time warning, as the correctness of the cast
1140 * could not be checked at runtime (because generic types are implemented
1143 * @return this {@code Class} object, cast to represent a subclass of
1144 * the specified class object.
1145 * @throws ClassCastException if this {@code Class} object does not
1146 * represent a subclass of the specified class (here "subclass" includes
1147 * the class itself).
1150 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
1151 if (clazz.isAssignableFrom(this))
1152 return (Class<? extends U>) this;
1154 throw new ClassCastException(this.toString());
1157 @JavaScriptBody(args = { "ac" },
1160 + " return this.anno['L' + ac.jvmName + ';'];"
1161 + "} else return null;"
1163 private Object getAnnotationData(Class<?> annotationClass) {
1164 throw new UnsupportedOperationException();
1167 * @throws NullPointerException {@inheritDoc}
1170 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
1171 Object data = getAnnotationData(annotationClass);
1172 return data == null ? null : AnnotationImpl.create(annotationClass, data);
1176 * @throws NullPointerException {@inheritDoc}
1179 @JavaScriptBody(args = { "ac" },
1180 body = "if (this.anno && this.anno['L' + ac.jvmName + ';']) { return true; }"
1181 + "else return false;"
1183 public boolean isAnnotationPresent(
1184 Class<? extends Annotation> annotationClass) {
1185 if (annotationClass == null)
1186 throw new NullPointerException();
1188 return getAnnotation(annotationClass) != null;
1191 @JavaScriptBody(args = {}, body = "return this.anno;")
1192 private Object getAnnotationData() {
1193 throw new UnsupportedOperationException();
1199 public Annotation[] getAnnotations() {
1200 Object data = getAnnotationData();
1201 return data == null ? new Annotation[0] : AnnotationImpl.create(data);
1207 public Annotation[] getDeclaredAnnotations() {
1208 throw new UnsupportedOperationException();
1211 @JavaScriptBody(args = "type", body = ""
1212 + "var c = vm.java_lang_Class(true);"
1213 + "c.jvmName = type;"
1214 + "c.primitive = true;"
1217 native static Class getPrimitiveClass(String type);
1219 @JavaScriptBody(args = {}, body =
1220 "return vm.desiredAssertionStatus ? vm.desiredAssertionStatus : false;"
1222 public native boolean desiredAssertionStatus();