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 java.io.InputStream;
30 import java.lang.annotation.Annotation;
31 import java.lang.reflect.Array;
32 import java.lang.reflect.Constructor;
33 import java.lang.reflect.Field;
34 import java.lang.reflect.Method;
35 import java.lang.reflect.TypeVariable;
37 import org.apidesign.bck2brwsr.core.Exported;
38 import org.apidesign.bck2brwsr.core.JavaScriptBody;
39 import org.apidesign.bck2brwsr.core.JavaScriptOnly;
40 import org.apidesign.bck2brwsr.emul.reflect.AnnotationImpl;
41 import org.apidesign.bck2brwsr.emul.reflect.MethodImpl;
44 * Instances of the class {@code Class} represent classes and
45 * interfaces in a running Java application. An enum is a kind of
46 * class and an annotation is a kind of interface. Every array also
47 * belongs to a class that is reflected as a {@code Class} object
48 * that is shared by all arrays with the same element type and number
49 * of dimensions. The primitive Java types ({@code boolean},
50 * {@code byte}, {@code char}, {@code short},
51 * {@code int}, {@code long}, {@code float}, and
52 * {@code double}), and the keyword {@code void} are also
53 * represented as {@code Class} objects.
55 * <p> {@code Class} has no public constructor. Instead {@code Class}
56 * objects are constructed automatically by the Java Virtual Machine as classes
57 * are loaded and by calls to the {@code defineClass} method in the class
60 * <p> The following example uses a {@code Class} object to print the
61 * class name of an object:
63 * <p> <blockquote><pre>
64 * void printClassName(Object obj) {
65 * System.out.println("The class of " + obj +
66 * " is " + obj.getClass().getName());
70 * <p> It is also possible to get the {@code Class} object for a named
71 * type (or for void) using a class literal. See Section 15.8.2 of
72 * <cite>The Java™ Language Specification</cite>.
76 * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
79 * @param <T> the type of the class modeled by this {@code Class}
80 * object. For example, the type of {@code String.class} is {@code
81 * Class<String>}. Use {@code Class<?>} if the class being modeled is
85 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
89 class Class<T> implements java.io.Serializable,
90 java.lang.reflect.GenericDeclaration,
91 java.lang.reflect.Type,
92 java.lang.reflect.AnnotatedElement {
93 private static final int ANNOTATION= 0x00002000;
94 private static final int ENUM = 0x00004000;
95 private static final int SYNTHETIC = 0x00001000;
97 /* Backing store of user-defined values pertaining to this class.
98 * Maintained by the ClassValue class.
100 transient Object classValueMap;
103 * Constructor. Only the Java Virtual Machine creates Class
110 * Converts the object to a string. The string representation is the
111 * string "class" or "interface", followed by a space, and then by the
112 * fully qualified name of the class in the format returned by
113 * {@code getName}. If this {@code Class} object represents a
114 * primitive type, this method returns the name of the primitive type. If
115 * this {@code Class} object represents void this method returns
118 * @return a string representation of this class object.
120 public String toString() {
121 return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
127 * Returns the {@code Class} object associated with the class or
128 * interface with the given string name. Invoking this method is
132 * {@code Class.forName(className, true, currentLoader)}
135 * where {@code currentLoader} denotes the defining class loader of
138 * <p> For example, the following code fragment returns the
139 * runtime {@code Class} descriptor for the class named
140 * {@code java.lang.Thread}:
143 * {@code Class t = Class.forName("java.lang.Thread")}
146 * A call to {@code forName("X")} causes the class named
147 * {@code X} to be initialized.
149 * @param className the fully qualified name of the desired class.
150 * @return the {@code Class} object for the class with the
152 * @exception LinkageError if the linkage fails
153 * @exception ExceptionInInitializerError if the initialization provoked
154 * by this method fails
155 * @exception ClassNotFoundException if the class cannot be located
157 public static Class<?> forName(String className)
158 throws ClassNotFoundException {
159 if (className.startsWith("[")) {
160 Class<?> arrType = defineArray(className, null);
161 Class<?> c = arrType;
162 while (c != null && c.isArray()) {
163 c = c.getComponentType0(); // verify component type is sane
168 final String inJsName = className.replace('.', '_');
169 Class<?> c = loadCls(className, inJsName);
171 c = loadCls(className, inJsName);
174 throw new ClassNotFoundException(className);
177 } catch (Throwable ex) {
178 throw new ClassNotFoundException(className, ex);
184 * Returns the {@code Class} object associated with the class or
185 * interface with the given string name, using the given class loader.
186 * Given the fully qualified name for a class or interface (in the same
187 * format returned by {@code getName}) this method attempts to
188 * locate, load, and link the class or interface. The specified class
189 * loader is used to load the class or interface. If the parameter
190 * {@code loader} is null, the class is loaded through the bootstrap
191 * class loader. The class is initialized only if the
192 * {@code initialize} parameter is {@code true} and if it has
193 * not been initialized earlier.
195 * <p> If {@code name} denotes a primitive type or void, an attempt
196 * will be made to locate a user-defined class in the unnamed package whose
197 * name is {@code name}. Therefore, this method cannot be used to
198 * obtain any of the {@code Class} objects representing primitive
201 * <p> If {@code name} denotes an array class, the component type of
202 * the array class is loaded but not initialized.
204 * <p> For example, in an instance method the expression:
207 * {@code Class.forName("Foo")}
213 * {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
216 * Note that this method throws errors related to loading, linking or
217 * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
218 * Java Language Specification</em>.
219 * Note that this method does not check whether the requested class
220 * is accessible to its caller.
222 * <p> If the {@code loader} is {@code null}, and a security
223 * manager is present, and the caller's class loader is not null, then this
224 * method calls the security manager's {@code checkPermission} method
225 * with a {@code RuntimePermission("getClassLoader")} permission to
226 * ensure it's ok to access the bootstrap class loader.
228 * @param name fully qualified name of the desired class
229 * @param initialize whether the class must be initialized
230 * @param loader class loader from which the class must be loaded
231 * @return class object representing the desired class
233 * @exception LinkageError if the linkage fails
234 * @exception ExceptionInInitializerError if the initialization provoked
235 * by this method fails
236 * @exception ClassNotFoundException if the class cannot be located by
237 * the specified class loader
239 * @see java.lang.Class#forName(String)
240 * @see java.lang.ClassLoader
243 public static Class<?> forName(String name, boolean initialize,
245 throws ClassNotFoundException
247 return forName(name);
250 @JavaScriptBody(args = {"n", "c" }, body =
253 + " var l = vm.loadClass ? vm.loadClass : exports ? exports.loadClass : null;\n"
257 + " if (vm[c]) m = vm[c];\n"
258 + " else if (exports[c]) m = exports[c];\n"
260 + "if (!m) return null;"
262 + "return m.$class ? m.$class : null;"
264 private static native Class<?> loadCls(String n, String c);
268 * Creates a new instance of the class represented by this {@code Class}
269 * object. The class is instantiated as if by a {@code new}
270 * expression with an empty argument list. The class is initialized if it
271 * has not already been initialized.
273 * <p>Note that this method propagates any exception thrown by the
274 * nullary constructor, including a checked exception. Use of
275 * this method effectively bypasses the compile-time exception
276 * checking that would otherwise be performed by the compiler.
278 * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
279 * Constructor.newInstance} method avoids this problem by wrapping
280 * any exception thrown by the constructor in a (checked) {@link
281 * java.lang.reflect.InvocationTargetException}.
283 * @return a newly allocated instance of the class represented by this
285 * @exception IllegalAccessException if the class or its nullary
286 * constructor is not accessible.
287 * @exception InstantiationException
288 * if this {@code Class} represents an abstract class,
289 * an interface, an array class, a primitive type, or void;
290 * or if the class has no nullary constructor;
291 * or if the instantiation fails for some other reason.
292 * @exception ExceptionInInitializerError if the initialization
293 * provoked by this method fails.
294 * @exception SecurityException
295 * If a security manager, <i>s</i>, is present and any of the
296 * following conditions is met:
301 * {@link SecurityManager#checkMemberAccess
302 * s.checkMemberAccess(this, Member.PUBLIC)} denies
303 * creation of new instances of this class
305 * <li> the caller's class loader is not the same as or an
306 * ancestor of the class loader for the current class and
307 * invocation of {@link SecurityManager#checkPackageAccess
308 * s.checkPackageAccess()} denies access to the package
314 @JavaScriptBody(args = { "self", "illegal" }, body =
315 "\nvar c = self.cnstr;"
316 + "\nif (c['cons__V']) {"
317 + "\n if ((c['cons__V'].access & 0x1) != 0) {"
318 + "\n var inst = c();"
319 + "\n c['cons__V'].call(inst);"
322 + "\n return illegal;"
326 private static native Object newInstance0(Class<?> self, Object illegal);
328 public T newInstance()
329 throws InstantiationException, IllegalAccessException
331 Object illegal = new Object();
332 Object inst = newInstance0(this, illegal);
334 throw new InstantiationException(getName());
336 if (inst == illegal) {
337 throw new IllegalAccessException();
343 * Determines if the specified {@code Object} is assignment-compatible
344 * with the object represented by this {@code Class}. This method is
345 * the dynamic equivalent of the Java language {@code instanceof}
346 * operator. The method returns {@code true} if the specified
347 * {@code Object} argument is non-null and can be cast to the
348 * reference type represented by this {@code Class} object without
349 * raising a {@code ClassCastException.} It returns {@code false}
352 * <p> Specifically, if this {@code Class} object represents a
353 * declared class, this method returns {@code true} if the specified
354 * {@code Object} argument is an instance of the represented class (or
355 * of any of its subclasses); it returns {@code false} otherwise. If
356 * this {@code Class} object represents an array class, this method
357 * returns {@code true} if the specified {@code Object} argument
358 * can be converted to an object of the array class by an identity
359 * conversion or by a widening reference conversion; it returns
360 * {@code false} otherwise. If this {@code Class} object
361 * represents an interface, this method returns {@code true} if the
362 * class or any superclass of the specified {@code Object} argument
363 * implements this interface; it returns {@code false} otherwise. If
364 * this {@code Class} object represents a primitive type, this method
365 * returns {@code false}.
367 * @param obj the object to check
368 * @return true if {@code obj} is an instance of this class
372 public boolean isInstance(Object obj) {
377 return isAssignableFrom(obj.getClass());
380 String prop = "$instOf_" + getName().replace('.', '_');
381 return hasProperty(obj, prop);
384 @JavaScriptBody(args = { "who", "prop" }, body =
385 "if (who[prop]) return true; else return false;"
387 private static native boolean hasProperty(Object who, String prop);
391 * Determines if the class or interface represented by this
392 * {@code Class} object is either the same as, or is a superclass or
393 * superinterface of, the class or interface represented by the specified
394 * {@code Class} parameter. It returns {@code true} if so;
395 * otherwise it returns {@code false}. If this {@code Class}
396 * object represents a primitive type, this method returns
397 * {@code true} if the specified {@code Class} parameter is
398 * exactly this {@code Class} object; otherwise it returns
401 * <p> Specifically, this method tests whether the type represented by the
402 * specified {@code Class} parameter can be converted to the type
403 * represented by this {@code Class} object via an identity conversion
404 * or via a widening reference conversion. See <em>The Java Language
405 * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
407 * @param cls the {@code Class} object to be checked
408 * @return the {@code boolean} value indicating whether objects of the
409 * type {@code cls} can be assigned to objects of this class
410 * @exception NullPointerException if the specified Class parameter is
414 public boolean isAssignableFrom(Class<?> cls) {
418 if (this == Object.class) {
423 final Class<?> cmpType = cls.getComponentType();
425 return this == cmpType;
427 return cmpType != null && getComponentType().isAssignableFrom(cmpType);
432 if (cls.isPrimitive()) {
438 String prop = "$instOf_" + getName().replace('.', '_');
439 return hasCnstrProperty(cls, prop);
443 @JavaScriptBody(args = { "who", "prop" }, body =
444 "if (who.cnstr.prototype[prop]) return true; else return false;"
446 private static native boolean hasCnstrProperty(Object who, String prop);
450 * Determines if the specified {@code Class} object represents an
453 * @return {@code true} if this object represents an interface;
454 * {@code false} otherwise.
456 public boolean isInterface() {
457 return (getAccess() & 0x200) != 0;
460 @JavaScriptBody(args = {}, body = "return this.access;")
461 private native int getAccess();
465 * Determines if this {@code Class} object represents an array class.
467 * @return {@code true} if this object represents an array class;
468 * {@code false} otherwise.
471 public boolean isArray() {
472 return hasProperty(this, "array"); // NOI18N
477 * Determines if the specified {@code Class} object represents a
480 * <p> There are nine predefined {@code Class} objects to represent
481 * the eight primitive types and void. These are created by the Java
482 * Virtual Machine, and have the same names as the primitive types that
483 * they represent, namely {@code boolean}, {@code byte},
484 * {@code char}, {@code short}, {@code int},
485 * {@code long}, {@code float}, and {@code double}.
487 * <p> These objects may only be accessed via the following public static
488 * final variables, and are the only {@code Class} objects for which
489 * this method returns {@code true}.
491 * @return true if and only if this class represents a primitive type
493 * @see java.lang.Boolean#TYPE
494 * @see java.lang.Character#TYPE
495 * @see java.lang.Byte#TYPE
496 * @see java.lang.Short#TYPE
497 * @see java.lang.Integer#TYPE
498 * @see java.lang.Long#TYPE
499 * @see java.lang.Float#TYPE
500 * @see java.lang.Double#TYPE
501 * @see java.lang.Void#TYPE
504 @JavaScriptBody(args = {}, body =
505 "if (this.primitive) return true;"
506 + "else return false;"
508 public native boolean isPrimitive();
511 * Returns true if this {@code Class} object represents an annotation
512 * type. Note that if this method returns true, {@link #isInterface()}
513 * would also return true, as all annotation types are also interfaces.
515 * @return {@code true} if this class object represents an annotation
516 * type; {@code false} otherwise
519 public boolean isAnnotation() {
520 return (getModifiers() & ANNOTATION) != 0;
524 * Returns {@code true} if this class is a synthetic class;
525 * returns {@code false} otherwise.
526 * @return {@code true} if and only if this class is a synthetic class as
527 * defined by the Java Language Specification.
530 public boolean isSynthetic() {
531 return (getModifiers() & SYNTHETIC) != 0;
535 * Returns the name of the entity (class, interface, array class,
536 * primitive type, or void) represented by this {@code Class} object,
537 * as a {@code String}.
539 * <p> If this class object represents a reference type that is not an
540 * array type then the binary name of the class is returned, as specified
542 * <cite>The Java™ Language Specification</cite>.
544 * <p> If this class object represents a primitive type or void, then the
545 * name returned is a {@code String} equal to the Java language
546 * keyword corresponding to the primitive type or void.
548 * <p> If this class object represents a class of arrays, then the internal
549 * form of the name consists of the name of the element type preceded by
550 * one or more '{@code [}' characters representing the depth of the array
551 * nesting. The encoding of element type names is as follows:
553 * <blockquote><table summary="Element types and encodings">
554 * <tr><th> Element Type <th> <th> Encoding
555 * <tr><td> boolean <td> <td align=center> Z
556 * <tr><td> byte <td> <td align=center> B
557 * <tr><td> char <td> <td align=center> C
558 * <tr><td> class or interface
559 * <td> <td align=center> L<i>classname</i>;
560 * <tr><td> double <td> <td align=center> D
561 * <tr><td> float <td> <td align=center> F
562 * <tr><td> int <td> <td align=center> I
563 * <tr><td> long <td> <td align=center> J
564 * <tr><td> short <td> <td align=center> S
565 * </table></blockquote>
567 * <p> The class or interface name <i>classname</i> is the binary name of
568 * the class specified above.
572 * String.class.getName()
573 * returns "java.lang.String"
574 * byte.class.getName()
576 * (new Object[3]).getClass().getName()
577 * returns "[Ljava.lang.Object;"
578 * (new int[3][4][5][6][7][8][9]).getClass().getName()
580 * </pre></blockquote>
582 * @return the name of the class or interface
583 * represented by this object.
585 public String getName() {
586 return jvmName().replace('/', '.');
589 @JavaScriptBody(args = {}, body = "return this.jvmName;")
590 private native String jvmName();
594 * Returns an array of {@code TypeVariable} objects that represent the
595 * type variables declared by the generic declaration represented by this
596 * {@code GenericDeclaration} object, in declaration order. Returns an
597 * array of length 0 if the underlying generic declaration declares no type
600 * @return an array of {@code TypeVariable} objects that represent
601 * the type variables declared by this generic declaration
602 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
603 * signature of this generic declaration does not conform to
604 * the format specified in
605 * <cite>The Java™ Virtual Machine Specification</cite>
608 public TypeVariable<Class<T>>[] getTypeParameters() {
609 throw new UnsupportedOperationException();
613 * Returns the {@code Class} representing the superclass of the entity
614 * (class, interface, primitive type or void) represented by this
615 * {@code Class}. If this {@code Class} represents either the
616 * {@code Object} class, an interface, a primitive type, or void, then
617 * null is returned. If this object represents an array class then the
618 * {@code Class} object representing the {@code Object} class is
621 * @return the superclass of the class represented by this object.
623 @JavaScriptBody(args = {}, body = "return this.superclass;")
624 public native Class<? super T> getSuperclass();
627 * Returns the Java language modifiers for this class or interface, encoded
628 * in an integer. The modifiers consist of the Java Virtual Machine's
629 * constants for {@code public}, {@code protected},
630 * {@code private}, {@code final}, {@code static},
631 * {@code abstract} and {@code interface}; they should be decoded
632 * using the methods of class {@code Modifier}.
634 * <p> If the underlying class is an array class, then its
635 * {@code public}, {@code private} and {@code protected}
636 * modifiers are the same as those of its component type. If this
637 * {@code Class} represents a primitive type or void, its
638 * {@code public} modifier is always {@code true}, and its
639 * {@code protected} and {@code private} modifiers are always
640 * {@code false}. If this object represents an array class, a
641 * primitive type or void, then its {@code final} modifier is always
642 * {@code true} and its interface modifier is always
643 * {@code false}. The values of its other modifiers are not determined
644 * by this specification.
646 * <p> The modifier encodings are defined in <em>The Java Virtual Machine
647 * Specification</em>, table 4.1.
649 * @return the {@code int} representing the modifiers for this class
650 * @see java.lang.reflect.Modifier
653 public int getModifiers() {
658 * If the class or interface represented by this {@code Class} object
659 * is a member of another class, returns the {@code Class} object
660 * representing the class in which it was declared. This method returns
661 * null if this class or interface is not a member of any other class. If
662 * this {@code Class} object represents an array class, a primitive
663 * type, or void,then this method returns null.
665 * @return the declaring class for this class
668 public Class<?> getDeclaringClass() {
669 throw new SecurityException();
673 * Returns the simple name of the underlying class as given in the
674 * source code. Returns an empty string if the underlying class is
677 * <p>The simple name of an array is the simple name of the
678 * component type with "[]" appended. In particular the simple
679 * name of an array whose component type is anonymous is "[]".
681 * @return the simple name of the underlying class
684 public String getSimpleName() {
686 return getComponentType().getSimpleName()+"[]";
688 String simpleName = getSimpleBinaryName();
689 if (simpleName == null) { // top level class
690 simpleName = getName();
691 return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
693 // According to JLS3 "Binary Compatibility" (13.1) the binary
694 // name of non-package classes (not top level) is the binary
695 // name of the immediately enclosing class followed by a '$' followed by:
696 // (for nested and inner classes): the simple name.
697 // (for local classes): 1 or more digits followed by the simple name.
698 // (for anonymous classes): 1 or more digits.
700 // Since getSimpleBinaryName() will strip the binary name of
701 // the immediatly enclosing class, we are now looking at a
702 // string that matches the regular expression "\$[0-9]*"
703 // followed by a simple name (considering the simple of an
704 // anonymous class to be the empty string).
706 // Remove leading "\$[0-9]*" from the name
707 int length = simpleName.length();
708 if (length < 1 || simpleName.charAt(0) != '$')
709 throw new IllegalStateException("Malformed class name");
711 while (index < length && isAsciiDigit(simpleName.charAt(index)))
713 // Eventually, this is the empty string iff this is an anonymous class
714 return simpleName.substring(index);
718 * Returns the "simple binary name" of the underlying class, i.e.,
719 * the binary name without the leading enclosing class name.
720 * Returns {@code null} if the underlying class is a top level
723 private String getSimpleBinaryName() {
724 final String name = getName();
725 int dolar = name.lastIndexOf('$');
729 return name.substring(dolar);
733 * Returns an array containing {@code Field} objects reflecting all
734 * the accessible public fields of the class or interface represented by
735 * this {@code Class} object. The elements in the array returned are
736 * not sorted and are not in any particular order. This method returns an
737 * array of length 0 if the class or interface has no accessible public
738 * fields, or if it represents an array class, a primitive type, or void.
740 * <p> Specifically, if this {@code Class} object represents a class,
741 * this method returns the public fields of this class and of all its
742 * superclasses. If this {@code Class} object represents an
743 * interface, this method returns the fields of this interface and of all
744 * its superinterfaces.
746 * <p> The implicit length field for array class is not reflected by this
747 * method. User code should use the methods of class {@code Array} to
750 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
752 * @return the array of {@code Field} objects representing the
754 * @exception SecurityException
755 * If a security manager, <i>s</i>, is present and any of the
756 * following conditions is met:
761 * {@link SecurityManager#checkMemberAccess
762 * s.checkMemberAccess(this, Member.PUBLIC)} denies
763 * access to the fields within this class
765 * <li> the caller's class loader is not the same as or an
766 * ancestor of the class loader for the current class and
767 * invocation of {@link SecurityManager#checkPackageAccess
768 * s.checkPackageAccess()} denies access to the package
775 public Field[] getFields() throws SecurityException {
776 throw new SecurityException();
780 * Returns an array containing {@code Method} objects reflecting all
781 * the public <em>member</em> methods of the class or interface represented
782 * by this {@code Class} object, including those declared by the class
783 * or interface and those inherited from superclasses and
784 * superinterfaces. Array classes return all the (public) member methods
785 * inherited from the {@code Object} class. The elements in the array
786 * returned are not sorted and are not in any particular order. This
787 * method returns an array of length 0 if this {@code Class} object
788 * represents a class or interface that has no public member methods, or if
789 * this {@code Class} object represents a primitive type or void.
791 * <p> The class initialization method {@code <clinit>} is not
792 * included in the returned array. If the class declares multiple public
793 * member methods with the same parameter types, they are all included in
794 * the returned array.
796 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
798 * @return the array of {@code Method} objects representing the
799 * public methods of this class
800 * @exception SecurityException
801 * If a security manager, <i>s</i>, is present and any of the
802 * following conditions is met:
807 * {@link SecurityManager#checkMemberAccess
808 * s.checkMemberAccess(this, Member.PUBLIC)} denies
809 * access to the methods within this class
811 * <li> the caller's class loader is not the same as or an
812 * ancestor of the class loader for the current class and
813 * invocation of {@link SecurityManager#checkPackageAccess
814 * s.checkPackageAccess()} denies access to the package
821 public Method[] getMethods() throws SecurityException {
822 return MethodImpl.findMethods(this, 0x01);
826 * Returns a {@code Field} object that reflects the specified public
827 * member field of the class or interface represented by this
828 * {@code Class} object. The {@code name} parameter is a
829 * {@code String} specifying the simple name of the desired field.
831 * <p> The field to be reflected is determined by the algorithm that
832 * follows. Let C be the class represented by this object:
834 * <LI> If C declares a public field with the name specified, that is the
835 * field to be reflected.</LI>
836 * <LI> If no field was found in step 1 above, this algorithm is applied
837 * recursively to each direct superinterface of C. The direct
838 * superinterfaces are searched in the order they were declared.</LI>
839 * <LI> If no field was found in steps 1 and 2 above, and C has a
840 * superclass S, then this algorithm is invoked recursively upon S.
841 * If C has no superclass, then a {@code NoSuchFieldException}
845 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
847 * @param name the field name
848 * @return the {@code Field} object of this class specified by
850 * @exception NoSuchFieldException if a field with the specified name is
852 * @exception NullPointerException if {@code name} is {@code null}
853 * @exception SecurityException
854 * If a security manager, <i>s</i>, is present and any of the
855 * following conditions is met:
860 * {@link SecurityManager#checkMemberAccess
861 * s.checkMemberAccess(this, Member.PUBLIC)} denies
862 * access to the field
864 * <li> the caller's class loader is not the same as or an
865 * ancestor of the class loader for the current class and
866 * invocation of {@link SecurityManager#checkPackageAccess
867 * s.checkPackageAccess()} denies access to the package
874 public Field getField(String name)
875 throws SecurityException {
876 throw new SecurityException();
881 * Returns a {@code Method} object that reflects the specified public
882 * member method of the class or interface represented by this
883 * {@code Class} object. The {@code name} parameter is a
884 * {@code String} specifying the simple name of the desired method. The
885 * {@code parameterTypes} parameter is an array of {@code Class}
886 * objects that identify the method's formal parameter types, in declared
887 * order. If {@code parameterTypes} is {@code null}, it is
888 * treated as if it were an empty array.
890 * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
891 * {@code NoSuchMethodException} is raised. Otherwise, the method to
892 * be reflected is determined by the algorithm that follows. Let C be the
893 * class represented by this object:
895 * <LI> C is searched for any <I>matching methods</I>. If no matching
896 * method is found, the algorithm of step 1 is invoked recursively on
897 * the superclass of C.</LI>
898 * <LI> If no method was found in step 1 above, the superinterfaces of C
899 * are searched for a matching method. If any such method is found, it
903 * To find a matching method in a class C: If C declares exactly one
904 * public method with the specified name and exactly the same formal
905 * parameter types, that is the method reflected. If more than one such
906 * method is found in C, and one of these methods has a return type that is
907 * more specific than any of the others, that method is reflected;
908 * otherwise one of the methods is chosen arbitrarily.
910 * <p>Note that there may be more than one matching method in a
911 * class because while the Java language forbids a class to
912 * declare multiple methods with the same signature but different
913 * return types, the Java virtual machine does not. This
914 * increased flexibility in the virtual machine can be used to
915 * implement various language features. For example, covariant
916 * returns can be implemented with {@linkplain
917 * java.lang.reflect.Method#isBridge bridge methods}; the bridge
918 * method and the method being overridden would have the same
919 * signature but different return types.
921 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
923 * @param name the name of the method
924 * @param parameterTypes the list of parameters
925 * @return the {@code Method} object that matches the specified
926 * {@code name} and {@code parameterTypes}
927 * @exception NoSuchMethodException if a matching method is not found
928 * or if the name is "<init>"or "<clinit>".
929 * @exception NullPointerException if {@code name} is {@code null}
930 * @exception SecurityException
931 * If a security manager, <i>s</i>, is present and any of the
932 * following conditions is met:
937 * {@link SecurityManager#checkMemberAccess
938 * s.checkMemberAccess(this, Member.PUBLIC)} denies
939 * access to the method
941 * <li> the caller's class loader is not the same as or an
942 * ancestor of the class loader for the current class and
943 * invocation of {@link SecurityManager#checkPackageAccess
944 * s.checkPackageAccess()} denies access to the package
951 public Method getMethod(String name, Class<?>... parameterTypes)
952 throws SecurityException, NoSuchMethodException {
953 Method m = MethodImpl.findMethod(this, name, parameterTypes);
955 StringBuilder sb = new StringBuilder();
956 sb.append(getName()).append('.').append(name).append('(');
958 for (int i = 0; i < parameterTypes.length; i++) {
959 sb.append(sep).append(parameterTypes[i].getName());
963 throw new NoSuchMethodException(sb.toString());
969 * Returns an array of {@code Method} objects reflecting all the
970 * methods declared by the class or interface represented by this
971 * {@code Class} object. This includes public, protected, default
972 * (package) access, and private methods, but excludes inherited methods.
973 * The elements in the array returned are not sorted and are not in any
974 * particular order. This method returns an array of length 0 if the class
975 * or interface declares no methods, or if this {@code Class} object
976 * represents a primitive type, an array class, or void. The class
977 * initialization method {@code <clinit>} is not included in the
978 * returned array. If the class declares multiple public member methods
979 * with the same parameter types, they are all included in the returned
982 * <p> See <em>The Java Language Specification</em>, section 8.2.
984 * @return the array of {@code Method} objects representing all the
985 * declared methods of this class
986 * @exception SecurityException
987 * If a security manager, <i>s</i>, is present and any of the
988 * following conditions is met:
993 * {@link SecurityManager#checkMemberAccess
994 * s.checkMemberAccess(this, Member.DECLARED)} denies
995 * access to the declared methods within this class
997 * <li> the caller's class loader is not the same as or an
998 * ancestor of the class loader for the current class and
999 * invocation of {@link SecurityManager#checkPackageAccess
1000 * s.checkPackageAccess()} denies access to the package
1007 public Method[] getDeclaredMethods() throws SecurityException {
1008 Method[] arr = getMethods();
1010 for (int i = 0; i < arr.length; i++) {
1011 if (arr[i].getDeclaringClass() == this) {
1015 Method[] ret = new Method[cnt];
1017 for (int i = 0; i < arr.length; i++) {
1018 if (arr[i].getDeclaringClass() == this) {
1019 ret[cnt++] = arr[i];
1026 * Returns an array of {@code Field} objects reflecting all the fields
1027 * declared by the class or interface represented by this
1028 * {@code Class} object. This includes public, protected, default
1029 * (package) access, and private fields, but excludes inherited fields.
1030 * The elements in the array returned are not sorted and are not in any
1031 * particular order. This method returns an array of length 0 if the class
1032 * or interface declares no fields, or if this {@code Class} object
1033 * represents a primitive type, an array class, or void.
1035 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
1037 * @return the array of {@code Field} objects representing all the
1038 * declared fields of this class
1039 * @exception SecurityException
1040 * If a security manager, <i>s</i>, is present and any of the
1041 * following conditions is met:
1045 * <li> invocation of
1046 * {@link SecurityManager#checkMemberAccess
1047 * s.checkMemberAccess(this, Member.DECLARED)} denies
1048 * access to the declared fields within this class
1050 * <li> the caller's class loader is not the same as or an
1051 * ancestor of the class loader for the current class and
1052 * invocation of {@link SecurityManager#checkPackageAccess
1053 * s.checkPackageAccess()} denies access to the package
1060 public Field[] getDeclaredFields() throws SecurityException {
1061 throw new SecurityException();
1065 * <b>Bck2Brwsr</b> emulation can only seek public methods, otherwise it
1066 * throws a {@code SecurityException}.
1068 * Returns a {@code Method} object that reflects the specified
1069 * declared method of the class or interface represented by this
1070 * {@code Class} object. The {@code name} parameter is a
1071 * {@code String} that specifies the simple name of the desired
1072 * method, and the {@code parameterTypes} parameter is an array of
1073 * {@code Class} objects that identify the method's formal parameter
1074 * types, in declared order. If more than one method with the same
1075 * parameter types is declared in a class, and one of these methods has a
1076 * return type that is more specific than any of the others, that method is
1077 * returned; otherwise one of the methods is chosen arbitrarily. If the
1078 * name is "<init>"or "<clinit>" a {@code NoSuchMethodException}
1081 * @param name the name of the method
1082 * @param parameterTypes the parameter array
1083 * @return the {@code Method} object for the method of this class
1084 * matching the specified name and parameters
1085 * @exception NoSuchMethodException if a matching method is not found.
1086 * @exception NullPointerException if {@code name} is {@code null}
1087 * @exception SecurityException
1088 * If a security manager, <i>s</i>, is present and any of the
1089 * following conditions is met:
1093 * <li> invocation of
1094 * {@link SecurityManager#checkMemberAccess
1095 * s.checkMemberAccess(this, Member.DECLARED)} denies
1096 * access to the declared method
1098 * <li> the caller's class loader is not the same as or an
1099 * ancestor of the class loader for the current class and
1100 * invocation of {@link SecurityManager#checkPackageAccess
1101 * s.checkPackageAccess()} denies access to the package
1108 public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
1109 throws NoSuchMethodException, SecurityException {
1111 return getMethod(name, parameterTypes);
1112 } catch (NoSuchMethodException ex) {
1113 throw new SecurityException();
1118 * Returns a {@code Field} object that reflects the specified declared
1119 * field of the class or interface represented by this {@code Class}
1120 * object. The {@code name} parameter is a {@code String} that
1121 * specifies the simple name of the desired field. Note that this method
1122 * will not reflect the {@code length} field of an array class.
1124 * @param name the name of the field
1125 * @return the {@code Field} object for the specified field in this
1127 * @exception NoSuchFieldException if a field with the specified name is
1129 * @exception NullPointerException if {@code name} is {@code null}
1130 * @exception SecurityException
1131 * If a security manager, <i>s</i>, is present and any of the
1132 * following conditions is met:
1136 * <li> invocation of
1137 * {@link SecurityManager#checkMemberAccess
1138 * s.checkMemberAccess(this, Member.DECLARED)} denies
1139 * access to the declared field
1141 * <li> the caller's class loader is not the same as or an
1142 * ancestor of the class loader for the current class and
1143 * invocation of {@link SecurityManager#checkPackageAccess
1144 * s.checkPackageAccess()} denies access to the package
1151 public Field getDeclaredField(String name)
1152 throws SecurityException {
1153 throw new SecurityException();
1157 * Returns an array containing {@code Constructor} objects reflecting
1158 * all the public constructors of the class represented by this
1159 * {@code Class} object. An array of length 0 is returned if the
1160 * class has no public constructors, or if the class is an array class, or
1161 * if the class reflects a primitive type or void.
1163 * Note that while this method returns an array of {@code
1164 * Constructor<T>} objects (that is an array of constructors from
1165 * this class), the return type of this method is {@code
1166 * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
1167 * might be expected. This less informative return type is
1168 * necessary since after being returned from this method, the
1169 * array could be modified to hold {@code Constructor} objects for
1170 * different classes, which would violate the type guarantees of
1171 * {@code Constructor<T>[]}.
1173 * @return the array of {@code Constructor} objects representing the
1174 * public constructors of this class
1175 * @exception SecurityException
1176 * If a security manager, <i>s</i>, is present and any of the
1177 * following conditions is met:
1181 * <li> invocation of
1182 * {@link SecurityManager#checkMemberAccess
1183 * s.checkMemberAccess(this, Member.PUBLIC)} denies
1184 * access to the constructors within this class
1186 * <li> the caller's class loader is not the same as or an
1187 * ancestor of the class loader for the current class and
1188 * invocation of {@link SecurityManager#checkPackageAccess
1189 * s.checkPackageAccess()} denies access to the package
1196 public Constructor<?>[] getConstructors() throws SecurityException {
1197 return MethodImpl.findConstructors(this, 0x01);
1201 * Returns a {@code Constructor} object that reflects the specified
1202 * public constructor of the class represented by this {@code Class}
1203 * object. The {@code parameterTypes} parameter is an array of
1204 * {@code Class} objects that identify the constructor's formal
1205 * parameter types, in declared order.
1207 * If this {@code Class} object represents an inner class
1208 * declared in a non-static context, the formal parameter types
1209 * include the explicit enclosing instance as the first parameter.
1211 * <p> The constructor to reflect is the public constructor of the class
1212 * represented by this {@code Class} object whose formal parameter
1213 * types match those specified by {@code parameterTypes}.
1215 * @param parameterTypes the parameter array
1216 * @return the {@code Constructor} object of the public constructor that
1217 * matches the specified {@code parameterTypes}
1218 * @exception NoSuchMethodException if a matching method is not found.
1219 * @exception SecurityException
1220 * If a security manager, <i>s</i>, is present and any of the
1221 * following conditions is met:
1225 * <li> invocation of
1226 * {@link SecurityManager#checkMemberAccess
1227 * s.checkMemberAccess(this, Member.PUBLIC)} denies
1228 * access to the constructor
1230 * <li> the caller's class loader is not the same as or an
1231 * ancestor of the class loader for the current class and
1232 * invocation of {@link SecurityManager#checkPackageAccess
1233 * s.checkPackageAccess()} denies access to the package
1240 public Constructor<T> getConstructor(Class<?>... parameterTypes)
1241 throws NoSuchMethodException, SecurityException {
1242 Constructor c = MethodImpl.findConstructor(this, parameterTypes);
1244 StringBuilder sb = new StringBuilder();
1245 sb.append(getName()).append('(');
1247 for (int i = 0; i < parameterTypes.length; i++) {
1248 sb.append(sep).append(parameterTypes[i].getName());
1252 throw new NoSuchMethodException(sb.toString());
1258 * Returns an array of {@code Constructor} objects reflecting all the
1259 * constructors declared by the class represented by this
1260 * {@code Class} object. These are public, protected, default
1261 * (package) access, and private constructors. The elements in the array
1262 * returned are not sorted and are not in any particular order. If the
1263 * class has a default constructor, it is included in the returned array.
1264 * This method returns an array of length 0 if this {@code Class}
1265 * object represents an interface, a primitive type, an array class, or
1268 * <p> See <em>The Java Language Specification</em>, section 8.2.
1270 * @return the array of {@code Constructor} objects representing all the
1271 * declared constructors of this class
1272 * @exception SecurityException
1273 * If a security manager, <i>s</i>, is present and any of the
1274 * following conditions is met:
1278 * <li> invocation of
1279 * {@link SecurityManager#checkMemberAccess
1280 * s.checkMemberAccess(this, Member.DECLARED)} denies
1281 * access to the declared constructors within this class
1283 * <li> the caller's class loader is not the same as or an
1284 * ancestor of the class loader for the current class and
1285 * invocation of {@link SecurityManager#checkPackageAccess
1286 * s.checkPackageAccess()} denies access to the package
1293 public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
1294 throw new SecurityException();
1297 * Returns a {@code Constructor} object that reflects the specified
1298 * constructor of the class or interface represented by this
1299 * {@code Class} object. The {@code parameterTypes} parameter is
1300 * an array of {@code Class} objects that identify the constructor's
1301 * formal parameter types, in declared order.
1303 * If this {@code Class} object represents an inner class
1304 * declared in a non-static context, the formal parameter types
1305 * include the explicit enclosing instance as the first parameter.
1307 * @param parameterTypes the parameter array
1308 * @return The {@code Constructor} object for the constructor with the
1309 * specified parameter list
1310 * @exception NoSuchMethodException if a matching method is not found.
1311 * @exception SecurityException
1312 * If a security manager, <i>s</i>, is present and any of the
1313 * following conditions is met:
1317 * <li> invocation of
1318 * {@link SecurityManager#checkMemberAccess
1319 * s.checkMemberAccess(this, Member.DECLARED)} denies
1320 * access to the declared constructor
1322 * <li> the caller's class loader is not the same as or an
1323 * ancestor of the class loader for the current class and
1324 * invocation of {@link SecurityManager#checkPackageAccess
1325 * s.checkPackageAccess()} denies access to the package
1332 public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
1333 throws NoSuchMethodException, SecurityException {
1334 return getConstructor(parameterTypes);
1339 * Character.isDigit answers {@code true} to some non-ascii
1340 * digits. This one does not.
1342 private static boolean isAsciiDigit(char c) {
1343 return '0' <= c && c <= '9';
1347 * Returns the canonical name of the underlying class as
1348 * defined by the Java Language Specification. Returns null if
1349 * the underlying class does not have a canonical name (i.e., if
1350 * it is a local or anonymous class or an array whose component
1351 * type does not have a canonical name).
1352 * @return the canonical name of the underlying class if it exists, and
1353 * {@code null} otherwise.
1356 public String getCanonicalName() {
1358 String canonicalName = getComponentType().getCanonicalName();
1359 if (canonicalName != null)
1360 return canonicalName + "[]";
1364 if (isLocalOrAnonymousClass())
1366 // Class<?> enclosingClass = getEnclosingClass();
1367 Class<?> enclosingClass = null;
1368 if (enclosingClass == null) { // top level class
1371 String enclosingName = enclosingClass.getCanonicalName();
1372 if (enclosingName == null)
1374 return enclosingName + "." + getSimpleName();
1379 * Returns {@code true} if and only if the underlying class is an anonymous
1382 * @return {@code true} if and only if this class is an anonymous class.
1385 public boolean isAnonymousClass() {
1386 return "".equals(getSimpleName());
1390 * Returns {@code true} if and only if the underlying class is a local
1393 * @return {@code true} if and only if this class is a local class.
1396 public boolean isLocalClass() {
1397 return isLocalOrAnonymousClass() && !isAnonymousClass();
1401 * Returns {@code true} if and only if the underlying class is a member
1404 * @return {@code true} if and only if this class is a member class.
1407 public boolean isMemberClass() {
1408 return getSimpleBinaryName() != null && !isLocalOrAnonymousClass();
1412 * Returns {@code true} if this is a local class or an anonymous class.
1413 * Returns {@code false} otherwise.
1415 private boolean isLocalOrAnonymousClass() {
1416 return (getAccess() & 0x10000) != 0;
1420 * Finds a resource with a given name. The rules for searching resources
1421 * associated with a given class are implemented by the defining
1422 * {@linkplain ClassLoader class loader} of the class. This method
1423 * delegates to this object's class loader. If this object was loaded by
1424 * the bootstrap class loader, the method delegates to {@link
1425 * ClassLoader#getSystemResourceAsStream}.
1427 * <p> Before delegation, an absolute resource name is constructed from the
1428 * given resource name using this algorithm:
1432 * <li> If the {@code name} begins with a {@code '/'}
1433 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
1434 * portion of the {@code name} following the {@code '/'}.
1436 * <li> Otherwise, the absolute name is of the following form:
1439 * {@code modified_package_name/name}
1442 * <p> Where the {@code modified_package_name} is the package name of this
1443 * object with {@code '/'} substituted for {@code '.'}
1444 * (<tt>'\u002e'</tt>).
1448 * @param name name of the desired resource
1449 * @return A {@link java.io.InputStream} object or {@code null} if
1450 * no resource with this name is found
1451 * @throws NullPointerException If {@code name} is {@code null}
1454 public InputStream getResourceAsStream(String name) {
1455 name = resolveName(name);
1456 byte[] arr = ClassLoader.getResourceAsStream0(name, 0);
1457 return arr == null ? null : new ByteArrayInputStream(arr);
1461 * Finds a resource with a given name. The rules for searching resources
1462 * associated with a given class are implemented by the defining
1463 * {@linkplain ClassLoader class loader} of the class. This method
1464 * delegates to this object's class loader. If this object was loaded by
1465 * the bootstrap class loader, the method delegates to {@link
1466 * ClassLoader#getSystemResource}.
1468 * <p> Before delegation, an absolute resource name is constructed from the
1469 * given resource name using this algorithm:
1473 * <li> If the {@code name} begins with a {@code '/'}
1474 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
1475 * portion of the {@code name} following the {@code '/'}.
1477 * <li> Otherwise, the absolute name is of the following form:
1480 * {@code modified_package_name/name}
1483 * <p> Where the {@code modified_package_name} is the package name of this
1484 * object with {@code '/'} substituted for {@code '.'}
1485 * (<tt>'\u002e'</tt>).
1489 * @param name name of the desired resource
1490 * @return A {@link java.net.URL} object or {@code null} if no
1491 * resource with this name is found
1494 public java.net.URL getResource(String name) {
1495 name = resolveName(name);
1496 byte[] arr = ClassLoader.getResourceAsStream0(name, 0);
1497 return arr == null ? null : newResourceURL(name, arr);
1500 static URL newResourceURL(String name, byte[] arr) {
1501 return newResourceURL0(URL.class, "res:/" + name, arr);
1504 @JavaScriptBody(args = { "url", "spec", "arr" }, body =
1505 "var u = url.cnstr(true);\n"
1506 + "u.constructor.cons__VLjava_lang_String_2_3B.call(u, spec, arr);\n"
1509 private static native URL newResourceURL0(Class<URL> url, String spec, byte[] arr);
1512 * Add a package name prefix if the name is not absolute Remove leading "/"
1513 * if name is absolute
1515 private String resolveName(String name) {
1519 if (!name.startsWith("/")) {
1521 while (c.isArray()) {
1522 c = c.getComponentType();
1524 String baseName = c.getName();
1525 int index = baseName.lastIndexOf('.');
1527 name = baseName.substring(0, index).replace('.', '/')
1531 name = name.substring(1);
1537 * Returns the class loader for the class. Some implementations may use
1538 * null to represent the bootstrap class loader. This method will return
1539 * null in such implementations if this class was loaded by the bootstrap
1542 * <p> If a security manager is present, and the caller's class loader is
1543 * not null and the caller's class loader is not the same as or an ancestor of
1544 * the class loader for the class whose class loader is requested, then
1545 * this method calls the security manager's {@code checkPermission}
1546 * method with a {@code RuntimePermission("getClassLoader")}
1547 * permission to ensure it's ok to access the class loader for the class.
1550 * represents a primitive type or void, null is returned.
1552 * @return the class loader that loaded the class or interface
1553 * represented by this object.
1554 * @throws SecurityException
1555 * if a security manager exists and its
1556 * {@code checkPermission} method denies
1557 * access to the class loader for the class.
1558 * @see java.lang.ClassLoader
1559 * @see SecurityManager#checkPermission
1560 * @see java.lang.RuntimePermission
1562 public ClassLoader getClassLoader() {
1563 return ClassLoader.getSystemClassLoader();
1567 * Determines the interfaces implemented by the class or interface
1568 * represented by this object.
1570 * <p> If this object represents a class, the return value is an array
1571 * containing objects representing all interfaces implemented by the
1572 * class. The order of the interface objects in the array corresponds to
1573 * the order of the interface names in the {@code implements} clause
1574 * of the declaration of the class represented by this object. For
1575 * example, given the declaration:
1577 * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
1579 * suppose the value of {@code s} is an instance of
1580 * {@code Shimmer}; the value of the expression:
1582 * {@code s.getClass().getInterfaces()[0]}
1584 * is the {@code Class} object that represents interface
1585 * {@code FloorWax}; and the value of:
1587 * {@code s.getClass().getInterfaces()[1]}
1589 * is the {@code Class} object that represents interface
1590 * {@code DessertTopping}.
1592 * <p> If this object represents an interface, the array contains objects
1593 * representing all interfaces extended by the interface. The order of the
1594 * interface objects in the array corresponds to the order of the interface
1595 * names in the {@code extends} clause of the declaration of the
1596 * interface represented by this object.
1598 * <p> If this object represents a class or interface that implements no
1599 * interfaces, the method returns an array of length 0.
1601 * <p> If this object represents a primitive type or void, the method
1602 * returns an array of length 0.
1604 * @return an array of interfaces implemented by this class.
1606 @JavaScriptBody(args = { }, body = "return this.interfaces();")
1607 public native Class<?>[] getInterfaces();
1610 * Returns the {@code Class} representing the component type of an
1611 * array. If this class does not represent an array class this method
1614 * @return the {@code Class} representing the component type of this
1615 * class if this class is an array
1616 * @see java.lang.reflect.Array
1619 public Class<?> getComponentType() {
1622 Class<?> c = getComponentTypeByFnc();
1623 return c != null ? c : getComponentType0();
1624 } catch (ClassNotFoundException cnfe) {
1625 throw new IllegalStateException(cnfe);
1631 @JavaScriptBody(args = { }, body =
1633 + " var c = this.fnc(false).constructor.$class;\n"
1634 // + " java.lang.System.out.println('will call: ' + (!!this.fnc) + ' res: ' + c.jvmName);\n"
1635 + " if (c) return c;\n"
1639 private native Class<?> getComponentTypeByFnc();
1641 private Class<?> getComponentType0() throws ClassNotFoundException {
1642 String n = getName().substring(1);
1643 switch (n.charAt(0)) {
1645 n = n.substring(1, n.length() - 1);
1646 return Class.forName(n);
1648 return Integer.TYPE;
1658 return Boolean.TYPE;
1664 return Character.TYPE;
1666 return defineArray(n, null);
1668 throw new ClassNotFoundException("Unknown component type of " + getName());
1672 @JavaScriptBody(args = { "sig", "fnc" }, body =
1673 "if (!sig) sig = '[Ljava/lang/Object;';\n" +
1674 "var c = Array[sig];\n" +
1676 " c = vm.java_lang_Class(true);\n" +
1677 " Object.defineProperty(c, 'jvmName', { 'configurable': true, 'writable': true, 'value': sig });\n" +
1678 " Object.defineProperty(c, 'superclass', { 'configurable': true, 'writable': true, 'value' : vm.java_lang_Object(false).$class });\n" +
1679 " Object.defineProperty(c, 'array', { 'configurable': true, 'writable': true, 'value': true });\n" +
1680 " Array[sig] = c;\n" +
1682 "if (!c.fnc) Object.defineProperty(c, 'fnc', { 'configurable': true, 'writable': true, 'value' : fnc });\n" +
1685 private static native Class<?> defineArray(String sig, Object fnc);
1688 * Returns true if and only if this class was declared as an enum in the
1691 * @return true if and only if this class was declared as an enum in the
1695 public boolean isEnum() {
1696 // An enum must both directly extend java.lang.Enum and have
1697 // the ENUM bit set; classes for specialized enum constants
1698 // don't do the former.
1699 return (this.getModifiers() & ENUM) != 0 &&
1700 this.getSuperclass() == java.lang.Enum.class;
1704 * Casts an object to the class or interface represented
1705 * by this {@code Class} object.
1707 * @param obj the object to be cast
1708 * @return the object after casting, or null if obj is null
1710 * @throws ClassCastException if the object is not
1711 * null and is not assignable to the type T.
1715 public T cast(Object obj) {
1716 if (obj != null && !isInstance(obj))
1717 throw new ClassCastException(cannotCastMsg(obj));
1721 private String cannotCastMsg(Object obj) {
1722 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
1726 * Casts this {@code Class} object to represent a subclass of the class
1727 * represented by the specified class object. Checks that that the cast
1728 * is valid, and throws a {@code ClassCastException} if it is not. If
1729 * this method succeeds, it always returns a reference to this class object.
1731 * <p>This method is useful when a client needs to "narrow" the type of
1732 * a {@code Class} object to pass it to an API that restricts the
1733 * {@code Class} objects that it is willing to accept. A cast would
1734 * generate a compile-time warning, as the correctness of the cast
1735 * could not be checked at runtime (because generic types are implemented
1738 * @return this {@code Class} object, cast to represent a subclass of
1739 * the specified class object.
1740 * @throws ClassCastException if this {@code Class} object does not
1741 * represent a subclass of the specified class (here "subclass" includes
1742 * the class itself).
1745 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
1746 if (clazz.isAssignableFrom(this))
1747 return (Class<? extends U>) this;
1749 throw new ClassCastException(this.toString());
1752 @JavaScriptBody(args = { "ac" },
1754 "if (this.anno) {\n"
1755 + " var r = this.anno['L' + ac.jvmName + ';'];\n"
1756 + " if (typeof r === 'undefined') r = null;\n"
1758 + "} else return null;\n"
1760 private Object getAnnotationData(Class<?> annotationClass) {
1761 throw new UnsupportedOperationException();
1764 * @throws NullPointerException {@inheritDoc}
1767 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
1768 Object data = getAnnotationData(annotationClass);
1769 return data == null ? null : AnnotationImpl.create(annotationClass, data);
1773 * @throws NullPointerException {@inheritDoc}
1776 @JavaScriptBody(args = { "ac" },
1777 body = "if (this.anno && this.anno['L' + ac.jvmName + ';']) { return true; }"
1778 + "else return false;"
1780 public boolean isAnnotationPresent(
1781 Class<? extends Annotation> annotationClass) {
1782 if (annotationClass == null)
1783 throw new NullPointerException();
1785 return getAnnotation(annotationClass) != null;
1788 @JavaScriptBody(args = {}, body = "return this.anno ? this.anno : null;")
1789 private native Object getAnnotationData();
1794 public Annotation[] getAnnotations() {
1795 Object data = getAnnotationData();
1796 return data == null ? new Annotation[0] : AnnotationImpl.create(data);
1802 public Annotation[] getDeclaredAnnotations() {
1803 return getAnnotations();
1806 @JavaScriptBody(args = "type", body = ""
1807 + "var c = vm.java_lang_Class(true);"
1808 + "c.jvmName = type;"
1809 + "c.primitive = true;"
1812 native static Class getPrimitiveClass(String type);
1814 @JavaScriptBody(args = {}, body =
1815 "return this['desiredAssertionStatus'] ? this['desiredAssertionStatus'] : false;"
1817 public native boolean desiredAssertionStatus();
1819 public boolean equals(Object obj) {
1820 if (isPrimitive() && obj instanceof Class) {
1821 Class c = ((Class)obj);
1822 return c.isPrimitive() && getName().equals(c.getName());
1824 return super.equals(obj);
1827 static void registerNatives() {
1828 boolean assertsOn = false;
1829 // assert assertsOn = true;
1833 } catch (Throwable ex) {
1839 @JavaScriptBody(args = {}, body = "var p = java_lang_Object(false);"
1840 + "p.toString = function() { return this.toString__Ljava_lang_String_2(); };"
1842 static native void registerToString();
1844 @JavaScriptBody(args = {"self"}, body
1845 = "var c = self.constructor.$class;\n"
1846 + "return c ? c : null;\n"
1848 static native Class<?> classFor(Object self);
1851 @JavaScriptBody(args = { "self" }, body
1852 = "if (self['$hashCode']) return self['$hashCode'];\n"
1853 + "var h = self['computeHashCode__I'] ? self['computeHashCode__I']() : Math.random() * Math.pow(2, 31);\n"
1854 + "return self['$hashCode'] = h & h;"
1856 static native int defaultHashCode(Object self);
1858 @JavaScriptBody(args = "self", body
1859 = "\nif (!self['$instOf_java_lang_Cloneable']) {"
1862 + "\n var clone = self.constructor(true);"
1863 + "\n var props = Object.getOwnPropertyNames(self);"
1864 + "\n for (var i = 0; i < props.length; i++) {"
1865 + "\n var p = props[i];"
1866 + "\n clone[p] = self[p];"
1868 + "\n return clone;"
1871 static native Object clone(Object self) throws CloneNotSupportedException;
1873 @JavaScriptOnly(name = "toJS", value = "function convToJS(v) {\n"
1874 + " if (v === null) return null;\n"
1875 + " if (Object.prototype.toString.call(v) === '[object Array]') {\n"
1876 + " return vm.org_apidesign_bck2brwsr_emul_lang_System(false).convArray__Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_Object_2(v, convToJS);\n"
1878 + " if (v instanceof Date) return v;\n"
1879 + " return v.valueOf();\n"
1882 static native int toJS();
1885 @JavaScriptOnly(name = "activate__Ljava_io_Closeable_2Lorg_apidesign_html_boot_spi_Fn$Presenter_2", value = "function() {\n"
1886 + " return vm.org_apidesign_bck2brwsr_emul_lang_System(false).activate__Ljava_io_Closeable_2();"
1889 static native int activate();
1892 @JavaScriptOnly(name = "activate__Ljava_io_Closeable_2Lorg_netbeans_html_boot_spi_Fn$Presenter_2", value = "function() {\n"
1893 + " return vm.org_apidesign_bck2brwsr_emul_lang_System(false).activate__Ljava_io_Closeable_2();"
1896 static native int activateNew();
1898 private static Object bck2BrwsrCnvrt(Object o) {
1899 if (o instanceof Throwable) {
1902 final String msg = msg(o);
1903 if (msg == null || msg.startsWith("TypeError")) {
1904 return new NullPointerException(msg);
1906 return new Throwable(msg);
1909 @JavaScriptBody(args = {"o"}, body = "return o ? o.toString() : null;")
1910 private static native String msg(Object o);
1913 @JavaScriptOnly(name = "bck2BrwsrThrwrbl", value = "c.bck2BrwsrCnvrt__Ljava_lang_Object_2Ljava_lang_Object_2")
1914 private static void bck2BrwsrCnvrtVM() {
1918 @JavaScriptOnly(name = "castEx", value = ""
1919 + "function(obj, type) {\n"
1920 + " var realType = obj.getClass__Ljava_lang_Class_2().getName__Ljava_lang_String_2();\n"
1921 + " var msg = realType + ' cannot be cast to ' + type;\n"
1922 + " var ex = vm.java_lang_ClassCastException(true);\n"
1923 + " ex.constructor.cons__VLjava_lang_String_2.call(ex, msg);;\n"
1928 private static void castEx() {