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.Field;
33 import java.lang.reflect.Method;
34 import java.lang.reflect.TypeVariable;
36 import org.apidesign.bck2brwsr.core.JavaScriptBody;
37 import org.apidesign.bck2brwsr.emul.reflect.MethodImpl;
40 * Instances of the class {@code Class} represent classes and
41 * interfaces in a running Java application. An enum is a kind of
42 * class and an annotation is a kind of interface. Every array also
43 * belongs to a class that is reflected as a {@code Class} object
44 * that is shared by all arrays with the same element type and number
45 * of dimensions. The primitive Java types ({@code boolean},
46 * {@code byte}, {@code char}, {@code short},
47 * {@code int}, {@code long}, {@code float}, and
48 * {@code double}), and the keyword {@code void} are also
49 * represented as {@code Class} objects.
51 * <p> {@code Class} has no public constructor. Instead {@code Class}
52 * objects are constructed automatically by the Java Virtual Machine as classes
53 * are loaded and by calls to the {@code defineClass} method in the class
56 * <p> The following example uses a {@code Class} object to print the
57 * class name of an object:
59 * <p> <blockquote><pre>
60 * void printClassName(Object obj) {
61 * System.out.println("The class of " + obj +
62 * " is " + obj.getClass().getName());
66 * <p> It is also possible to get the {@code Class} object for a named
67 * type (or for void) using a class literal. See Section 15.8.2 of
68 * <cite>The Java™ Language Specification</cite>.
72 * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
75 * @param <T> the type of the class modeled by this {@code Class}
76 * object. For example, the type of {@code String.class} is {@code
77 * Class<String>}. Use {@code Class<?>} if the class being modeled is
81 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
85 class Class<T> implements java.io.Serializable,
86 java.lang.reflect.GenericDeclaration,
87 java.lang.reflect.Type,
88 java.lang.reflect.AnnotatedElement {
89 private static final int ANNOTATION= 0x00002000;
90 private static final int ENUM = 0x00004000;
91 private static final int SYNTHETIC = 0x00001000;
94 * Constructor. Only the Java Virtual Machine creates Class
101 * Converts the object to a string. The string representation is the
102 * string "class" or "interface", followed by a space, and then by the
103 * fully qualified name of the class in the format returned by
104 * {@code getName}. If this {@code Class} object represents a
105 * primitive type, this method returns the name of the primitive type. If
106 * this {@code Class} object represents void this method returns
109 * @return a string representation of this class object.
111 public String toString() {
112 return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
118 * Returns the {@code Class} object associated with the class or
119 * interface with the given string name. Invoking this method is
123 * {@code Class.forName(className, true, currentLoader)}
126 * where {@code currentLoader} denotes the defining class loader of
129 * <p> For example, the following code fragment returns the
130 * runtime {@code Class} descriptor for the class named
131 * {@code java.lang.Thread}:
134 * {@code Class t = Class.forName("java.lang.Thread")}
137 * A call to {@code forName("X")} causes the class named
138 * {@code X} to be initialized.
140 * @param className the fully qualified name of the desired class.
141 * @return the {@code Class} object for the class with the
143 * @exception LinkageError if the linkage fails
144 * @exception ExceptionInInitializerError if the initialization provoked
145 * by this method fails
146 * @exception ClassNotFoundException if the class cannot be located
148 public static Class<?> forName(String className)
149 throws ClassNotFoundException {
150 if (className.startsWith("[")) {
151 Class<?> arrType = defineArray(className);
152 Class<?> c = arrType;
153 while (c != null && c.isArray()) {
154 c = c.getComponentType0(); // verify component type is sane
158 Class<?> c = loadCls(className, className.replace('.', '_'));
160 throw new ClassNotFoundException(className);
167 * Returns the {@code Class} object associated with the class or
168 * interface with the given string name, using the given class loader.
169 * Given the fully qualified name for a class or interface (in the same
170 * format returned by {@code getName}) this method attempts to
171 * locate, load, and link the class or interface. The specified class
172 * loader is used to load the class or interface. If the parameter
173 * {@code loader} is null, the class is loaded through the bootstrap
174 * class loader. The class is initialized only if the
175 * {@code initialize} parameter is {@code true} and if it has
176 * not been initialized earlier.
178 * <p> If {@code name} denotes a primitive type or void, an attempt
179 * will be made to locate a user-defined class in the unnamed package whose
180 * name is {@code name}. Therefore, this method cannot be used to
181 * obtain any of the {@code Class} objects representing primitive
184 * <p> If {@code name} denotes an array class, the component type of
185 * the array class is loaded but not initialized.
187 * <p> For example, in an instance method the expression:
190 * {@code Class.forName("Foo")}
196 * {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
199 * Note that this method throws errors related to loading, linking or
200 * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
201 * Java Language Specification</em>.
202 * Note that this method does not check whether the requested class
203 * is accessible to its caller.
205 * <p> If the {@code loader} is {@code null}, and a security
206 * manager is present, and the caller's class loader is not null, then this
207 * method calls the security manager's {@code checkPermission} method
208 * with a {@code RuntimePermission("getClassLoader")} permission to
209 * ensure it's ok to access the bootstrap class loader.
211 * @param name fully qualified name of the desired class
212 * @param initialize whether the class must be initialized
213 * @param loader class loader from which the class must be loaded
214 * @return class object representing the desired class
216 * @exception LinkageError if the linkage fails
217 * @exception ExceptionInInitializerError if the initialization provoked
218 * by this method fails
219 * @exception ClassNotFoundException if the class cannot be located by
220 * the specified class loader
222 * @see java.lang.Class#forName(String)
223 * @see java.lang.ClassLoader
226 public static Class<?> forName(String name, boolean initialize,
228 throws ClassNotFoundException
230 return forName(name);
233 @JavaScriptBody(args = {"n", "c" }, body =
234 "if (vm[c]) return vm[c].$class;\n"
235 + "if (vm.loadClass) {\n"
236 + " vm.loadClass(n);\n"
237 + " if (vm[c]) return vm[c].$class;\n"
241 private static native Class<?> loadCls(String n, String c);
245 * Creates a new instance of the class represented by this {@code Class}
246 * object. The class is instantiated as if by a {@code new}
247 * expression with an empty argument list. The class is initialized if it
248 * has not already been initialized.
250 * <p>Note that this method propagates any exception thrown by the
251 * nullary constructor, including a checked exception. Use of
252 * this method effectively bypasses the compile-time exception
253 * checking that would otherwise be performed by the compiler.
255 * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
256 * Constructor.newInstance} method avoids this problem by wrapping
257 * any exception thrown by the constructor in a (checked) {@link
258 * java.lang.reflect.InvocationTargetException}.
260 * @return a newly allocated instance of the class represented by this
262 * @exception IllegalAccessException if the class or its nullary
263 * constructor is not accessible.
264 * @exception InstantiationException
265 * if this {@code Class} represents an abstract class,
266 * an interface, an array class, a primitive type, or void;
267 * or if the class has no nullary constructor;
268 * or if the instantiation fails for some other reason.
269 * @exception ExceptionInInitializerError if the initialization
270 * provoked by this method fails.
271 * @exception SecurityException
272 * If a security manager, <i>s</i>, is present and any of the
273 * following conditions is met:
278 * {@link SecurityManager#checkMemberAccess
279 * s.checkMemberAccess(this, Member.PUBLIC)} denies
280 * creation of new instances of this class
282 * <li> the caller's class loader is not the same as or an
283 * ancestor of the class loader for the current class and
284 * invocation of {@link SecurityManager#checkPackageAccess
285 * s.checkPackageAccess()} denies access to the package
291 @JavaScriptBody(args = { "self", "illegal" }, body =
292 "\nvar c = self.cnstr;"
293 + "\nif (c['cons__V']) {"
294 + "\n if ((c.cons__V.access & 0x1) != 0) {"
295 + "\n var inst = c();"
296 + "\n c.cons__V.call(inst);"
299 + "\n return illegal;"
303 private static native Object newInstance0(Class<?> self, Object illegal);
305 public T newInstance()
306 throws InstantiationException, IllegalAccessException
308 Object illegal = new Object();
309 Object inst = newInstance0(this, illegal);
311 throw new InstantiationException(getName());
313 if (inst == illegal) {
314 throw new IllegalAccessException();
320 * Determines if the specified {@code Object} is assignment-compatible
321 * with the object represented by this {@code Class}. This method is
322 * the dynamic equivalent of the Java language {@code instanceof}
323 * operator. The method returns {@code true} if the specified
324 * {@code Object} argument is non-null and can be cast to the
325 * reference type represented by this {@code Class} object without
326 * raising a {@code ClassCastException.} It returns {@code false}
329 * <p> Specifically, if this {@code Class} object represents a
330 * declared class, this method returns {@code true} if the specified
331 * {@code Object} argument is an instance of the represented class (or
332 * of any of its subclasses); it returns {@code false} otherwise. If
333 * this {@code Class} object represents an array class, this method
334 * returns {@code true} if the specified {@code Object} argument
335 * can be converted to an object of the array class by an identity
336 * conversion or by a widening reference conversion; it returns
337 * {@code false} otherwise. If this {@code Class} object
338 * represents an interface, this method returns {@code true} if the
339 * class or any superclass of the specified {@code Object} argument
340 * implements this interface; it returns {@code false} otherwise. If
341 * this {@code Class} object represents a primitive type, this method
342 * returns {@code false}.
344 * @param obj the object to check
345 * @return true if {@code obj} is an instance of this class
349 public boolean isInstance(Object obj) {
354 return isAssignableFrom(obj.getClass());
357 String prop = "$instOf_" + getName().replace('.', '_');
358 return hasProperty(obj, prop);
361 @JavaScriptBody(args = { "who", "prop" }, body =
362 "if (who[prop]) return true; else return false;"
364 private static native boolean hasProperty(Object who, String prop);
368 * Determines if the class or interface represented by this
369 * {@code Class} object is either the same as, or is a superclass or
370 * superinterface of, the class or interface represented by the specified
371 * {@code Class} parameter. It returns {@code true} if so;
372 * otherwise it returns {@code false}. If this {@code Class}
373 * object represents a primitive type, this method returns
374 * {@code true} if the specified {@code Class} parameter is
375 * exactly this {@code Class} object; otherwise it returns
378 * <p> Specifically, this method tests whether the type represented by the
379 * specified {@code Class} parameter can be converted to the type
380 * represented by this {@code Class} object via an identity conversion
381 * or via a widening reference conversion. See <em>The Java Language
382 * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
384 * @param cls the {@code Class} object to be checked
385 * @return the {@code boolean} value indicating whether objects of the
386 * type {@code cls} can be assigned to objects of this class
387 * @exception NullPointerException if the specified Class parameter is
391 public boolean isAssignableFrom(Class<?> cls) {
397 final Class<?> cmpType = cls.getComponentType();
399 return this == cmpType;
401 return cmpType != null && getComponentType().isAssignableFrom(cmpType);
403 String prop = "$instOf_" + getName().replace('.', '_');
404 return hasProperty(cls, prop);
409 * Determines if the specified {@code Class} object represents an
412 * @return {@code true} if this object represents an interface;
413 * {@code false} otherwise.
415 public boolean isInterface() {
416 return (getAccess() & 0x200) != 0;
419 @JavaScriptBody(args = {}, body = "return this.access;")
420 private native int getAccess();
424 * Determines if this {@code Class} object represents an array class.
426 * @return {@code true} if this object represents an array class;
427 * {@code false} otherwise.
430 public boolean isArray() {
431 return hasProperty(this, "array"); // NOI18N
436 * Determines if the specified {@code Class} object represents a
439 * <p> There are nine predefined {@code Class} objects to represent
440 * the eight primitive types and void. These are created by the Java
441 * Virtual Machine, and have the same names as the primitive types that
442 * they represent, namely {@code boolean}, {@code byte},
443 * {@code char}, {@code short}, {@code int},
444 * {@code long}, {@code float}, and {@code double}.
446 * <p> These objects may only be accessed via the following public static
447 * final variables, and are the only {@code Class} objects for which
448 * this method returns {@code true}.
450 * @return true if and only if this class represents a primitive type
452 * @see java.lang.Boolean#TYPE
453 * @see java.lang.Character#TYPE
454 * @see java.lang.Byte#TYPE
455 * @see java.lang.Short#TYPE
456 * @see java.lang.Integer#TYPE
457 * @see java.lang.Long#TYPE
458 * @see java.lang.Float#TYPE
459 * @see java.lang.Double#TYPE
460 * @see java.lang.Void#TYPE
463 @JavaScriptBody(args = {}, body =
464 "if (this.primitive) return true;"
465 + "else return false;"
467 public native boolean isPrimitive();
470 * Returns true if this {@code Class} object represents an annotation
471 * type. Note that if this method returns true, {@link #isInterface()}
472 * would also return true, as all annotation types are also interfaces.
474 * @return {@code true} if this class object represents an annotation
475 * type; {@code false} otherwise
478 public boolean isAnnotation() {
479 return (getModifiers() & ANNOTATION) != 0;
483 * Returns {@code true} if this class is a synthetic class;
484 * returns {@code false} otherwise.
485 * @return {@code true} if and only if this class is a synthetic class as
486 * defined by the Java Language Specification.
489 public boolean isSynthetic() {
490 return (getModifiers() & SYNTHETIC) != 0;
494 * Returns the name of the entity (class, interface, array class,
495 * primitive type, or void) represented by this {@code Class} object,
496 * as a {@code String}.
498 * <p> If this class object represents a reference type that is not an
499 * array type then the binary name of the class is returned, as specified
501 * <cite>The Java™ Language Specification</cite>.
503 * <p> If this class object represents a primitive type or void, then the
504 * name returned is a {@code String} equal to the Java language
505 * keyword corresponding to the primitive type or void.
507 * <p> If this class object represents a class of arrays, then the internal
508 * form of the name consists of the name of the element type preceded by
509 * one or more '{@code [}' characters representing the depth of the array
510 * nesting. The encoding of element type names is as follows:
512 * <blockquote><table summary="Element types and encodings">
513 * <tr><th> Element Type <th> <th> Encoding
514 * <tr><td> boolean <td> <td align=center> Z
515 * <tr><td> byte <td> <td align=center> B
516 * <tr><td> char <td> <td align=center> C
517 * <tr><td> class or interface
518 * <td> <td align=center> L<i>classname</i>;
519 * <tr><td> double <td> <td align=center> D
520 * <tr><td> float <td> <td align=center> F
521 * <tr><td> int <td> <td align=center> I
522 * <tr><td> long <td> <td align=center> J
523 * <tr><td> short <td> <td align=center> S
524 * </table></blockquote>
526 * <p> The class or interface name <i>classname</i> is the binary name of
527 * the class specified above.
531 * String.class.getName()
532 * returns "java.lang.String"
533 * byte.class.getName()
535 * (new Object[3]).getClass().getName()
536 * returns "[Ljava.lang.Object;"
537 * (new int[3][4][5][6][7][8][9]).getClass().getName()
539 * </pre></blockquote>
541 * @return the name of the class or interface
542 * represented by this object.
544 public String getName() {
545 return jvmName().replace('/', '.');
548 @JavaScriptBody(args = {}, body = "return this.jvmName;")
549 private native String jvmName();
553 * Returns an array of {@code TypeVariable} objects that represent the
554 * type variables declared by the generic declaration represented by this
555 * {@code GenericDeclaration} object, in declaration order. Returns an
556 * array of length 0 if the underlying generic declaration declares no type
559 * @return an array of {@code TypeVariable} objects that represent
560 * the type variables declared by this generic declaration
561 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
562 * signature of this generic declaration does not conform to
563 * the format specified in
564 * <cite>The Java™ Virtual Machine Specification</cite>
567 public TypeVariable<Class<T>>[] getTypeParameters() {
568 throw new UnsupportedOperationException();
572 * Returns the {@code Class} representing the superclass of the entity
573 * (class, interface, primitive type or void) represented by this
574 * {@code Class}. If this {@code Class} represents either the
575 * {@code Object} class, an interface, a primitive type, or void, then
576 * null is returned. If this object represents an array class then the
577 * {@code Class} object representing the {@code Object} class is
580 * @return the superclass of the class represented by this object.
582 @JavaScriptBody(args = {}, body = "return this.superclass;")
583 public native Class<? super T> getSuperclass();
586 * Returns the Java language modifiers for this class or interface, encoded
587 * in an integer. The modifiers consist of the Java Virtual Machine's
588 * constants for {@code public}, {@code protected},
589 * {@code private}, {@code final}, {@code static},
590 * {@code abstract} and {@code interface}; they should be decoded
591 * using the methods of class {@code Modifier}.
593 * <p> If the underlying class is an array class, then its
594 * {@code public}, {@code private} and {@code protected}
595 * modifiers are the same as those of its component type. If this
596 * {@code Class} represents a primitive type or void, its
597 * {@code public} modifier is always {@code true}, and its
598 * {@code protected} and {@code private} modifiers are always
599 * {@code false}. If this object represents an array class, a
600 * primitive type or void, then its {@code final} modifier is always
601 * {@code true} and its interface modifier is always
602 * {@code false}. The values of its other modifiers are not determined
603 * by this specification.
605 * <p> The modifier encodings are defined in <em>The Java Virtual Machine
606 * Specification</em>, table 4.1.
608 * @return the {@code int} representing the modifiers for this class
609 * @see java.lang.reflect.Modifier
612 public int getModifiers() {
618 * Returns the simple name of the underlying class as given in the
619 * source code. Returns an empty string if the underlying class is
622 * <p>The simple name of an array is the simple name of the
623 * component type with "[]" appended. In particular the simple
624 * name of an array whose component type is anonymous is "[]".
626 * @return the simple name of the underlying class
629 public String getSimpleName() {
631 return getComponentType().getSimpleName()+"[]";
633 String simpleName = getSimpleBinaryName();
634 if (simpleName == null) { // top level class
635 simpleName = getName();
636 return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
638 // According to JLS3 "Binary Compatibility" (13.1) the binary
639 // name of non-package classes (not top level) is the binary
640 // name of the immediately enclosing class followed by a '$' followed by:
641 // (for nested and inner classes): the simple name.
642 // (for local classes): 1 or more digits followed by the simple name.
643 // (for anonymous classes): 1 or more digits.
645 // Since getSimpleBinaryName() will strip the binary name of
646 // the immediatly enclosing class, we are now looking at a
647 // string that matches the regular expression "\$[0-9]*"
648 // followed by a simple name (considering the simple of an
649 // anonymous class to be the empty string).
651 // Remove leading "\$[0-9]*" from the name
652 int length = simpleName.length();
653 if (length < 1 || simpleName.charAt(0) != '$')
654 throw new IllegalStateException("Malformed class name");
656 while (index < length && isAsciiDigit(simpleName.charAt(index)))
658 // Eventually, this is the empty string iff this is an anonymous class
659 return simpleName.substring(index);
663 * Returns the "simple binary name" of the underlying class, i.e.,
664 * the binary name without the leading enclosing class name.
665 * Returns {@code null} if the underlying class is a top level
668 private String getSimpleBinaryName() {
669 Class<?> enclosingClass = null; // XXX getEnclosingClass();
670 if (enclosingClass == null) // top level class
672 // Otherwise, strip the enclosing class' name
674 return getName().substring(enclosingClass.getName().length());
675 } catch (IndexOutOfBoundsException ex) {
676 throw new IllegalStateException("Malformed class name");
681 * Returns an array containing {@code Field} objects reflecting all
682 * the accessible public fields of the class or interface represented by
683 * this {@code Class} object. The elements in the array returned are
684 * not sorted and are not in any particular order. This method returns an
685 * array of length 0 if the class or interface has no accessible public
686 * fields, or if it represents an array class, a primitive type, or void.
688 * <p> Specifically, if this {@code Class} object represents a class,
689 * this method returns the public fields of this class and of all its
690 * superclasses. If this {@code Class} object represents an
691 * interface, this method returns the fields of this interface and of all
692 * its superinterfaces.
694 * <p> The implicit length field for array class is not reflected by this
695 * method. User code should use the methods of class {@code Array} to
698 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
700 * @return the array of {@code Field} objects representing the
702 * @exception SecurityException
703 * If a security manager, <i>s</i>, is present and any of the
704 * following conditions is met:
709 * {@link SecurityManager#checkMemberAccess
710 * s.checkMemberAccess(this, Member.PUBLIC)} denies
711 * access to the fields within this class
713 * <li> the caller's class loader is not the same as or an
714 * ancestor of the class loader for the current class and
715 * invocation of {@link SecurityManager#checkPackageAccess
716 * s.checkPackageAccess()} denies access to the package
723 public Field[] getFields() throws SecurityException {
724 throw new SecurityException();
728 * Returns an array containing {@code Method} objects reflecting all
729 * the public <em>member</em> methods of the class or interface represented
730 * by this {@code Class} object, including those declared by the class
731 * or interface and those inherited from superclasses and
732 * superinterfaces. Array classes return all the (public) member methods
733 * inherited from the {@code Object} class. The elements in the array
734 * returned are not sorted and are not in any particular order. This
735 * method returns an array of length 0 if this {@code Class} object
736 * represents a class or interface that has no public member methods, or if
737 * this {@code Class} object represents a primitive type or void.
739 * <p> The class initialization method {@code <clinit>} is not
740 * included in the returned array. If the class declares multiple public
741 * member methods with the same parameter types, they are all included in
742 * the returned array.
744 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
746 * @return the array of {@code Method} objects representing the
747 * public methods of this class
748 * @exception SecurityException
749 * If a security manager, <i>s</i>, is present and any of the
750 * following conditions is met:
755 * {@link SecurityManager#checkMemberAccess
756 * s.checkMemberAccess(this, Member.PUBLIC)} denies
757 * access to the methods within this class
759 * <li> the caller's class loader is not the same as or an
760 * ancestor of the class loader for the current class and
761 * invocation of {@link SecurityManager#checkPackageAccess
762 * s.checkPackageAccess()} denies access to the package
769 public Method[] getMethods() throws SecurityException {
770 return MethodImpl.findMethods(this, 0x01);
774 * Returns a {@code Field} object that reflects the specified public
775 * member field of the class or interface represented by this
776 * {@code Class} object. The {@code name} parameter is a
777 * {@code String} specifying the simple name of the desired field.
779 * <p> The field to be reflected is determined by the algorithm that
780 * follows. Let C be the class represented by this object:
782 * <LI> If C declares a public field with the name specified, that is the
783 * field to be reflected.</LI>
784 * <LI> If no field was found in step 1 above, this algorithm is applied
785 * recursively to each direct superinterface of C. The direct
786 * superinterfaces are searched in the order they were declared.</LI>
787 * <LI> If no field was found in steps 1 and 2 above, and C has a
788 * superclass S, then this algorithm is invoked recursively upon S.
789 * If C has no superclass, then a {@code NoSuchFieldException}
793 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
795 * @param name the field name
796 * @return the {@code Field} object of this class specified by
798 * @exception NoSuchFieldException if a field with the specified name is
800 * @exception NullPointerException if {@code name} is {@code null}
801 * @exception SecurityException
802 * If a security manager, <i>s</i>, is present and any of the
803 * following conditions is met:
808 * {@link SecurityManager#checkMemberAccess
809 * s.checkMemberAccess(this, Member.PUBLIC)} denies
810 * access to the field
812 * <li> the caller's class loader is not the same as or an
813 * ancestor of the class loader for the current class and
814 * invocation of {@link SecurityManager#checkPackageAccess
815 * s.checkPackageAccess()} denies access to the package
822 public Field getField(String name)
823 throws SecurityException {
824 throw new SecurityException();
829 * Returns a {@code Method} object that reflects the specified public
830 * member method of the class or interface represented by this
831 * {@code Class} object. The {@code name} parameter is a
832 * {@code String} specifying the simple name of the desired method. The
833 * {@code parameterTypes} parameter is an array of {@code Class}
834 * objects that identify the method's formal parameter types, in declared
835 * order. If {@code parameterTypes} is {@code null}, it is
836 * treated as if it were an empty array.
838 * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
839 * {@code NoSuchMethodException} is raised. Otherwise, the method to
840 * be reflected is determined by the algorithm that follows. Let C be the
841 * class represented by this object:
843 * <LI> C is searched for any <I>matching methods</I>. If no matching
844 * method is found, the algorithm of step 1 is invoked recursively on
845 * the superclass of C.</LI>
846 * <LI> If no method was found in step 1 above, the superinterfaces of C
847 * are searched for a matching method. If any such method is found, it
851 * To find a matching method in a class C: If C declares exactly one
852 * public method with the specified name and exactly the same formal
853 * parameter types, that is the method reflected. If more than one such
854 * method is found in C, and one of these methods has a return type that is
855 * more specific than any of the others, that method is reflected;
856 * otherwise one of the methods is chosen arbitrarily.
858 * <p>Note that there may be more than one matching method in a
859 * class because while the Java language forbids a class to
860 * declare multiple methods with the same signature but different
861 * return types, the Java virtual machine does not. This
862 * increased flexibility in the virtual machine can be used to
863 * implement various language features. For example, covariant
864 * returns can be implemented with {@linkplain
865 * java.lang.reflect.Method#isBridge bridge methods}; the bridge
866 * method and the method being overridden would have the same
867 * signature but different return types.
869 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
871 * @param name the name of the method
872 * @param parameterTypes the list of parameters
873 * @return the {@code Method} object that matches the specified
874 * {@code name} and {@code parameterTypes}
875 * @exception NoSuchMethodException if a matching method is not found
876 * or if the name is "<init>"or "<clinit>".
877 * @exception NullPointerException if {@code name} is {@code null}
878 * @exception SecurityException
879 * If a security manager, <i>s</i>, is present and any of the
880 * following conditions is met:
885 * {@link SecurityManager#checkMemberAccess
886 * s.checkMemberAccess(this, Member.PUBLIC)} denies
887 * access to the method
889 * <li> the caller's class loader is not the same as or an
890 * ancestor of the class loader for the current class and
891 * invocation of {@link SecurityManager#checkPackageAccess
892 * s.checkPackageAccess()} denies access to the package
899 public Method getMethod(String name, Class<?>... parameterTypes)
900 throws SecurityException, NoSuchMethodException {
901 Method m = MethodImpl.findMethod(this, name, parameterTypes);
903 StringBuilder sb = new StringBuilder();
904 sb.append(getName()).append('.').append(name).append('(');
906 for (int i = 0; i < parameterTypes.length; i++) {
907 sb.append(sep).append(parameterTypes[i].getName());
911 throw new NoSuchMethodException(sb.toString());
917 * Returns an array of {@code Method} objects reflecting all the
918 * methods declared by the class or interface represented by this
919 * {@code Class} object. This includes public, protected, default
920 * (package) access, and private methods, but excludes inherited methods.
921 * The elements in the array returned are not sorted and are not in any
922 * particular order. This method returns an array of length 0 if the class
923 * or interface declares no methods, or if this {@code Class} object
924 * represents a primitive type, an array class, or void. The class
925 * initialization method {@code <clinit>} is not included in the
926 * returned array. If the class declares multiple public member methods
927 * with the same parameter types, they are all included in the returned
930 * <p> See <em>The Java Language Specification</em>, section 8.2.
932 * @return the array of {@code Method} objects representing all the
933 * declared methods of this class
934 * @exception SecurityException
935 * If a security manager, <i>s</i>, is present and any of the
936 * following conditions is met:
941 * {@link SecurityManager#checkMemberAccess
942 * s.checkMemberAccess(this, Member.DECLARED)} denies
943 * access to the declared methods within this class
945 * <li> the caller's class loader is not the same as or an
946 * ancestor of the class loader for the current class and
947 * invocation of {@link SecurityManager#checkPackageAccess
948 * s.checkPackageAccess()} denies access to the package
955 public Method[] getDeclaredMethods() throws SecurityException {
956 throw new SecurityException();
960 * Character.isDigit answers {@code true} to some non-ascii
961 * digits. This one does not.
963 private static boolean isAsciiDigit(char c) {
964 return '0' <= c && c <= '9';
968 * Returns the canonical name of the underlying class as
969 * defined by the Java Language Specification. Returns null if
970 * the underlying class does not have a canonical name (i.e., if
971 * it is a local or anonymous class or an array whose component
972 * type does not have a canonical name).
973 * @return the canonical name of the underlying class if it exists, and
974 * {@code null} otherwise.
977 public String getCanonicalName() {
979 String canonicalName = getComponentType().getCanonicalName();
980 if (canonicalName != null)
981 return canonicalName + "[]";
985 // if (isLocalOrAnonymousClass())
987 // Class<?> enclosingClass = getEnclosingClass();
988 Class<?> enclosingClass = null;
989 if (enclosingClass == null) { // top level class
992 String enclosingName = enclosingClass.getCanonicalName();
993 if (enclosingName == null)
995 return enclosingName + "." + getSimpleName();
1000 * Finds a resource with a given name. The rules for searching resources
1001 * associated with a given class are implemented by the defining
1002 * {@linkplain ClassLoader class loader} of the class. This method
1003 * delegates to this object's class loader. If this object was loaded by
1004 * the bootstrap class loader, the method delegates to {@link
1005 * ClassLoader#getSystemResourceAsStream}.
1007 * <p> Before delegation, an absolute resource name is constructed from the
1008 * given resource name using this algorithm:
1012 * <li> If the {@code name} begins with a {@code '/'}
1013 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
1014 * portion of the {@code name} following the {@code '/'}.
1016 * <li> Otherwise, the absolute name is of the following form:
1019 * {@code modified_package_name/name}
1022 * <p> Where the {@code modified_package_name} is the package name of this
1023 * object with {@code '/'} substituted for {@code '.'}
1024 * (<tt>'\u002e'</tt>).
1028 * @param name name of the desired resource
1029 * @return A {@link java.io.InputStream} object or {@code null} if
1030 * no resource with this name is found
1031 * @throws NullPointerException If {@code name} is {@code null}
1034 public InputStream getResourceAsStream(String name) {
1035 name = resolveName(name);
1036 byte[] arr = getResourceAsStream0(name);
1037 return arr == null ? null : new ByteArrayInputStream(arr);
1040 @JavaScriptBody(args = "name", body =
1041 "return (vm.loadBytes) ? vm.loadBytes(name) : null;"
1043 private static native byte[] getResourceAsStream0(String name);
1046 * Finds a resource with a given name. The rules for searching resources
1047 * associated with a given class are implemented by the defining
1048 * {@linkplain ClassLoader class loader} of the class. This method
1049 * delegates to this object's class loader. If this object was loaded by
1050 * the bootstrap class loader, the method delegates to {@link
1051 * ClassLoader#getSystemResource}.
1053 * <p> Before delegation, an absolute resource name is constructed from the
1054 * given resource name using this algorithm:
1058 * <li> If the {@code name} begins with a {@code '/'}
1059 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
1060 * portion of the {@code name} following the {@code '/'}.
1062 * <li> Otherwise, the absolute name is of the following form:
1065 * {@code modified_package_name/name}
1068 * <p> Where the {@code modified_package_name} is the package name of this
1069 * object with {@code '/'} substituted for {@code '.'}
1070 * (<tt>'\u002e'</tt>).
1074 * @param name name of the desired resource
1075 * @return A {@link java.net.URL} object or {@code null} if no
1076 * resource with this name is found
1079 public java.net.URL getResource(String name) {
1080 InputStream is = getResourceAsStream(name);
1081 return is == null ? null : newResourceURL(URL.class, "res:/" + name, is);
1084 @JavaScriptBody(args = { "url", "spec", "is" }, body =
1085 "var u = url.cnstr(true);\n"
1086 + "u.constructor.cons__VLjava_lang_String_2Ljava_io_InputStream_2.call(u, spec, is);\n"
1089 private static native URL newResourceURL(Class<URL> url, String spec, InputStream is);
1092 * Add a package name prefix if the name is not absolute Remove leading "/"
1093 * if name is absolute
1095 private String resolveName(String name) {
1099 if (!name.startsWith("/")) {
1101 while (c.isArray()) {
1102 c = c.getComponentType();
1104 String baseName = c.getName();
1105 int index = baseName.lastIndexOf('.');
1107 name = baseName.substring(0, index).replace('.', '/')
1111 name = name.substring(1);
1117 * Returns the class loader for the class. Some implementations may use
1118 * null to represent the bootstrap class loader. This method will return
1119 * null in such implementations if this class was loaded by the bootstrap
1122 * <p> If a security manager is present, and the caller's class loader is
1123 * not null and the caller's class loader is not the same as or an ancestor of
1124 * the class loader for the class whose class loader is requested, then
1125 * this method calls the security manager's {@code checkPermission}
1126 * method with a {@code RuntimePermission("getClassLoader")}
1127 * permission to ensure it's ok to access the class loader for the class.
1130 * represents a primitive type or void, null is returned.
1132 * @return the class loader that loaded the class or interface
1133 * represented by this object.
1134 * @throws SecurityException
1135 * if a security manager exists and its
1136 * {@code checkPermission} method denies
1137 * access to the class loader for the class.
1138 * @see java.lang.ClassLoader
1139 * @see SecurityManager#checkPermission
1140 * @see java.lang.RuntimePermission
1142 public ClassLoader getClassLoader() {
1143 throw new SecurityException();
1147 * Determines the interfaces implemented by the class or interface
1148 * represented by this object.
1150 * <p> If this object represents a class, the return value is an array
1151 * containing objects representing all interfaces implemented by the
1152 * class. The order of the interface objects in the array corresponds to
1153 * the order of the interface names in the {@code implements} clause
1154 * of the declaration of the class represented by this object. For
1155 * example, given the declaration:
1157 * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
1159 * suppose the value of {@code s} is an instance of
1160 * {@code Shimmer}; the value of the expression:
1162 * {@code s.getClass().getInterfaces()[0]}
1164 * is the {@code Class} object that represents interface
1165 * {@code FloorWax}; and the value of:
1167 * {@code s.getClass().getInterfaces()[1]}
1169 * is the {@code Class} object that represents interface
1170 * {@code DessertTopping}.
1172 * <p> If this object represents an interface, the array contains objects
1173 * representing all interfaces extended by the interface. The order of the
1174 * interface objects in the array corresponds to the order of the interface
1175 * names in the {@code extends} clause of the declaration of the
1176 * interface represented by this object.
1178 * <p> If this object represents a class or interface that implements no
1179 * interfaces, the method returns an array of length 0.
1181 * <p> If this object represents a primitive type or void, the method
1182 * returns an array of length 0.
1184 * @return an array of interfaces implemented by this class.
1186 public native Class<?>[] getInterfaces();
1189 * Returns the {@code Class} representing the component type of an
1190 * array. If this class does not represent an array class this method
1193 * @return the {@code Class} representing the component type of this
1194 * class if this class is an array
1195 * @see java.lang.reflect.Array
1198 public Class<?> getComponentType() {
1201 return getComponentType0();
1202 } catch (ClassNotFoundException cnfe) {
1203 throw new IllegalStateException(cnfe);
1209 private Class<?> getComponentType0() throws ClassNotFoundException {
1210 String n = getName().substring(1);
1211 switch (n.charAt(0)) {
1213 n = n.substring(1, n.length() - 1);
1214 return Class.forName(n);
1216 return Integer.TYPE;
1226 return Boolean.TYPE;
1232 return Character.TYPE;
1234 return defineArray(n);
1236 throw new ClassNotFoundException("Unknown component type of " + getName());
1240 @JavaScriptBody(args = { "sig" }, body =
1241 "var c = Array[sig];\n" +
1242 "if (c) return c;\n" +
1243 "c = vm.java_lang_Class(true);\n" +
1244 "c.jvmName = sig;\n" +
1245 "c.superclass = vm.java_lang_Object(false).$class;\n" +
1246 "c.array = true;\n" +
1247 "Array[sig] = c;\n" +
1250 private static native Class<?> defineArray(String sig);
1253 * Returns true if and only if this class was declared as an enum in the
1256 * @return true if and only if this class was declared as an enum in the
1260 public boolean isEnum() {
1261 // An enum must both directly extend java.lang.Enum and have
1262 // the ENUM bit set; classes for specialized enum constants
1263 // don't do the former.
1264 return (this.getModifiers() & ENUM) != 0 &&
1265 this.getSuperclass() == java.lang.Enum.class;
1269 * Casts an object to the class or interface represented
1270 * by this {@code Class} object.
1272 * @param obj the object to be cast
1273 * @return the object after casting, or null if obj is null
1275 * @throws ClassCastException if the object is not
1276 * null and is not assignable to the type T.
1280 public T cast(Object obj) {
1281 if (obj != null && !isInstance(obj))
1282 throw new ClassCastException(cannotCastMsg(obj));
1286 private String cannotCastMsg(Object obj) {
1287 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
1291 * Casts this {@code Class} object to represent a subclass of the class
1292 * represented by the specified class object. Checks that that the cast
1293 * is valid, and throws a {@code ClassCastException} if it is not. If
1294 * this method succeeds, it always returns a reference to this class object.
1296 * <p>This method is useful when a client needs to "narrow" the type of
1297 * a {@code Class} object to pass it to an API that restricts the
1298 * {@code Class} objects that it is willing to accept. A cast would
1299 * generate a compile-time warning, as the correctness of the cast
1300 * could not be checked at runtime (because generic types are implemented
1303 * @return this {@code Class} object, cast to represent a subclass of
1304 * the specified class object.
1305 * @throws ClassCastException if this {@code Class} object does not
1306 * represent a subclass of the specified class (here "subclass" includes
1307 * the class itself).
1310 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
1311 if (clazz.isAssignableFrom(this))
1312 return (Class<? extends U>) this;
1314 throw new ClassCastException(this.toString());
1317 @JavaScriptBody(args = { "ac" },
1320 + " return this.anno['L' + ac.jvmName + ';'];"
1321 + "} else return null;"
1323 private Object getAnnotationData(Class<?> annotationClass) {
1324 throw new UnsupportedOperationException();
1327 * @throws NullPointerException {@inheritDoc}
1330 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
1331 Object data = getAnnotationData(annotationClass);
1332 return data == null ? null : AnnotationImpl.create(annotationClass, data);
1336 * @throws NullPointerException {@inheritDoc}
1339 @JavaScriptBody(args = { "ac" },
1340 body = "if (this.anno && this.anno['L' + ac.jvmName + ';']) { return true; }"
1341 + "else return false;"
1343 public boolean isAnnotationPresent(
1344 Class<? extends Annotation> annotationClass) {
1345 if (annotationClass == null)
1346 throw new NullPointerException();
1348 return getAnnotation(annotationClass) != null;
1351 @JavaScriptBody(args = {}, body = "return this.anno;")
1352 private Object getAnnotationData() {
1353 throw new UnsupportedOperationException();
1359 public Annotation[] getAnnotations() {
1360 Object data = getAnnotationData();
1361 return data == null ? new Annotation[0] : AnnotationImpl.create(data);
1367 public Annotation[] getDeclaredAnnotations() {
1368 throw new UnsupportedOperationException();
1371 @JavaScriptBody(args = "type", body = ""
1372 + "var c = vm.java_lang_Class(true);"
1373 + "c.jvmName = type;"
1374 + "c.primitive = true;"
1377 native static Class getPrimitiveClass(String type);
1379 @JavaScriptBody(args = {}, body =
1380 "return vm.desiredAssertionStatus ? vm.desiredAssertionStatus : false;"
1382 public native boolean desiredAssertionStatus();