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 org.apidesign.bck2brwsr.emul.AnnotationImpl;
29 import java.io.InputStream;
30 import java.lang.annotation.Annotation;
31 import java.lang.reflect.Field;
32 import java.lang.reflect.Method;
33 import java.lang.reflect.TypeVariable;
34 import org.apidesign.bck2brwsr.core.JavaScriptBody;
35 import org.apidesign.bck2brwsr.emul.MethodImpl;
38 * Instances of the class {@code Class} represent classes and
39 * interfaces in a running Java application. An enum is a kind of
40 * class and an annotation is a kind of interface. Every array also
41 * belongs to a class that is reflected as a {@code Class} object
42 * that is shared by all arrays with the same element type and number
43 * of dimensions. The primitive Java types ({@code boolean},
44 * {@code byte}, {@code char}, {@code short},
45 * {@code int}, {@code long}, {@code float}, and
46 * {@code double}), and the keyword {@code void} are also
47 * represented as {@code Class} objects.
49 * <p> {@code Class} has no public constructor. Instead {@code Class}
50 * objects are constructed automatically by the Java Virtual Machine as classes
51 * are loaded and by calls to the {@code defineClass} method in the class
54 * <p> The following example uses a {@code Class} object to print the
55 * class name of an object:
57 * <p> <blockquote><pre>
58 * void printClassName(Object obj) {
59 * System.out.println("The class of " + obj +
60 * " is " + obj.getClass().getName());
64 * <p> It is also possible to get the {@code Class} object for a named
65 * type (or for void) using a class literal. See Section 15.8.2 of
66 * <cite>The Java™ Language Specification</cite>.
70 * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
73 * @param <T> the type of the class modeled by this {@code Class}
74 * object. For example, the type of {@code String.class} is {@code
75 * Class<String>}. Use {@code Class<?>} if the class being modeled is
79 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
83 class Class<T> implements java.io.Serializable,
84 java.lang.reflect.GenericDeclaration,
85 java.lang.reflect.Type,
86 java.lang.reflect.AnnotatedElement {
87 private static final int ANNOTATION= 0x00002000;
88 private static final int ENUM = 0x00004000;
89 private static final int SYNTHETIC = 0x00001000;
92 * Constructor. Only the Java Virtual Machine creates Class
99 * Converts the object to a string. The string representation is the
100 * string "class" or "interface", followed by a space, and then by the
101 * fully qualified name of the class in the format returned by
102 * {@code getName}. If this {@code Class} object represents a
103 * primitive type, this method returns the name of the primitive type. If
104 * this {@code Class} object represents void this method returns
107 * @return a string representation of this class object.
109 public String toString() {
110 return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
116 * Returns the {@code Class} object associated with the class or
117 * interface with the given string name. Invoking this method is
121 * {@code Class.forName(className, true, currentLoader)}
124 * where {@code currentLoader} denotes the defining class loader of
127 * <p> For example, the following code fragment returns the
128 * runtime {@code Class} descriptor for the class named
129 * {@code java.lang.Thread}:
132 * {@code Class t = Class.forName("java.lang.Thread")}
135 * A call to {@code forName("X")} causes the class named
136 * {@code X} to be initialized.
138 * @param className the fully qualified name of the desired class.
139 * @return the {@code Class} object for the class with the
141 * @exception LinkageError if the linkage fails
142 * @exception ExceptionInInitializerError if the initialization provoked
143 * by this method fails
144 * @exception ClassNotFoundException if the class cannot be located
146 public static Class<?> forName(String className)
147 throws ClassNotFoundException {
148 Class<?> c = loadCls(className, className.replace('.', '_'));
150 throw new ClassNotFoundException();
155 @JavaScriptBody(args = {"n", "c" }, body =
156 "if (vm[c]) return vm[c].$class;\n"
157 + "if (vm.loadClass) {\n"
158 + " vm.loadClass(n);\n"
159 + " if (vm[c]) return vm[c].$class;\n"
163 private static native Class<?> loadCls(String n, String c);
167 * Creates a new instance of the class represented by this {@code Class}
168 * object. The class is instantiated as if by a {@code new}
169 * expression with an empty argument list. The class is initialized if it
170 * has not already been initialized.
172 * <p>Note that this method propagates any exception thrown by the
173 * nullary constructor, including a checked exception. Use of
174 * this method effectively bypasses the compile-time exception
175 * checking that would otherwise be performed by the compiler.
177 * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
178 * Constructor.newInstance} method avoids this problem by wrapping
179 * any exception thrown by the constructor in a (checked) {@link
180 * java.lang.reflect.InvocationTargetException}.
182 * @return a newly allocated instance of the class represented by this
184 * @exception IllegalAccessException if the class or its nullary
185 * constructor is not accessible.
186 * @exception InstantiationException
187 * if this {@code Class} represents an abstract class,
188 * an interface, an array class, a primitive type, or void;
189 * or if the class has no nullary constructor;
190 * or if the instantiation fails for some other reason.
191 * @exception ExceptionInInitializerError if the initialization
192 * provoked by this method fails.
193 * @exception SecurityException
194 * If a security manager, <i>s</i>, is present and any of the
195 * following conditions is met:
200 * {@link SecurityManager#checkMemberAccess
201 * s.checkMemberAccess(this, Member.PUBLIC)} denies
202 * creation of new instances of this class
204 * <li> the caller's class loader is not the same as or an
205 * ancestor of the class loader for the current class and
206 * invocation of {@link SecurityManager#checkPackageAccess
207 * s.checkPackageAccess()} denies access to the package
213 @JavaScriptBody(args = "self", body =
214 "var inst = self.cnstr();"
215 + "inst.cons__V(inst);"
218 public T newInstance()
219 throws InstantiationException, IllegalAccessException
221 throw new UnsupportedOperationException();
225 * Determines if the specified {@code Object} is assignment-compatible
226 * with the object represented by this {@code Class}. This method is
227 * the dynamic equivalent of the Java language {@code instanceof}
228 * operator. The method returns {@code true} if the specified
229 * {@code Object} argument is non-null and can be cast to the
230 * reference type represented by this {@code Class} object without
231 * raising a {@code ClassCastException.} It returns {@code false}
234 * <p> Specifically, if this {@code Class} object represents a
235 * declared class, this method returns {@code true} if the specified
236 * {@code Object} argument is an instance of the represented class (or
237 * of any of its subclasses); it returns {@code false} otherwise. If
238 * this {@code Class} object represents an array class, this method
239 * returns {@code true} if the specified {@code Object} argument
240 * can be converted to an object of the array class by an identity
241 * conversion or by a widening reference conversion; it returns
242 * {@code false} otherwise. If this {@code Class} object
243 * represents an interface, this method returns {@code true} if the
244 * class or any superclass of the specified {@code Object} argument
245 * implements this interface; it returns {@code false} otherwise. If
246 * this {@code Class} object represents a primitive type, this method
247 * returns {@code false}.
249 * @param obj the object to check
250 * @return true if {@code obj} is an instance of this class
254 public native boolean isInstance(Object obj);
258 * Determines if the class or interface represented by this
259 * {@code Class} object is either the same as, or is a superclass or
260 * superinterface of, the class or interface represented by the specified
261 * {@code Class} parameter. It returns {@code true} if so;
262 * otherwise it returns {@code false}. If this {@code Class}
263 * object represents a primitive type, this method returns
264 * {@code true} if the specified {@code Class} parameter is
265 * exactly this {@code Class} object; otherwise it returns
268 * <p> Specifically, this method tests whether the type represented by the
269 * specified {@code Class} parameter can be converted to the type
270 * represented by this {@code Class} object via an identity conversion
271 * or via a widening reference conversion. See <em>The Java Language
272 * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
274 * @param cls the {@code Class} object to be checked
275 * @return the {@code boolean} value indicating whether objects of the
276 * type {@code cls} can be assigned to objects of this class
277 * @exception NullPointerException if the specified Class parameter is
281 public native boolean isAssignableFrom(Class<?> cls);
285 * Determines if the specified {@code Class} object represents an
288 * @return {@code true} if this object represents an interface;
289 * {@code false} otherwise.
291 public boolean isInterface() {
292 return (getAccess() & 0x200) != 0;
295 @JavaScriptBody(args = "self", body = "return self.access;")
296 private native int getAccess();
300 * Determines if this {@code Class} object represents an array class.
302 * @return {@code true} if this object represents an array class;
303 * {@code false} otherwise.
306 public boolean isArray() {
312 * Determines if the specified {@code Class} object represents a
315 * <p> There are nine predefined {@code Class} objects to represent
316 * the eight primitive types and void. These are created by the Java
317 * Virtual Machine, and have the same names as the primitive types that
318 * they represent, namely {@code boolean}, {@code byte},
319 * {@code char}, {@code short}, {@code int},
320 * {@code long}, {@code float}, and {@code double}.
322 * <p> These objects may only be accessed via the following public static
323 * final variables, and are the only {@code Class} objects for which
324 * this method returns {@code true}.
326 * @return true if and only if this class represents a primitive type
328 * @see java.lang.Boolean#TYPE
329 * @see java.lang.Character#TYPE
330 * @see java.lang.Byte#TYPE
331 * @see java.lang.Short#TYPE
332 * @see java.lang.Integer#TYPE
333 * @see java.lang.Long#TYPE
334 * @see java.lang.Float#TYPE
335 * @see java.lang.Double#TYPE
336 * @see java.lang.Void#TYPE
339 @JavaScriptBody(args = "self", body =
340 "if (self.primitive) return true;"
341 + "else return false;"
343 public native boolean isPrimitive();
346 * Returns true if this {@code Class} object represents an annotation
347 * type. Note that if this method returns true, {@link #isInterface()}
348 * would also return true, as all annotation types are also interfaces.
350 * @return {@code true} if this class object represents an annotation
351 * type; {@code false} otherwise
354 public boolean isAnnotation() {
355 return (getModifiers() & ANNOTATION) != 0;
359 * Returns {@code true} if this class is a synthetic class;
360 * returns {@code false} otherwise.
361 * @return {@code true} if and only if this class is a synthetic class as
362 * defined by the Java Language Specification.
365 public boolean isSynthetic() {
366 return (getModifiers() & SYNTHETIC) != 0;
370 * Returns the name of the entity (class, interface, array class,
371 * primitive type, or void) represented by this {@code Class} object,
372 * as a {@code String}.
374 * <p> If this class object represents a reference type that is not an
375 * array type then the binary name of the class is returned, as specified
377 * <cite>The Java™ Language Specification</cite>.
379 * <p> If this class object represents a primitive type or void, then the
380 * name returned is a {@code String} equal to the Java language
381 * keyword corresponding to the primitive type or void.
383 * <p> If this class object represents a class of arrays, then the internal
384 * form of the name consists of the name of the element type preceded by
385 * one or more '{@code [}' characters representing the depth of the array
386 * nesting. The encoding of element type names is as follows:
388 * <blockquote><table summary="Element types and encodings">
389 * <tr><th> Element Type <th> <th> Encoding
390 * <tr><td> boolean <td> <td align=center> Z
391 * <tr><td> byte <td> <td align=center> B
392 * <tr><td> char <td> <td align=center> C
393 * <tr><td> class or interface
394 * <td> <td align=center> L<i>classname</i>;
395 * <tr><td> double <td> <td align=center> D
396 * <tr><td> float <td> <td align=center> F
397 * <tr><td> int <td> <td align=center> I
398 * <tr><td> long <td> <td align=center> J
399 * <tr><td> short <td> <td align=center> S
400 * </table></blockquote>
402 * <p> The class or interface name <i>classname</i> is the binary name of
403 * the class specified above.
407 * String.class.getName()
408 * returns "java.lang.String"
409 * byte.class.getName()
411 * (new Object[3]).getClass().getName()
412 * returns "[Ljava.lang.Object;"
413 * (new int[3][4][5][6][7][8][9]).getClass().getName()
415 * </pre></blockquote>
417 * @return the name of the class or interface
418 * represented by this object.
420 public String getName() {
421 return jvmName().replace('/', '.');
424 @JavaScriptBody(args = "self", body = "return self.jvmName;")
425 private native String jvmName();
429 * Returns an array of {@code TypeVariable} objects that represent the
430 * type variables declared by the generic declaration represented by this
431 * {@code GenericDeclaration} object, in declaration order. Returns an
432 * array of length 0 if the underlying generic declaration declares no type
435 * @return an array of {@code TypeVariable} objects that represent
436 * the type variables declared by this generic declaration
437 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
438 * signature of this generic declaration does not conform to
439 * the format specified in
440 * <cite>The Java™ Virtual Machine Specification</cite>
443 public TypeVariable<Class<T>>[] getTypeParameters() {
444 throw new UnsupportedOperationException();
448 * Returns the {@code Class} representing the superclass of the entity
449 * (class, interface, primitive type or void) represented by this
450 * {@code Class}. If this {@code Class} represents either the
451 * {@code Object} class, an interface, a primitive type, or void, then
452 * null is returned. If this object represents an array class then the
453 * {@code Class} object representing the {@code Object} class is
456 * @return the superclass of the class represented by this object.
458 @JavaScriptBody(args = "self", body = "return self.superclass;")
459 public native Class<? super T> getSuperclass();
462 * Returns the Java language modifiers for this class or interface, encoded
463 * in an integer. The modifiers consist of the Java Virtual Machine's
464 * constants for {@code public}, {@code protected},
465 * {@code private}, {@code final}, {@code static},
466 * {@code abstract} and {@code interface}; they should be decoded
467 * using the methods of class {@code Modifier}.
469 * <p> If the underlying class is an array class, then its
470 * {@code public}, {@code private} and {@code protected}
471 * modifiers are the same as those of its component type. If this
472 * {@code Class} represents a primitive type or void, its
473 * {@code public} modifier is always {@code true}, and its
474 * {@code protected} and {@code private} modifiers are always
475 * {@code false}. If this object represents an array class, a
476 * primitive type or void, then its {@code final} modifier is always
477 * {@code true} and its interface modifier is always
478 * {@code false}. The values of its other modifiers are not determined
479 * by this specification.
481 * <p> The modifier encodings are defined in <em>The Java Virtual Machine
482 * Specification</em>, table 4.1.
484 * @return the {@code int} representing the modifiers for this class
485 * @see java.lang.reflect.Modifier
488 public native int getModifiers();
492 * Returns the simple name of the underlying class as given in the
493 * source code. Returns an empty string if the underlying class is
496 * <p>The simple name of an array is the simple name of the
497 * component type with "[]" appended. In particular the simple
498 * name of an array whose component type is anonymous is "[]".
500 * @return the simple name of the underlying class
503 public String getSimpleName() {
505 return getComponentType().getSimpleName()+"[]";
507 String simpleName = getSimpleBinaryName();
508 if (simpleName == null) { // top level class
509 simpleName = getName();
510 return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
512 // According to JLS3 "Binary Compatibility" (13.1) the binary
513 // name of non-package classes (not top level) is the binary
514 // name of the immediately enclosing class followed by a '$' followed by:
515 // (for nested and inner classes): the simple name.
516 // (for local classes): 1 or more digits followed by the simple name.
517 // (for anonymous classes): 1 or more digits.
519 // Since getSimpleBinaryName() will strip the binary name of
520 // the immediatly enclosing class, we are now looking at a
521 // string that matches the regular expression "\$[0-9]*"
522 // followed by a simple name (considering the simple of an
523 // anonymous class to be the empty string).
525 // Remove leading "\$[0-9]*" from the name
526 int length = simpleName.length();
527 if (length < 1 || simpleName.charAt(0) != '$')
528 throw new IllegalStateException("Malformed class name");
530 while (index < length && isAsciiDigit(simpleName.charAt(index)))
532 // Eventually, this is the empty string iff this is an anonymous class
533 return simpleName.substring(index);
537 * Returns the "simple binary name" of the underlying class, i.e.,
538 * the binary name without the leading enclosing class name.
539 * Returns {@code null} if the underlying class is a top level
542 private String getSimpleBinaryName() {
543 Class<?> enclosingClass = null; // XXX getEnclosingClass();
544 if (enclosingClass == null) // top level class
546 // Otherwise, strip the enclosing class' name
548 return getName().substring(enclosingClass.getName().length());
549 } catch (IndexOutOfBoundsException ex) {
550 throw new IllegalStateException("Malformed class name");
555 * Returns an array containing {@code Field} objects reflecting all
556 * the accessible public fields of the class or interface represented by
557 * this {@code Class} object. The elements in the array returned are
558 * not sorted and are not in any particular order. This method returns an
559 * array of length 0 if the class or interface has no accessible public
560 * fields, or if it represents an array class, a primitive type, or void.
562 * <p> Specifically, if this {@code Class} object represents a class,
563 * this method returns the public fields of this class and of all its
564 * superclasses. If this {@code Class} object represents an
565 * interface, this method returns the fields of this interface and of all
566 * its superinterfaces.
568 * <p> The implicit length field for array class is not reflected by this
569 * method. User code should use the methods of class {@code Array} to
572 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
574 * @return the array of {@code Field} objects representing the
576 * @exception SecurityException
577 * If a security manager, <i>s</i>, is present and any of the
578 * following conditions is met:
583 * {@link SecurityManager#checkMemberAccess
584 * s.checkMemberAccess(this, Member.PUBLIC)} denies
585 * access to the fields within this class
587 * <li> the caller's class loader is not the same as or an
588 * ancestor of the class loader for the current class and
589 * invocation of {@link SecurityManager#checkPackageAccess
590 * s.checkPackageAccess()} denies access to the package
597 public Field[] getFields() throws SecurityException {
598 throw new SecurityException();
602 * Returns an array containing {@code Method} objects reflecting all
603 * the public <em>member</em> methods of the class or interface represented
604 * by this {@code Class} object, including those declared by the class
605 * or interface and those inherited from superclasses and
606 * superinterfaces. Array classes return all the (public) member methods
607 * inherited from the {@code Object} class. The elements in the array
608 * returned are not sorted and are not in any particular order. This
609 * method returns an array of length 0 if this {@code Class} object
610 * represents a class or interface that has no public member methods, or if
611 * this {@code Class} object represents a primitive type or void.
613 * <p> The class initialization method {@code <clinit>} is not
614 * included in the returned array. If the class declares multiple public
615 * member methods with the same parameter types, they are all included in
616 * the returned array.
618 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
620 * @return the array of {@code Method} objects representing the
621 * public methods of this class
622 * @exception SecurityException
623 * If a security manager, <i>s</i>, is present and any of the
624 * following conditions is met:
629 * {@link SecurityManager#checkMemberAccess
630 * s.checkMemberAccess(this, Member.PUBLIC)} denies
631 * access to the methods within this class
633 * <li> the caller's class loader is not the same as or an
634 * ancestor of the class loader for the current class and
635 * invocation of {@link SecurityManager#checkPackageAccess
636 * s.checkPackageAccess()} denies access to the package
643 public Method[] getMethods() throws SecurityException {
644 return MethodImpl.findMethods(this);
648 * Returns a {@code Field} object that reflects the specified public
649 * member field of the class or interface represented by this
650 * {@code Class} object. The {@code name} parameter is a
651 * {@code String} specifying the simple name of the desired field.
653 * <p> The field to be reflected is determined by the algorithm that
654 * follows. Let C be the class represented by this object:
656 * <LI> If C declares a public field with the name specified, that is the
657 * field to be reflected.</LI>
658 * <LI> If no field was found in step 1 above, this algorithm is applied
659 * recursively to each direct superinterface of C. The direct
660 * superinterfaces are searched in the order they were declared.</LI>
661 * <LI> If no field was found in steps 1 and 2 above, and C has a
662 * superclass S, then this algorithm is invoked recursively upon S.
663 * If C has no superclass, then a {@code NoSuchFieldException}
667 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
669 * @param name the field name
670 * @return the {@code Field} object of this class specified by
672 * @exception NoSuchFieldException if a field with the specified name is
674 * @exception NullPointerException if {@code name} is {@code null}
675 * @exception SecurityException
676 * If a security manager, <i>s</i>, is present and any of the
677 * following conditions is met:
682 * {@link SecurityManager#checkMemberAccess
683 * s.checkMemberAccess(this, Member.PUBLIC)} denies
684 * access to the field
686 * <li> the caller's class loader is not the same as or an
687 * ancestor of the class loader for the current class and
688 * invocation of {@link SecurityManager#checkPackageAccess
689 * s.checkPackageAccess()} denies access to the package
696 public Field getField(String name)
697 throws SecurityException {
698 throw new SecurityException();
703 * Returns a {@code Method} object that reflects the specified public
704 * member method of the class or interface represented by this
705 * {@code Class} object. The {@code name} parameter is a
706 * {@code String} specifying the simple name of the desired method. The
707 * {@code parameterTypes} parameter is an array of {@code Class}
708 * objects that identify the method's formal parameter types, in declared
709 * order. If {@code parameterTypes} is {@code null}, it is
710 * treated as if it were an empty array.
712 * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
713 * {@code NoSuchMethodException} is raised. Otherwise, the method to
714 * be reflected is determined by the algorithm that follows. Let C be the
715 * class represented by this object:
717 * <LI> C is searched for any <I>matching methods</I>. If no matching
718 * method is found, the algorithm of step 1 is invoked recursively on
719 * the superclass of C.</LI>
720 * <LI> If no method was found in step 1 above, the superinterfaces of C
721 * are searched for a matching method. If any such method is found, it
725 * To find a matching method in a class C: If C declares exactly one
726 * public method with the specified name and exactly the same formal
727 * parameter types, that is the method reflected. If more than one such
728 * method is found in C, and one of these methods has a return type that is
729 * more specific than any of the others, that method is reflected;
730 * otherwise one of the methods is chosen arbitrarily.
732 * <p>Note that there may be more than one matching method in a
733 * class because while the Java language forbids a class to
734 * declare multiple methods with the same signature but different
735 * return types, the Java virtual machine does not. This
736 * increased flexibility in the virtual machine can be used to
737 * implement various language features. For example, covariant
738 * returns can be implemented with {@linkplain
739 * java.lang.reflect.Method#isBridge bridge methods}; the bridge
740 * method and the method being overridden would have the same
741 * signature but different return types.
743 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
745 * @param name the name of the method
746 * @param parameterTypes the list of parameters
747 * @return the {@code Method} object that matches the specified
748 * {@code name} and {@code parameterTypes}
749 * @exception NoSuchMethodException if a matching method is not found
750 * or if the name is "<init>"or "<clinit>".
751 * @exception NullPointerException if {@code name} is {@code null}
752 * @exception SecurityException
753 * If a security manager, <i>s</i>, is present and any of the
754 * following conditions is met:
759 * {@link SecurityManager#checkMemberAccess
760 * s.checkMemberAccess(this, Member.PUBLIC)} denies
761 * access to the method
763 * <li> the caller's class loader is not the same as or an
764 * ancestor of the class loader for the current class and
765 * invocation of {@link SecurityManager#checkPackageAccess
766 * s.checkPackageAccess()} denies access to the package
773 public Method getMethod(String name, Class<?>... parameterTypes)
774 throws SecurityException {
775 Method m = MethodImpl.findMethod(this, name, parameterTypes);
777 throw new SecurityException(); // XXX: NoSuchMethodException
783 * Character.isDigit answers {@code true} to some non-ascii
784 * digits. This one does not.
786 private static boolean isAsciiDigit(char c) {
787 return '0' <= c && c <= '9';
791 * Returns the canonical name of the underlying class as
792 * defined by the Java Language Specification. Returns null if
793 * the underlying class does not have a canonical name (i.e., if
794 * it is a local or anonymous class or an array whose component
795 * type does not have a canonical name).
796 * @return the canonical name of the underlying class if it exists, and
797 * {@code null} otherwise.
800 public String getCanonicalName() {
802 String canonicalName = getComponentType().getCanonicalName();
803 if (canonicalName != null)
804 return canonicalName + "[]";
808 // if (isLocalOrAnonymousClass())
810 // Class<?> enclosingClass = getEnclosingClass();
811 Class<?> enclosingClass = null;
812 if (enclosingClass == null) { // top level class
815 String enclosingName = enclosingClass.getCanonicalName();
816 if (enclosingName == null)
818 return enclosingName + "." + getSimpleName();
823 * Finds a resource with a given name. The rules for searching resources
824 * associated with a given class are implemented by the defining
825 * {@linkplain ClassLoader class loader} of the class. This method
826 * delegates to this object's class loader. If this object was loaded by
827 * the bootstrap class loader, the method delegates to {@link
828 * ClassLoader#getSystemResourceAsStream}.
830 * <p> Before delegation, an absolute resource name is constructed from the
831 * given resource name using this algorithm:
835 * <li> If the {@code name} begins with a {@code '/'}
836 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
837 * portion of the {@code name} following the {@code '/'}.
839 * <li> Otherwise, the absolute name is of the following form:
842 * {@code modified_package_name/name}
845 * <p> Where the {@code modified_package_name} is the package name of this
846 * object with {@code '/'} substituted for {@code '.'}
847 * (<tt>'\u002e'</tt>).
851 * @param name name of the desired resource
852 * @return A {@link java.io.InputStream} object or {@code null} if
853 * no resource with this name is found
854 * @throws NullPointerException If {@code name} is {@code null}
857 public InputStream getResourceAsStream(String name) {
858 name = resolveName(name);
859 ClassLoader cl = getClassLoader0();
862 return ClassLoader.getSystemResourceAsStream(name);
864 return cl.getResourceAsStream(name);
868 * Finds a resource with a given name. The rules for searching resources
869 * associated with a given class are implemented by the defining
870 * {@linkplain ClassLoader class loader} of the class. This method
871 * delegates to this object's class loader. If this object was loaded by
872 * the bootstrap class loader, the method delegates to {@link
873 * ClassLoader#getSystemResource}.
875 * <p> Before delegation, an absolute resource name is constructed from the
876 * given resource name using this algorithm:
880 * <li> If the {@code name} begins with a {@code '/'}
881 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
882 * portion of the {@code name} following the {@code '/'}.
884 * <li> Otherwise, the absolute name is of the following form:
887 * {@code modified_package_name/name}
890 * <p> Where the {@code modified_package_name} is the package name of this
891 * object with {@code '/'} substituted for {@code '.'}
892 * (<tt>'\u002e'</tt>).
896 * @param name name of the desired resource
897 * @return A {@link java.net.URL} object or {@code null} if no
898 * resource with this name is found
901 public java.net.URL getResource(String name) {
902 name = resolveName(name);
903 ClassLoader cl = getClassLoader0();
906 return ClassLoader.getSystemResource(name);
908 return cl.getResource(name);
913 * Add a package name prefix if the name is not absolute Remove leading "/"
914 * if name is absolute
916 private String resolveName(String name) {
920 if (!name.startsWith("/")) {
922 while (c.isArray()) {
923 c = c.getComponentType();
925 String baseName = c.getName();
926 int index = baseName.lastIndexOf('.');
928 name = baseName.substring(0, index).replace('.', '/')
932 name = name.substring(1);
938 * Returns the class loader for the class. Some implementations may use
939 * null to represent the bootstrap class loader. This method will return
940 * null in such implementations if this class was loaded by the bootstrap
943 * <p> If a security manager is present, and the caller's class loader is
944 * not null and the caller's class loader is not the same as or an ancestor of
945 * the class loader for the class whose class loader is requested, then
946 * this method calls the security manager's {@code checkPermission}
947 * method with a {@code RuntimePermission("getClassLoader")}
948 * permission to ensure it's ok to access the class loader for the class.
951 * represents a primitive type or void, null is returned.
953 * @return the class loader that loaded the class or interface
954 * represented by this object.
955 * @throws SecurityException
956 * if a security manager exists and its
957 * {@code checkPermission} method denies
958 * access to the class loader for the class.
959 * @see java.lang.ClassLoader
960 * @see SecurityManager#checkPermission
961 * @see java.lang.RuntimePermission
963 public ClassLoader getClassLoader() {
964 throw new SecurityException();
967 // Package-private to allow ClassLoader access
968 native ClassLoader getClassLoader0();
971 * Returns the {@code Class} representing the component type of an
972 * array. If this class does not represent an array class this method
975 * @return the {@code Class} representing the component type of this
976 * class if this class is an array
977 * @see java.lang.reflect.Array
980 public Class<?> getComponentType() {
985 * Returns true if and only if this class was declared as an enum in the
988 * @return true if and only if this class was declared as an enum in the
992 public boolean isEnum() {
993 // An enum must both directly extend java.lang.Enum and have
994 // the ENUM bit set; classes for specialized enum constants
995 // don't do the former.
996 return (this.getModifiers() & ENUM) != 0 &&
997 this.getSuperclass() == java.lang.Enum.class;
1001 * Casts an object to the class or interface represented
1002 * by this {@code Class} object.
1004 * @param obj the object to be cast
1005 * @return the object after casting, or null if obj is null
1007 * @throws ClassCastException if the object is not
1008 * null and is not assignable to the type T.
1012 public T cast(Object obj) {
1013 if (obj != null && !isInstance(obj))
1014 throw new ClassCastException(cannotCastMsg(obj));
1018 private String cannotCastMsg(Object obj) {
1019 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
1023 * Casts this {@code Class} object to represent a subclass of the class
1024 * represented by the specified class object. Checks that that the cast
1025 * is valid, and throws a {@code ClassCastException} if it is not. If
1026 * this method succeeds, it always returns a reference to this class object.
1028 * <p>This method is useful when a client needs to "narrow" the type of
1029 * a {@code Class} object to pass it to an API that restricts the
1030 * {@code Class} objects that it is willing to accept. A cast would
1031 * generate a compile-time warning, as the correctness of the cast
1032 * could not be checked at runtime (because generic types are implemented
1035 * @return this {@code Class} object, cast to represent a subclass of
1036 * the specified class object.
1037 * @throws ClassCastException if this {@code Class} object does not
1038 * represent a subclass of the specified class (here "subclass" includes
1039 * the class itself).
1042 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
1043 if (clazz.isAssignableFrom(this))
1044 return (Class<? extends U>) this;
1046 throw new ClassCastException(this.toString());
1049 @JavaScriptBody(args = { "self", "ac" },
1052 + " return self.anno['L' + ac.jvmName + ';'];"
1053 + "} else return null;"
1055 private Object getAnnotationData(Class<?> annotationClass) {
1056 throw new UnsupportedOperationException();
1059 * @throws NullPointerException {@inheritDoc}
1062 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
1063 Object data = getAnnotationData(annotationClass);
1064 return data == null ? null : AnnotationImpl.create(annotationClass, data);
1068 * @throws NullPointerException {@inheritDoc}
1071 @JavaScriptBody(args = { "self", "ac" },
1072 body = "if (self.anno && self.anno['L' + ac.jvmName + ';']) { return true; }"
1073 + "else return false;"
1075 public boolean isAnnotationPresent(
1076 Class<? extends Annotation> annotationClass) {
1077 if (annotationClass == null)
1078 throw new NullPointerException();
1080 return getAnnotation(annotationClass) != null;
1083 @JavaScriptBody(args = "self", body = "return self.anno;")
1084 private Object getAnnotationData() {
1085 throw new UnsupportedOperationException();
1091 public Annotation[] getAnnotations() {
1092 Object data = getAnnotationData();
1093 return data == null ? new Annotation[0] : AnnotationImpl.create(data);
1099 public Annotation[] getDeclaredAnnotations() {
1100 throw new UnsupportedOperationException();
1103 @JavaScriptBody(args = "type", body = ""
1104 + "var c = vm.java_lang_Class(true);"
1105 + "c.jvmName = type;"
1106 + "c.primitive = true;"
1109 native static Class getPrimitiveClass(String type);
1111 public boolean desiredAssertionStatus() {