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;
35 import org.apidesign.bck2brwsr.core.JavaScriptBody;
36 import org.apidesign.bck2brwsr.emul.reflect.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);
166 * Returns the {@code Class} object associated with the class or
167 * interface with the given string name, using the given class loader.
168 * Given the fully qualified name for a class or interface (in the same
169 * format returned by {@code getName}) this method attempts to
170 * locate, load, and link the class or interface. The specified class
171 * loader is used to load the class or interface. If the parameter
172 * {@code loader} is null, the class is loaded through the bootstrap
173 * class loader. The class is initialized only if the
174 * {@code initialize} parameter is {@code true} and if it has
175 * not been initialized earlier.
177 * <p> If {@code name} denotes a primitive type or void, an attempt
178 * will be made to locate a user-defined class in the unnamed package whose
179 * name is {@code name}. Therefore, this method cannot be used to
180 * obtain any of the {@code Class} objects representing primitive
183 * <p> If {@code name} denotes an array class, the component type of
184 * the array class is loaded but not initialized.
186 * <p> For example, in an instance method the expression:
189 * {@code Class.forName("Foo")}
195 * {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
198 * Note that this method throws errors related to loading, linking or
199 * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
200 * Java Language Specification</em>.
201 * Note that this method does not check whether the requested class
202 * is accessible to its caller.
204 * <p> If the {@code loader} is {@code null}, and a security
205 * manager is present, and the caller's class loader is not null, then this
206 * method calls the security manager's {@code checkPermission} method
207 * with a {@code RuntimePermission("getClassLoader")} permission to
208 * ensure it's ok to access the bootstrap class loader.
210 * @param name fully qualified name of the desired class
211 * @param initialize whether the class must be initialized
212 * @param loader class loader from which the class must be loaded
213 * @return class object representing the desired class
215 * @exception LinkageError if the linkage fails
216 * @exception ExceptionInInitializerError if the initialization provoked
217 * by this method fails
218 * @exception ClassNotFoundException if the class cannot be located by
219 * the specified class loader
221 * @see java.lang.Class#forName(String)
222 * @see java.lang.ClassLoader
225 public static Class<?> forName(String name, boolean initialize,
227 throws ClassNotFoundException
229 return forName(name);
232 @JavaScriptBody(args = {"n", "c" }, body =
233 "if (vm[c]) return vm[c].$class;\n"
234 + "if (vm.loadClass) {\n"
235 + " vm.loadClass(n);\n"
236 + " if (vm[c]) return vm[c].$class;\n"
240 private static native Class<?> loadCls(String n, String c);
244 * Creates a new instance of the class represented by this {@code Class}
245 * object. The class is instantiated as if by a {@code new}
246 * expression with an empty argument list. The class is initialized if it
247 * has not already been initialized.
249 * <p>Note that this method propagates any exception thrown by the
250 * nullary constructor, including a checked exception. Use of
251 * this method effectively bypasses the compile-time exception
252 * checking that would otherwise be performed by the compiler.
254 * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
255 * Constructor.newInstance} method avoids this problem by wrapping
256 * any exception thrown by the constructor in a (checked) {@link
257 * java.lang.reflect.InvocationTargetException}.
259 * @return a newly allocated instance of the class represented by this
261 * @exception IllegalAccessException if the class or its nullary
262 * constructor is not accessible.
263 * @exception InstantiationException
264 * if this {@code Class} represents an abstract class,
265 * an interface, an array class, a primitive type, or void;
266 * or if the class has no nullary constructor;
267 * or if the instantiation fails for some other reason.
268 * @exception ExceptionInInitializerError if the initialization
269 * provoked by this method fails.
270 * @exception SecurityException
271 * If a security manager, <i>s</i>, is present and any of the
272 * following conditions is met:
277 * {@link SecurityManager#checkMemberAccess
278 * s.checkMemberAccess(this, Member.PUBLIC)} denies
279 * creation of new instances of this class
281 * <li> the caller's class loader is not the same as or an
282 * ancestor of the class loader for the current class and
283 * invocation of {@link SecurityManager#checkPackageAccess
284 * s.checkPackageAccess()} denies access to the package
290 @JavaScriptBody(args = { "self", "illegal" }, body =
291 "\nvar c = self.cnstr;"
292 + "\nif (c['cons__V']) {"
293 + "\n if ((c.cons__V.access & 0x1) != 0) {"
294 + "\n var inst = c();"
295 + "\n c.cons__V.call(inst);"
298 + "\n return illegal;"
302 private static native Object newInstance0(Class<?> self, Object illegal);
304 public T newInstance()
305 throws InstantiationException, IllegalAccessException
307 Object illegal = new Object();
308 Object inst = newInstance0(this, illegal);
310 throw new InstantiationException(getName());
312 if (inst == illegal) {
313 throw new IllegalAccessException();
319 * Determines if the specified {@code Object} is assignment-compatible
320 * with the object represented by this {@code Class}. This method is
321 * the dynamic equivalent of the Java language {@code instanceof}
322 * operator. The method returns {@code true} if the specified
323 * {@code Object} argument is non-null and can be cast to the
324 * reference type represented by this {@code Class} object without
325 * raising a {@code ClassCastException.} It returns {@code false}
328 * <p> Specifically, if this {@code Class} object represents a
329 * declared class, this method returns {@code true} if the specified
330 * {@code Object} argument is an instance of the represented class (or
331 * of any of its subclasses); it returns {@code false} otherwise. If
332 * this {@code Class} object represents an array class, this method
333 * returns {@code true} if the specified {@code Object} argument
334 * can be converted to an object of the array class by an identity
335 * conversion or by a widening reference conversion; it returns
336 * {@code false} otherwise. If this {@code Class} object
337 * represents an interface, this method returns {@code true} if the
338 * class or any superclass of the specified {@code Object} argument
339 * implements this interface; it returns {@code false} otherwise. If
340 * this {@code Class} object represents a primitive type, this method
341 * returns {@code false}.
343 * @param obj the object to check
344 * @return true if {@code obj} is an instance of this class
348 public boolean isInstance(Object obj) {
349 String prop = "$instOf_" + getName().replace('.', '_');
350 return hasProperty(obj, prop);
353 @JavaScriptBody(args = { "who", "prop" }, body =
354 "if (who[prop]) return true; else return false;"
356 private static native boolean hasProperty(Object who, String prop);
360 * Determines if the class or interface represented by this
361 * {@code Class} object is either the same as, or is a superclass or
362 * superinterface of, the class or interface represented by the specified
363 * {@code Class} parameter. It returns {@code true} if so;
364 * otherwise it returns {@code false}. If this {@code Class}
365 * object represents a primitive type, this method returns
366 * {@code true} if the specified {@code Class} parameter is
367 * exactly this {@code Class} object; otherwise it returns
370 * <p> Specifically, this method tests whether the type represented by the
371 * specified {@code Class} parameter can be converted to the type
372 * represented by this {@code Class} object via an identity conversion
373 * or via a widening reference conversion. See <em>The Java Language
374 * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
376 * @param cls the {@code Class} object to be checked
377 * @return the {@code boolean} value indicating whether objects of the
378 * type {@code cls} can be assigned to objects of this class
379 * @exception NullPointerException if the specified Class parameter is
383 public native boolean isAssignableFrom(Class<?> cls);
387 * Determines if the specified {@code Class} object represents an
390 * @return {@code true} if this object represents an interface;
391 * {@code false} otherwise.
393 public boolean isInterface() {
394 return (getAccess() & 0x200) != 0;
397 @JavaScriptBody(args = {}, body = "return this.access;")
398 private native int getAccess();
402 * Determines if this {@code Class} object represents an array class.
404 * @return {@code true} if this object represents an array class;
405 * {@code false} otherwise.
408 public boolean isArray() {
409 return hasProperty(this, "array"); // NOI18N
414 * Determines if the specified {@code Class} object represents a
417 * <p> There are nine predefined {@code Class} objects to represent
418 * the eight primitive types and void. These are created by the Java
419 * Virtual Machine, and have the same names as the primitive types that
420 * they represent, namely {@code boolean}, {@code byte},
421 * {@code char}, {@code short}, {@code int},
422 * {@code long}, {@code float}, and {@code double}.
424 * <p> These objects may only be accessed via the following public static
425 * final variables, and are the only {@code Class} objects for which
426 * this method returns {@code true}.
428 * @return true if and only if this class represents a primitive type
430 * @see java.lang.Boolean#TYPE
431 * @see java.lang.Character#TYPE
432 * @see java.lang.Byte#TYPE
433 * @see java.lang.Short#TYPE
434 * @see java.lang.Integer#TYPE
435 * @see java.lang.Long#TYPE
436 * @see java.lang.Float#TYPE
437 * @see java.lang.Double#TYPE
438 * @see java.lang.Void#TYPE
441 @JavaScriptBody(args = {}, body =
442 "if (this.primitive) return true;"
443 + "else return false;"
445 public native boolean isPrimitive();
448 * Returns true if this {@code Class} object represents an annotation
449 * type. Note that if this method returns true, {@link #isInterface()}
450 * would also return true, as all annotation types are also interfaces.
452 * @return {@code true} if this class object represents an annotation
453 * type; {@code false} otherwise
456 public boolean isAnnotation() {
457 return (getModifiers() & ANNOTATION) != 0;
461 * Returns {@code true} if this class is a synthetic class;
462 * returns {@code false} otherwise.
463 * @return {@code true} if and only if this class is a synthetic class as
464 * defined by the Java Language Specification.
467 public boolean isSynthetic() {
468 return (getModifiers() & SYNTHETIC) != 0;
472 * Returns the name of the entity (class, interface, array class,
473 * primitive type, or void) represented by this {@code Class} object,
474 * as a {@code String}.
476 * <p> If this class object represents a reference type that is not an
477 * array type then the binary name of the class is returned, as specified
479 * <cite>The Java™ Language Specification</cite>.
481 * <p> If this class object represents a primitive type or void, then the
482 * name returned is a {@code String} equal to the Java language
483 * keyword corresponding to the primitive type or void.
485 * <p> If this class object represents a class of arrays, then the internal
486 * form of the name consists of the name of the element type preceded by
487 * one or more '{@code [}' characters representing the depth of the array
488 * nesting. The encoding of element type names is as follows:
490 * <blockquote><table summary="Element types and encodings">
491 * <tr><th> Element Type <th> <th> Encoding
492 * <tr><td> boolean <td> <td align=center> Z
493 * <tr><td> byte <td> <td align=center> B
494 * <tr><td> char <td> <td align=center> C
495 * <tr><td> class or interface
496 * <td> <td align=center> L<i>classname</i>;
497 * <tr><td> double <td> <td align=center> D
498 * <tr><td> float <td> <td align=center> F
499 * <tr><td> int <td> <td align=center> I
500 * <tr><td> long <td> <td align=center> J
501 * <tr><td> short <td> <td align=center> S
502 * </table></blockquote>
504 * <p> The class or interface name <i>classname</i> is the binary name of
505 * the class specified above.
509 * String.class.getName()
510 * returns "java.lang.String"
511 * byte.class.getName()
513 * (new Object[3]).getClass().getName()
514 * returns "[Ljava.lang.Object;"
515 * (new int[3][4][5][6][7][8][9]).getClass().getName()
517 * </pre></blockquote>
519 * @return the name of the class or interface
520 * represented by this object.
522 public String getName() {
523 return jvmName().replace('/', '.');
526 @JavaScriptBody(args = {}, body = "return this.jvmName;")
527 private native String jvmName();
531 * Returns an array of {@code TypeVariable} objects that represent the
532 * type variables declared by the generic declaration represented by this
533 * {@code GenericDeclaration} object, in declaration order. Returns an
534 * array of length 0 if the underlying generic declaration declares no type
537 * @return an array of {@code TypeVariable} objects that represent
538 * the type variables declared by this generic declaration
539 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
540 * signature of this generic declaration does not conform to
541 * the format specified in
542 * <cite>The Java™ Virtual Machine Specification</cite>
545 public TypeVariable<Class<T>>[] getTypeParameters() {
546 throw new UnsupportedOperationException();
550 * Returns the {@code Class} representing the superclass of the entity
551 * (class, interface, primitive type or void) represented by this
552 * {@code Class}. If this {@code Class} represents either the
553 * {@code Object} class, an interface, a primitive type, or void, then
554 * null is returned. If this object represents an array class then the
555 * {@code Class} object representing the {@code Object} class is
558 * @return the superclass of the class represented by this object.
560 @JavaScriptBody(args = {}, body = "return this.superclass;")
561 public native Class<? super T> getSuperclass();
564 * Returns the Java language modifiers for this class or interface, encoded
565 * in an integer. The modifiers consist of the Java Virtual Machine's
566 * constants for {@code public}, {@code protected},
567 * {@code private}, {@code final}, {@code static},
568 * {@code abstract} and {@code interface}; they should be decoded
569 * using the methods of class {@code Modifier}.
571 * <p> If the underlying class is an array class, then its
572 * {@code public}, {@code private} and {@code protected}
573 * modifiers are the same as those of its component type. If this
574 * {@code Class} represents a primitive type or void, its
575 * {@code public} modifier is always {@code true}, and its
576 * {@code protected} and {@code private} modifiers are always
577 * {@code false}. If this object represents an array class, a
578 * primitive type or void, then its {@code final} modifier is always
579 * {@code true} and its interface modifier is always
580 * {@code false}. The values of its other modifiers are not determined
581 * by this specification.
583 * <p> The modifier encodings are defined in <em>The Java Virtual Machine
584 * Specification</em>, table 4.1.
586 * @return the {@code int} representing the modifiers for this class
587 * @see java.lang.reflect.Modifier
590 public native int getModifiers();
594 * Returns the simple name of the underlying class as given in the
595 * source code. Returns an empty string if the underlying class is
598 * <p>The simple name of an array is the simple name of the
599 * component type with "[]" appended. In particular the simple
600 * name of an array whose component type is anonymous is "[]".
602 * @return the simple name of the underlying class
605 public String getSimpleName() {
607 return getComponentType().getSimpleName()+"[]";
609 String simpleName = getSimpleBinaryName();
610 if (simpleName == null) { // top level class
611 simpleName = getName();
612 return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
614 // According to JLS3 "Binary Compatibility" (13.1) the binary
615 // name of non-package classes (not top level) is the binary
616 // name of the immediately enclosing class followed by a '$' followed by:
617 // (for nested and inner classes): the simple name.
618 // (for local classes): 1 or more digits followed by the simple name.
619 // (for anonymous classes): 1 or more digits.
621 // Since getSimpleBinaryName() will strip the binary name of
622 // the immediatly enclosing class, we are now looking at a
623 // string that matches the regular expression "\$[0-9]*"
624 // followed by a simple name (considering the simple of an
625 // anonymous class to be the empty string).
627 // Remove leading "\$[0-9]*" from the name
628 int length = simpleName.length();
629 if (length < 1 || simpleName.charAt(0) != '$')
630 throw new IllegalStateException("Malformed class name");
632 while (index < length && isAsciiDigit(simpleName.charAt(index)))
634 // Eventually, this is the empty string iff this is an anonymous class
635 return simpleName.substring(index);
639 * Returns the "simple binary name" of the underlying class, i.e.,
640 * the binary name without the leading enclosing class name.
641 * Returns {@code null} if the underlying class is a top level
644 private String getSimpleBinaryName() {
645 Class<?> enclosingClass = null; // XXX getEnclosingClass();
646 if (enclosingClass == null) // top level class
648 // Otherwise, strip the enclosing class' name
650 return getName().substring(enclosingClass.getName().length());
651 } catch (IndexOutOfBoundsException ex) {
652 throw new IllegalStateException("Malformed class name");
657 * Returns an array containing {@code Field} objects reflecting all
658 * the accessible public fields of the class or interface represented by
659 * this {@code Class} object. The elements in the array returned are
660 * not sorted and are not in any particular order. This method returns an
661 * array of length 0 if the class or interface has no accessible public
662 * fields, or if it represents an array class, a primitive type, or void.
664 * <p> Specifically, if this {@code Class} object represents a class,
665 * this method returns the public fields of this class and of all its
666 * superclasses. If this {@code Class} object represents an
667 * interface, this method returns the fields of this interface and of all
668 * its superinterfaces.
670 * <p> The implicit length field for array class is not reflected by this
671 * method. User code should use the methods of class {@code Array} to
674 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
676 * @return the array of {@code Field} objects representing the
678 * @exception SecurityException
679 * If a security manager, <i>s</i>, is present and any of the
680 * following conditions is met:
685 * {@link SecurityManager#checkMemberAccess
686 * s.checkMemberAccess(this, Member.PUBLIC)} denies
687 * access to the fields within this class
689 * <li> the caller's class loader is not the same as or an
690 * ancestor of the class loader for the current class and
691 * invocation of {@link SecurityManager#checkPackageAccess
692 * s.checkPackageAccess()} denies access to the package
699 public Field[] getFields() throws SecurityException {
700 throw new SecurityException();
704 * Returns an array containing {@code Method} objects reflecting all
705 * the public <em>member</em> methods of the class or interface represented
706 * by this {@code Class} object, including those declared by the class
707 * or interface and those inherited from superclasses and
708 * superinterfaces. Array classes return all the (public) member methods
709 * inherited from the {@code Object} class. The elements in the array
710 * returned are not sorted and are not in any particular order. This
711 * method returns an array of length 0 if this {@code Class} object
712 * represents a class or interface that has no public member methods, or if
713 * this {@code Class} object represents a primitive type or void.
715 * <p> The class initialization method {@code <clinit>} is not
716 * included in the returned array. If the class declares multiple public
717 * member methods with the same parameter types, they are all included in
718 * the returned array.
720 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
722 * @return the array of {@code Method} objects representing the
723 * public methods of this class
724 * @exception SecurityException
725 * If a security manager, <i>s</i>, is present and any of the
726 * following conditions is met:
731 * {@link SecurityManager#checkMemberAccess
732 * s.checkMemberAccess(this, Member.PUBLIC)} denies
733 * access to the methods within this class
735 * <li> the caller's class loader is not the same as or an
736 * ancestor of the class loader for the current class and
737 * invocation of {@link SecurityManager#checkPackageAccess
738 * s.checkPackageAccess()} denies access to the package
745 public Method[] getMethods() throws SecurityException {
746 return MethodImpl.findMethods(this, 0x01);
750 * Returns a {@code Field} object that reflects the specified public
751 * member field of the class or interface represented by this
752 * {@code Class} object. The {@code name} parameter is a
753 * {@code String} specifying the simple name of the desired field.
755 * <p> The field to be reflected is determined by the algorithm that
756 * follows. Let C be the class represented by this object:
758 * <LI> If C declares a public field with the name specified, that is the
759 * field to be reflected.</LI>
760 * <LI> If no field was found in step 1 above, this algorithm is applied
761 * recursively to each direct superinterface of C. The direct
762 * superinterfaces are searched in the order they were declared.</LI>
763 * <LI> If no field was found in steps 1 and 2 above, and C has a
764 * superclass S, then this algorithm is invoked recursively upon S.
765 * If C has no superclass, then a {@code NoSuchFieldException}
769 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
771 * @param name the field name
772 * @return the {@code Field} object of this class specified by
774 * @exception NoSuchFieldException if a field with the specified name is
776 * @exception NullPointerException if {@code name} is {@code null}
777 * @exception SecurityException
778 * If a security manager, <i>s</i>, is present and any of the
779 * following conditions is met:
784 * {@link SecurityManager#checkMemberAccess
785 * s.checkMemberAccess(this, Member.PUBLIC)} denies
786 * access to the field
788 * <li> the caller's class loader is not the same as or an
789 * ancestor of the class loader for the current class and
790 * invocation of {@link SecurityManager#checkPackageAccess
791 * s.checkPackageAccess()} denies access to the package
798 public Field getField(String name)
799 throws SecurityException {
800 throw new SecurityException();
805 * Returns a {@code Method} object that reflects the specified public
806 * member method of the class or interface represented by this
807 * {@code Class} object. The {@code name} parameter is a
808 * {@code String} specifying the simple name of the desired method. The
809 * {@code parameterTypes} parameter is an array of {@code Class}
810 * objects that identify the method's formal parameter types, in declared
811 * order. If {@code parameterTypes} is {@code null}, it is
812 * treated as if it were an empty array.
814 * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
815 * {@code NoSuchMethodException} is raised. Otherwise, the method to
816 * be reflected is determined by the algorithm that follows. Let C be the
817 * class represented by this object:
819 * <LI> C is searched for any <I>matching methods</I>. If no matching
820 * method is found, the algorithm of step 1 is invoked recursively on
821 * the superclass of C.</LI>
822 * <LI> If no method was found in step 1 above, the superinterfaces of C
823 * are searched for a matching method. If any such method is found, it
827 * To find a matching method in a class C: If C declares exactly one
828 * public method with the specified name and exactly the same formal
829 * parameter types, that is the method reflected. If more than one such
830 * method is found in C, and one of these methods has a return type that is
831 * more specific than any of the others, that method is reflected;
832 * otherwise one of the methods is chosen arbitrarily.
834 * <p>Note that there may be more than one matching method in a
835 * class because while the Java language forbids a class to
836 * declare multiple methods with the same signature but different
837 * return types, the Java virtual machine does not. This
838 * increased flexibility in the virtual machine can be used to
839 * implement various language features. For example, covariant
840 * returns can be implemented with {@linkplain
841 * java.lang.reflect.Method#isBridge bridge methods}; the bridge
842 * method and the method being overridden would have the same
843 * signature but different return types.
845 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
847 * @param name the name of the method
848 * @param parameterTypes the list of parameters
849 * @return the {@code Method} object that matches the specified
850 * {@code name} and {@code parameterTypes}
851 * @exception NoSuchMethodException if a matching method is not found
852 * or if the name is "<init>"or "<clinit>".
853 * @exception NullPointerException if {@code name} is {@code null}
854 * @exception SecurityException
855 * If a security manager, <i>s</i>, is present and any of the
856 * following conditions is met:
861 * {@link SecurityManager#checkMemberAccess
862 * s.checkMemberAccess(this, Member.PUBLIC)} denies
863 * access to the method
865 * <li> the caller's class loader is not the same as or an
866 * ancestor of the class loader for the current class and
867 * invocation of {@link SecurityManager#checkPackageAccess
868 * s.checkPackageAccess()} denies access to the package
875 public Method getMethod(String name, Class<?>... parameterTypes)
876 throws SecurityException, NoSuchMethodException {
877 Method m = MethodImpl.findMethod(this, name, parameterTypes);
879 StringBuilder sb = new StringBuilder();
880 sb.append(getName()).append('.').append(name).append('(');
882 for (int i = 0; i < parameterTypes.length; i++) {
883 sb.append(sep).append(parameterTypes[i].getName());
887 throw new NoSuchMethodException(sb.toString());
893 * Character.isDigit answers {@code true} to some non-ascii
894 * digits. This one does not.
896 private static boolean isAsciiDigit(char c) {
897 return '0' <= c && c <= '9';
901 * Returns the canonical name of the underlying class as
902 * defined by the Java Language Specification. Returns null if
903 * the underlying class does not have a canonical name (i.e., if
904 * it is a local or anonymous class or an array whose component
905 * type does not have a canonical name).
906 * @return the canonical name of the underlying class if it exists, and
907 * {@code null} otherwise.
910 public String getCanonicalName() {
912 String canonicalName = getComponentType().getCanonicalName();
913 if (canonicalName != null)
914 return canonicalName + "[]";
918 // if (isLocalOrAnonymousClass())
920 // Class<?> enclosingClass = getEnclosingClass();
921 Class<?> enclosingClass = null;
922 if (enclosingClass == null) { // top level class
925 String enclosingName = enclosingClass.getCanonicalName();
926 if (enclosingName == null)
928 return enclosingName + "." + getSimpleName();
933 * Finds a resource with a given name. The rules for searching resources
934 * associated with a given class are implemented by the defining
935 * {@linkplain ClassLoader class loader} of the class. This method
936 * delegates to this object's class loader. If this object was loaded by
937 * the bootstrap class loader, the method delegates to {@link
938 * ClassLoader#getSystemResourceAsStream}.
940 * <p> Before delegation, an absolute resource name is constructed from the
941 * given resource name using this algorithm:
945 * <li> If the {@code name} begins with a {@code '/'}
946 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
947 * portion of the {@code name} following the {@code '/'}.
949 * <li> Otherwise, the absolute name is of the following form:
952 * {@code modified_package_name/name}
955 * <p> Where the {@code modified_package_name} is the package name of this
956 * object with {@code '/'} substituted for {@code '.'}
957 * (<tt>'\u002e'</tt>).
961 * @param name name of the desired resource
962 * @return A {@link java.io.InputStream} object or {@code null} if
963 * no resource with this name is found
964 * @throws NullPointerException If {@code name} is {@code null}
967 public InputStream getResourceAsStream(String name) {
968 name = resolveName(name);
969 byte[] arr = getResourceAsStream0(name);
970 return arr == null ? null : new ByteArrayInputStream(arr);
973 @JavaScriptBody(args = "name", body =
974 "return (vm.loadBytes) ? vm.loadBytes(name) : null;"
976 private static native byte[] getResourceAsStream0(String name);
979 * Finds a resource with a given name. The rules for searching resources
980 * associated with a given class are implemented by the defining
981 * {@linkplain ClassLoader class loader} of the class. This method
982 * delegates to this object's class loader. If this object was loaded by
983 * the bootstrap class loader, the method delegates to {@link
984 * ClassLoader#getSystemResource}.
986 * <p> Before delegation, an absolute resource name is constructed from the
987 * given resource name using this algorithm:
991 * <li> If the {@code name} begins with a {@code '/'}
992 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
993 * portion of the {@code name} following the {@code '/'}.
995 * <li> Otherwise, the absolute name is of the following form:
998 * {@code modified_package_name/name}
1001 * <p> Where the {@code modified_package_name} is the package name of this
1002 * object with {@code '/'} substituted for {@code '.'}
1003 * (<tt>'\u002e'</tt>).
1007 * @param name name of the desired resource
1008 * @return A {@link java.net.URL} object or {@code null} if no
1009 * resource with this name is found
1012 public java.net.URL getResource(String name) {
1013 name = resolveName(name);
1014 ClassLoader cl = null;
1017 return ClassLoader.getSystemResource(name);
1019 return cl.getResource(name);
1024 * Add a package name prefix if the name is not absolute Remove leading "/"
1025 * if name is absolute
1027 private String resolveName(String name) {
1031 if (!name.startsWith("/")) {
1033 while (c.isArray()) {
1034 c = c.getComponentType();
1036 String baseName = c.getName();
1037 int index = baseName.lastIndexOf('.');
1039 name = baseName.substring(0, index).replace('.', '/')
1043 name = name.substring(1);
1049 * Returns the class loader for the class. Some implementations may use
1050 * null to represent the bootstrap class loader. This method will return
1051 * null in such implementations if this class was loaded by the bootstrap
1054 * <p> If a security manager is present, and the caller's class loader is
1055 * not null and the caller's class loader is not the same as or an ancestor of
1056 * the class loader for the class whose class loader is requested, then
1057 * this method calls the security manager's {@code checkPermission}
1058 * method with a {@code RuntimePermission("getClassLoader")}
1059 * permission to ensure it's ok to access the class loader for the class.
1062 * represents a primitive type or void, null is returned.
1064 * @return the class loader that loaded the class or interface
1065 * represented by this object.
1066 * @throws SecurityException
1067 * if a security manager exists and its
1068 * {@code checkPermission} method denies
1069 * access to the class loader for the class.
1070 * @see java.lang.ClassLoader
1071 * @see SecurityManager#checkPermission
1072 * @see java.lang.RuntimePermission
1074 public ClassLoader getClassLoader() {
1075 throw new SecurityException();
1079 * Returns the {@code Class} representing the component type of an
1080 * array. If this class does not represent an array class this method
1083 * @return the {@code Class} representing the component type of this
1084 * class if this class is an array
1085 * @see java.lang.reflect.Array
1088 public Class<?> getComponentType() {
1091 return getComponentType0();
1092 } catch (ClassNotFoundException cnfe) {
1093 throw new IllegalStateException(cnfe);
1099 private Class<?> getComponentType0() throws ClassNotFoundException {
1100 String n = getName().substring(1);
1101 switch (n.charAt(0)) {
1103 n = n.substring(1, n.length() - 1);
1104 return Class.forName(n);
1106 return Integer.TYPE;
1116 return Boolean.TYPE;
1122 return Character.TYPE;
1124 return defineArray(n);
1126 throw new ClassNotFoundException("Unknown component type of " + getName());
1130 @JavaScriptBody(args = { "sig" }, body =
1131 "var c = Array[sig];\n" +
1132 "if (c) return c;\n" +
1133 "c = vm.java_lang_Class(true);\n" +
1134 "c.jvmName = sig;\n" +
1135 "c.superclass = vm.java_lang_Object(false).$class;\n" +
1136 "c.array = true;\n" +
1137 "Array[sig] = c;\n" +
1140 private static native Class<?> defineArray(String sig);
1143 * Returns true if and only if this class was declared as an enum in the
1146 * @return true if and only if this class was declared as an enum in the
1150 public boolean isEnum() {
1151 // An enum must both directly extend java.lang.Enum and have
1152 // the ENUM bit set; classes for specialized enum constants
1153 // don't do the former.
1154 return (this.getModifiers() & ENUM) != 0 &&
1155 this.getSuperclass() == java.lang.Enum.class;
1159 * Casts an object to the class or interface represented
1160 * by this {@code Class} object.
1162 * @param obj the object to be cast
1163 * @return the object after casting, or null if obj is null
1165 * @throws ClassCastException if the object is not
1166 * null and is not assignable to the type T.
1170 public T cast(Object obj) {
1171 if (obj != null && !isInstance(obj))
1172 throw new ClassCastException(cannotCastMsg(obj));
1176 private String cannotCastMsg(Object obj) {
1177 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
1181 * Casts this {@code Class} object to represent a subclass of the class
1182 * represented by the specified class object. Checks that that the cast
1183 * is valid, and throws a {@code ClassCastException} if it is not. If
1184 * this method succeeds, it always returns a reference to this class object.
1186 * <p>This method is useful when a client needs to "narrow" the type of
1187 * a {@code Class} object to pass it to an API that restricts the
1188 * {@code Class} objects that it is willing to accept. A cast would
1189 * generate a compile-time warning, as the correctness of the cast
1190 * could not be checked at runtime (because generic types are implemented
1193 * @return this {@code Class} object, cast to represent a subclass of
1194 * the specified class object.
1195 * @throws ClassCastException if this {@code Class} object does not
1196 * represent a subclass of the specified class (here "subclass" includes
1197 * the class itself).
1200 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
1201 if (clazz.isAssignableFrom(this))
1202 return (Class<? extends U>) this;
1204 throw new ClassCastException(this.toString());
1207 @JavaScriptBody(args = { "ac" },
1210 + " return this.anno['L' + ac.jvmName + ';'];"
1211 + "} else return null;"
1213 private Object getAnnotationData(Class<?> annotationClass) {
1214 throw new UnsupportedOperationException();
1217 * @throws NullPointerException {@inheritDoc}
1220 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
1221 Object data = getAnnotationData(annotationClass);
1222 return data == null ? null : AnnotationImpl.create(annotationClass, data);
1226 * @throws NullPointerException {@inheritDoc}
1229 @JavaScriptBody(args = { "ac" },
1230 body = "if (this.anno && this.anno['L' + ac.jvmName + ';']) { return true; }"
1231 + "else return false;"
1233 public boolean isAnnotationPresent(
1234 Class<? extends Annotation> annotationClass) {
1235 if (annotationClass == null)
1236 throw new NullPointerException();
1238 return getAnnotation(annotationClass) != null;
1241 @JavaScriptBody(args = {}, body = "return this.anno;")
1242 private Object getAnnotationData() {
1243 throw new UnsupportedOperationException();
1249 public Annotation[] getAnnotations() {
1250 Object data = getAnnotationData();
1251 return data == null ? new Annotation[0] : AnnotationImpl.create(data);
1257 public Annotation[] getDeclaredAnnotations() {
1258 throw new UnsupportedOperationException();
1261 @JavaScriptBody(args = "type", body = ""
1262 + "var c = vm.java_lang_Class(true);"
1263 + "c.jvmName = type;"
1264 + "c.primitive = true;"
1267 native static Class getPrimitiveClass(String type);
1269 @JavaScriptBody(args = {}, body =
1270 "return vm.desiredAssertionStatus ? vm.desiredAssertionStatus : false;"
1272 public native boolean desiredAssertionStatus();