Support for reflection on primitive types. All tests finish in the browser.
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;
37 * Instances of the class {@code Class} represent classes and
38 * interfaces in a running Java application. An enum is a kind of
39 * class and an annotation is a kind of interface. Every array also
40 * belongs to a class that is reflected as a {@code Class} object
41 * that is shared by all arrays with the same element type and number
42 * of dimensions. The primitive Java types ({@code boolean},
43 * {@code byte}, {@code char}, {@code short},
44 * {@code int}, {@code long}, {@code float}, and
45 * {@code double}), and the keyword {@code void} are also
46 * represented as {@code Class} objects.
48 * <p> {@code Class} has no public constructor. Instead {@code Class}
49 * objects are constructed automatically by the Java Virtual Machine as classes
50 * are loaded and by calls to the {@code defineClass} method in the class
53 * <p> The following example uses a {@code Class} object to print the
54 * class name of an object:
56 * <p> <blockquote><pre>
57 * void printClassName(Object obj) {
58 * System.out.println("The class of " + obj +
59 * " is " + obj.getClass().getName());
63 * <p> It is also possible to get the {@code Class} object for a named
64 * type (or for void) using a class literal. See Section 15.8.2 of
65 * <cite>The Java™ Language Specification</cite>.
69 * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
72 * @param <T> the type of the class modeled by this {@code Class}
73 * object. For example, the type of {@code String.class} is {@code
74 * Class<String>}. Use {@code Class<?>} if the class being modeled is
78 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
82 class Class<T> implements java.io.Serializable,
83 java.lang.reflect.GenericDeclaration,
84 java.lang.reflect.Type,
85 java.lang.reflect.AnnotatedElement {
86 private static final int ANNOTATION= 0x00002000;
87 private static final int ENUM = 0x00004000;
88 private static final int SYNTHETIC = 0x00001000;
91 * Constructor. Only the Java Virtual Machine creates Class
98 * Converts the object to a string. The string representation is the
99 * string "class" or "interface", followed by a space, and then by the
100 * fully qualified name of the class in the format returned by
101 * {@code getName}. If this {@code Class} object represents a
102 * primitive type, this method returns the name of the primitive type. If
103 * this {@code Class} object represents void this method returns
106 * @return a string representation of this class object.
108 public String toString() {
109 return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
115 * Returns the {@code Class} object associated with the class or
116 * interface with the given string name. Invoking this method is
120 * {@code Class.forName(className, true, currentLoader)}
123 * where {@code currentLoader} denotes the defining class loader of
126 * <p> For example, the following code fragment returns the
127 * runtime {@code Class} descriptor for the class named
128 * {@code java.lang.Thread}:
131 * {@code Class t = Class.forName("java.lang.Thread")}
134 * A call to {@code forName("X")} causes the class named
135 * {@code X} to be initialized.
137 * @param className the fully qualified name of the desired class.
138 * @return the {@code Class} object for the class with the
140 * @exception LinkageError if the linkage fails
141 * @exception ExceptionInInitializerError if the initialization provoked
142 * by this method fails
143 * @exception ClassNotFoundException if the class cannot be located
145 public static Class<?> forName(String className)
146 throws ClassNotFoundException {
147 Class<?> c = loadCls(className, className.replace('.', '_'));
149 throw new ClassNotFoundException();
154 @JavaScriptBody(args = {"n", "c" }, body =
155 "if (vm[c]) return vm[c].$class;\n"
156 + "if (vm.loadClass) {\n"
157 + " vm.loadClass(n);\n"
158 + " if (vm[c]) return vm[c].$class;\n"
162 private static native Class<?> loadCls(String n, String c);
166 * Creates a new instance of the class represented by this {@code Class}
167 * object. The class is instantiated as if by a {@code new}
168 * expression with an empty argument list. The class is initialized if it
169 * has not already been initialized.
171 * <p>Note that this method propagates any exception thrown by the
172 * nullary constructor, including a checked exception. Use of
173 * this method effectively bypasses the compile-time exception
174 * checking that would otherwise be performed by the compiler.
176 * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
177 * Constructor.newInstance} method avoids this problem by wrapping
178 * any exception thrown by the constructor in a (checked) {@link
179 * java.lang.reflect.InvocationTargetException}.
181 * @return a newly allocated instance of the class represented by this
183 * @exception IllegalAccessException if the class or its nullary
184 * constructor is not accessible.
185 * @exception InstantiationException
186 * if this {@code Class} represents an abstract class,
187 * an interface, an array class, a primitive type, or void;
188 * or if the class has no nullary constructor;
189 * or if the instantiation fails for some other reason.
190 * @exception ExceptionInInitializerError if the initialization
191 * provoked by this method fails.
192 * @exception SecurityException
193 * If a security manager, <i>s</i>, is present and any of the
194 * following conditions is met:
199 * {@link SecurityManager#checkMemberAccess
200 * s.checkMemberAccess(this, Member.PUBLIC)} denies
201 * creation of new instances of this class
203 * <li> the caller's class loader is not the same as or an
204 * ancestor of the class loader for the current class and
205 * invocation of {@link SecurityManager#checkPackageAccess
206 * s.checkPackageAccess()} denies access to the package
212 @JavaScriptBody(args = "self", body =
213 "var inst = self.cnstr();"
214 + "inst.cons__V(inst);"
217 public T newInstance()
218 throws InstantiationException, IllegalAccessException
220 throw new UnsupportedOperationException();
224 * Determines if the specified {@code Object} is assignment-compatible
225 * with the object represented by this {@code Class}. This method is
226 * the dynamic equivalent of the Java language {@code instanceof}
227 * operator. The method returns {@code true} if the specified
228 * {@code Object} argument is non-null and can be cast to the
229 * reference type represented by this {@code Class} object without
230 * raising a {@code ClassCastException.} It returns {@code false}
233 * <p> Specifically, if this {@code Class} object represents a
234 * declared class, this method returns {@code true} if the specified
235 * {@code Object} argument is an instance of the represented class (or
236 * of any of its subclasses); it returns {@code false} otherwise. If
237 * this {@code Class} object represents an array class, this method
238 * returns {@code true} if the specified {@code Object} argument
239 * can be converted to an object of the array class by an identity
240 * conversion or by a widening reference conversion; it returns
241 * {@code false} otherwise. If this {@code Class} object
242 * represents an interface, this method returns {@code true} if the
243 * class or any superclass of the specified {@code Object} argument
244 * implements this interface; it returns {@code false} otherwise. If
245 * this {@code Class} object represents a primitive type, this method
246 * returns {@code false}.
248 * @param obj the object to check
249 * @return true if {@code obj} is an instance of this class
253 public native boolean isInstance(Object obj);
257 * Determines if the class or interface represented by this
258 * {@code Class} object is either the same as, or is a superclass or
259 * superinterface of, the class or interface represented by the specified
260 * {@code Class} parameter. It returns {@code true} if so;
261 * otherwise it returns {@code false}. If this {@code Class}
262 * object represents a primitive type, this method returns
263 * {@code true} if the specified {@code Class} parameter is
264 * exactly this {@code Class} object; otherwise it returns
267 * <p> Specifically, this method tests whether the type represented by the
268 * specified {@code Class} parameter can be converted to the type
269 * represented by this {@code Class} object via an identity conversion
270 * or via a widening reference conversion. See <em>The Java Language
271 * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
273 * @param cls the {@code Class} object to be checked
274 * @return the {@code boolean} value indicating whether objects of the
275 * type {@code cls} can be assigned to objects of this class
276 * @exception NullPointerException if the specified Class parameter is
280 public native boolean isAssignableFrom(Class<?> cls);
284 * Determines if the specified {@code Class} object represents an
287 * @return {@code true} if this object represents an interface;
288 * {@code false} otherwise.
290 public boolean isInterface() {
291 return (getAccess() & 0x200) != 0;
294 @JavaScriptBody(args = "self", body = "return self.access;")
295 private native int getAccess();
299 * Determines if this {@code Class} object represents an array class.
301 * @return {@code true} if this object represents an array class;
302 * {@code false} otherwise.
305 public boolean isArray() {
311 * Determines if the specified {@code Class} object represents a
314 * <p> There are nine predefined {@code Class} objects to represent
315 * the eight primitive types and void. These are created by the Java
316 * Virtual Machine, and have the same names as the primitive types that
317 * they represent, namely {@code boolean}, {@code byte},
318 * {@code char}, {@code short}, {@code int},
319 * {@code long}, {@code float}, and {@code double}.
321 * <p> These objects may only be accessed via the following public static
322 * final variables, and are the only {@code Class} objects for which
323 * this method returns {@code true}.
325 * @return true if and only if this class represents a primitive type
327 * @see java.lang.Boolean#TYPE
328 * @see java.lang.Character#TYPE
329 * @see java.lang.Byte#TYPE
330 * @see java.lang.Short#TYPE
331 * @see java.lang.Integer#TYPE
332 * @see java.lang.Long#TYPE
333 * @see java.lang.Float#TYPE
334 * @see java.lang.Double#TYPE
335 * @see java.lang.Void#TYPE
338 @JavaScriptBody(args = "self", body =
339 "if (self.primitive) return true;"
340 + "else return false;"
342 public native boolean isPrimitive();
345 * Returns true if this {@code Class} object represents an annotation
346 * type. Note that if this method returns true, {@link #isInterface()}
347 * would also return true, as all annotation types are also interfaces.
349 * @return {@code true} if this class object represents an annotation
350 * type; {@code false} otherwise
353 public boolean isAnnotation() {
354 return (getModifiers() & ANNOTATION) != 0;
358 * Returns {@code true} if this class is a synthetic class;
359 * returns {@code false} otherwise.
360 * @return {@code true} if and only if this class is a synthetic class as
361 * defined by the Java Language Specification.
364 public boolean isSynthetic() {
365 return (getModifiers() & SYNTHETIC) != 0;
369 * Returns the name of the entity (class, interface, array class,
370 * primitive type, or void) represented by this {@code Class} object,
371 * as a {@code String}.
373 * <p> If this class object represents a reference type that is not an
374 * array type then the binary name of the class is returned, as specified
376 * <cite>The Java™ Language Specification</cite>.
378 * <p> If this class object represents a primitive type or void, then the
379 * name returned is a {@code String} equal to the Java language
380 * keyword corresponding to the primitive type or void.
382 * <p> If this class object represents a class of arrays, then the internal
383 * form of the name consists of the name of the element type preceded by
384 * one or more '{@code [}' characters representing the depth of the array
385 * nesting. The encoding of element type names is as follows:
387 * <blockquote><table summary="Element types and encodings">
388 * <tr><th> Element Type <th> <th> Encoding
389 * <tr><td> boolean <td> <td align=center> Z
390 * <tr><td> byte <td> <td align=center> B
391 * <tr><td> char <td> <td align=center> C
392 * <tr><td> class or interface
393 * <td> <td align=center> L<i>classname</i>;
394 * <tr><td> double <td> <td align=center> D
395 * <tr><td> float <td> <td align=center> F
396 * <tr><td> int <td> <td align=center> I
397 * <tr><td> long <td> <td align=center> J
398 * <tr><td> short <td> <td align=center> S
399 * </table></blockquote>
401 * <p> The class or interface name <i>classname</i> is the binary name of
402 * the class specified above.
406 * String.class.getName()
407 * returns "java.lang.String"
408 * byte.class.getName()
410 * (new Object[3]).getClass().getName()
411 * returns "[Ljava.lang.Object;"
412 * (new int[3][4][5][6][7][8][9]).getClass().getName()
414 * </pre></blockquote>
416 * @return the name of the class or interface
417 * represented by this object.
419 public String getName() {
420 return jvmName().replace('/', '.');
423 @JavaScriptBody(args = "self", body = "return self.jvmName;")
424 private native String jvmName();
428 * Returns an array of {@code TypeVariable} objects that represent the
429 * type variables declared by the generic declaration represented by this
430 * {@code GenericDeclaration} object, in declaration order. Returns an
431 * array of length 0 if the underlying generic declaration declares no type
434 * @return an array of {@code TypeVariable} objects that represent
435 * the type variables declared by this generic declaration
436 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
437 * signature of this generic declaration does not conform to
438 * the format specified in
439 * <cite>The Java™ Virtual Machine Specification</cite>
442 public TypeVariable<Class<T>>[] getTypeParameters() {
443 throw new UnsupportedOperationException();
447 * Returns the {@code Class} representing the superclass of the entity
448 * (class, interface, primitive type or void) represented by this
449 * {@code Class}. If this {@code Class} represents either the
450 * {@code Object} class, an interface, a primitive type, or void, then
451 * null is returned. If this object represents an array class then the
452 * {@code Class} object representing the {@code Object} class is
455 * @return the superclass of the class represented by this object.
457 @JavaScriptBody(args = "self", body = "return self.superclass;")
458 public native Class<? super T> getSuperclass();
461 * Returns the Java language modifiers for this class or interface, encoded
462 * in an integer. The modifiers consist of the Java Virtual Machine's
463 * constants for {@code public}, {@code protected},
464 * {@code private}, {@code final}, {@code static},
465 * {@code abstract} and {@code interface}; they should be decoded
466 * using the methods of class {@code Modifier}.
468 * <p> If the underlying class is an array class, then its
469 * {@code public}, {@code private} and {@code protected}
470 * modifiers are the same as those of its component type. If this
471 * {@code Class} represents a primitive type or void, its
472 * {@code public} modifier is always {@code true}, and its
473 * {@code protected} and {@code private} modifiers are always
474 * {@code false}. If this object represents an array class, a
475 * primitive type or void, then its {@code final} modifier is always
476 * {@code true} and its interface modifier is always
477 * {@code false}. The values of its other modifiers are not determined
478 * by this specification.
480 * <p> The modifier encodings are defined in <em>The Java Virtual Machine
481 * Specification</em>, table 4.1.
483 * @return the {@code int} representing the modifiers for this class
484 * @see java.lang.reflect.Modifier
487 public native int getModifiers();
491 * Returns the simple name of the underlying class as given in the
492 * source code. Returns an empty string if the underlying class is
495 * <p>The simple name of an array is the simple name of the
496 * component type with "[]" appended. In particular the simple
497 * name of an array whose component type is anonymous is "[]".
499 * @return the simple name of the underlying class
502 public String getSimpleName() {
504 return getComponentType().getSimpleName()+"[]";
506 String simpleName = getSimpleBinaryName();
507 if (simpleName == null) { // top level class
508 simpleName = getName();
509 return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
511 // According to JLS3 "Binary Compatibility" (13.1) the binary
512 // name of non-package classes (not top level) is the binary
513 // name of the immediately enclosing class followed by a '$' followed by:
514 // (for nested and inner classes): the simple name.
515 // (for local classes): 1 or more digits followed by the simple name.
516 // (for anonymous classes): 1 or more digits.
518 // Since getSimpleBinaryName() will strip the binary name of
519 // the immediatly enclosing class, we are now looking at a
520 // string that matches the regular expression "\$[0-9]*"
521 // followed by a simple name (considering the simple of an
522 // anonymous class to be the empty string).
524 // Remove leading "\$[0-9]*" from the name
525 int length = simpleName.length();
526 if (length < 1 || simpleName.charAt(0) != '$')
527 throw new IllegalStateException("Malformed class name");
529 while (index < length && isAsciiDigit(simpleName.charAt(index)))
531 // Eventually, this is the empty string iff this is an anonymous class
532 return simpleName.substring(index);
536 * Returns the "simple binary name" of the underlying class, i.e.,
537 * the binary name without the leading enclosing class name.
538 * Returns {@code null} if the underlying class is a top level
541 private String getSimpleBinaryName() {
542 Class<?> enclosingClass = null; // XXX getEnclosingClass();
543 if (enclosingClass == null) // top level class
545 // Otherwise, strip the enclosing class' name
547 return getName().substring(enclosingClass.getName().length());
548 } catch (IndexOutOfBoundsException ex) {
549 throw new IllegalStateException("Malformed class name");
554 * Returns an array containing {@code Field} objects reflecting all
555 * the accessible public fields of the class or interface represented by
556 * this {@code Class} object. The elements in the array returned are
557 * not sorted and are not in any particular order. This method returns an
558 * array of length 0 if the class or interface has no accessible public
559 * fields, or if it represents an array class, a primitive type, or void.
561 * <p> Specifically, if this {@code Class} object represents a class,
562 * this method returns the public fields of this class and of all its
563 * superclasses. If this {@code Class} object represents an
564 * interface, this method returns the fields of this interface and of all
565 * its superinterfaces.
567 * <p> The implicit length field for array class is not reflected by this
568 * method. User code should use the methods of class {@code Array} to
571 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
573 * @return the array of {@code Field} objects representing the
575 * @exception SecurityException
576 * If a security manager, <i>s</i>, is present and any of the
577 * following conditions is met:
582 * {@link SecurityManager#checkMemberAccess
583 * s.checkMemberAccess(this, Member.PUBLIC)} denies
584 * access to the fields within this class
586 * <li> the caller's class loader is not the same as or an
587 * ancestor of the class loader for the current class and
588 * invocation of {@link SecurityManager#checkPackageAccess
589 * s.checkPackageAccess()} denies access to the package
596 public Field[] getFields() throws SecurityException {
597 throw new SecurityException();
601 * Returns an array containing {@code Method} objects reflecting all
602 * the public <em>member</em> methods of the class or interface represented
603 * by this {@code Class} object, including those declared by the class
604 * or interface and those inherited from superclasses and
605 * superinterfaces. Array classes return all the (public) member methods
606 * inherited from the {@code Object} class. The elements in the array
607 * returned are not sorted and are not in any particular order. This
608 * method returns an array of length 0 if this {@code Class} object
609 * represents a class or interface that has no public member methods, or if
610 * this {@code Class} object represents a primitive type or void.
612 * <p> The class initialization method {@code <clinit>} is not
613 * included in the returned array. If the class declares multiple public
614 * member methods with the same parameter types, they are all included in
615 * the returned array.
617 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
619 * @return the array of {@code Method} objects representing the
620 * public methods of this class
621 * @exception SecurityException
622 * If a security manager, <i>s</i>, is present and any of the
623 * following conditions is met:
628 * {@link SecurityManager#checkMemberAccess
629 * s.checkMemberAccess(this, Member.PUBLIC)} denies
630 * access to the methods within this class
632 * <li> the caller's class loader is not the same as or an
633 * ancestor of the class loader for the current class and
634 * invocation of {@link SecurityManager#checkPackageAccess
635 * s.checkPackageAccess()} denies access to the package
642 public Method[] getMethods() throws SecurityException {
643 return Method.findMethods(this);
647 * Returns a {@code Field} object that reflects the specified public
648 * member field of the class or interface represented by this
649 * {@code Class} object. The {@code name} parameter is a
650 * {@code String} specifying the simple name of the desired field.
652 * <p> The field to be reflected is determined by the algorithm that
653 * follows. Let C be the class represented by this object:
655 * <LI> If C declares a public field with the name specified, that is the
656 * field to be reflected.</LI>
657 * <LI> If no field was found in step 1 above, this algorithm is applied
658 * recursively to each direct superinterface of C. The direct
659 * superinterfaces are searched in the order they were declared.</LI>
660 * <LI> If no field was found in steps 1 and 2 above, and C has a
661 * superclass S, then this algorithm is invoked recursively upon S.
662 * If C has no superclass, then a {@code NoSuchFieldException}
666 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
668 * @param name the field name
669 * @return the {@code Field} object of this class specified by
671 * @exception NoSuchFieldException if a field with the specified name is
673 * @exception NullPointerException if {@code name} is {@code null}
674 * @exception SecurityException
675 * If a security manager, <i>s</i>, is present and any of the
676 * following conditions is met:
681 * {@link SecurityManager#checkMemberAccess
682 * s.checkMemberAccess(this, Member.PUBLIC)} denies
683 * access to the field
685 * <li> the caller's class loader is not the same as or an
686 * ancestor of the class loader for the current class and
687 * invocation of {@link SecurityManager#checkPackageAccess
688 * s.checkPackageAccess()} denies access to the package
695 public Field getField(String name)
696 throws SecurityException {
697 throw new SecurityException();
702 * Returns a {@code Method} object that reflects the specified public
703 * member method of the class or interface represented by this
704 * {@code Class} object. The {@code name} parameter is a
705 * {@code String} specifying the simple name of the desired method. The
706 * {@code parameterTypes} parameter is an array of {@code Class}
707 * objects that identify the method's formal parameter types, in declared
708 * order. If {@code parameterTypes} is {@code null}, it is
709 * treated as if it were an empty array.
711 * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
712 * {@code NoSuchMethodException} is raised. Otherwise, the method to
713 * be reflected is determined by the algorithm that follows. Let C be the
714 * class represented by this object:
716 * <LI> C is searched for any <I>matching methods</I>. If no matching
717 * method is found, the algorithm of step 1 is invoked recursively on
718 * the superclass of C.</LI>
719 * <LI> If no method was found in step 1 above, the superinterfaces of C
720 * are searched for a matching method. If any such method is found, it
724 * To find a matching method in a class C: If C declares exactly one
725 * public method with the specified name and exactly the same formal
726 * parameter types, that is the method reflected. If more than one such
727 * method is found in C, and one of these methods has a return type that is
728 * more specific than any of the others, that method is reflected;
729 * otherwise one of the methods is chosen arbitrarily.
731 * <p>Note that there may be more than one matching method in a
732 * class because while the Java language forbids a class to
733 * declare multiple methods with the same signature but different
734 * return types, the Java virtual machine does not. This
735 * increased flexibility in the virtual machine can be used to
736 * implement various language features. For example, covariant
737 * returns can be implemented with {@linkplain
738 * java.lang.reflect.Method#isBridge bridge methods}; the bridge
739 * method and the method being overridden would have the same
740 * signature but different return types.
742 * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
744 * @param name the name of the method
745 * @param parameterTypes the list of parameters
746 * @return the {@code Method} object that matches the specified
747 * {@code name} and {@code parameterTypes}
748 * @exception NoSuchMethodException if a matching method is not found
749 * or if the name is "<init>"or "<clinit>".
750 * @exception NullPointerException if {@code name} is {@code null}
751 * @exception SecurityException
752 * If a security manager, <i>s</i>, is present and any of the
753 * following conditions is met:
758 * {@link SecurityManager#checkMemberAccess
759 * s.checkMemberAccess(this, Member.PUBLIC)} denies
760 * access to the method
762 * <li> the caller's class loader is not the same as or an
763 * ancestor of the class loader for the current class and
764 * invocation of {@link SecurityManager#checkPackageAccess
765 * s.checkPackageAccess()} denies access to the package
772 public Method getMethod(String name, Class<?>... parameterTypes)
773 throws SecurityException {
774 Method m = Method.findMethod(this, name, parameterTypes);
776 throw new SecurityException(); // XXX: NoSuchMethodException
782 * Character.isDigit answers {@code true} to some non-ascii
783 * digits. This one does not.
785 private static boolean isAsciiDigit(char c) {
786 return '0' <= c && c <= '9';
790 * Returns the canonical name of the underlying class as
791 * defined by the Java Language Specification. Returns null if
792 * the underlying class does not have a canonical name (i.e., if
793 * it is a local or anonymous class or an array whose component
794 * type does not have a canonical name).
795 * @return the canonical name of the underlying class if it exists, and
796 * {@code null} otherwise.
799 public String getCanonicalName() {
801 String canonicalName = getComponentType().getCanonicalName();
802 if (canonicalName != null)
803 return canonicalName + "[]";
807 // if (isLocalOrAnonymousClass())
809 // Class<?> enclosingClass = getEnclosingClass();
810 Class<?> enclosingClass = null;
811 if (enclosingClass == null) { // top level class
814 String enclosingName = enclosingClass.getCanonicalName();
815 if (enclosingName == null)
817 return enclosingName + "." + getSimpleName();
822 * Finds a resource with a given name. The rules for searching resources
823 * associated with a given class are implemented by the defining
824 * {@linkplain ClassLoader class loader} of the class. This method
825 * delegates to this object's class loader. If this object was loaded by
826 * the bootstrap class loader, the method delegates to {@link
827 * ClassLoader#getSystemResourceAsStream}.
829 * <p> Before delegation, an absolute resource name is constructed from the
830 * given resource name using this algorithm:
834 * <li> If the {@code name} begins with a {@code '/'}
835 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
836 * portion of the {@code name} following the {@code '/'}.
838 * <li> Otherwise, the absolute name is of the following form:
841 * {@code modified_package_name/name}
844 * <p> Where the {@code modified_package_name} is the package name of this
845 * object with {@code '/'} substituted for {@code '.'}
846 * (<tt>'\u002e'</tt>).
850 * @param name name of the desired resource
851 * @return A {@link java.io.InputStream} object or {@code null} if
852 * no resource with this name is found
853 * @throws NullPointerException If {@code name} is {@code null}
856 public InputStream getResourceAsStream(String name) {
857 name = resolveName(name);
858 ClassLoader cl = getClassLoader0();
861 return ClassLoader.getSystemResourceAsStream(name);
863 return cl.getResourceAsStream(name);
867 * Finds a resource with a given name. The rules for searching resources
868 * associated with a given class are implemented by the defining
869 * {@linkplain ClassLoader class loader} of the class. This method
870 * delegates to this object's class loader. If this object was loaded by
871 * the bootstrap class loader, the method delegates to {@link
872 * ClassLoader#getSystemResource}.
874 * <p> Before delegation, an absolute resource name is constructed from the
875 * given resource name using this algorithm:
879 * <li> If the {@code name} begins with a {@code '/'}
880 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
881 * portion of the {@code name} following the {@code '/'}.
883 * <li> Otherwise, the absolute name is of the following form:
886 * {@code modified_package_name/name}
889 * <p> Where the {@code modified_package_name} is the package name of this
890 * object with {@code '/'} substituted for {@code '.'}
891 * (<tt>'\u002e'</tt>).
895 * @param name name of the desired resource
896 * @return A {@link java.net.URL} object or {@code null} if no
897 * resource with this name is found
900 public java.net.URL getResource(String name) {
901 name = resolveName(name);
902 ClassLoader cl = getClassLoader0();
905 return ClassLoader.getSystemResource(name);
907 return cl.getResource(name);
912 * Add a package name prefix if the name is not absolute Remove leading "/"
913 * if name is absolute
915 private String resolveName(String name) {
919 if (!name.startsWith("/")) {
921 while (c.isArray()) {
922 c = c.getComponentType();
924 String baseName = c.getName();
925 int index = baseName.lastIndexOf('.');
927 name = baseName.substring(0, index).replace('.', '/')
931 name = name.substring(1);
937 * Returns the class loader for the class. Some implementations may use
938 * null to represent the bootstrap class loader. This method will return
939 * null in such implementations if this class was loaded by the bootstrap
942 * <p> If a security manager is present, and the caller's class loader is
943 * not null and the caller's class loader is not the same as or an ancestor of
944 * the class loader for the class whose class loader is requested, then
945 * this method calls the security manager's {@code checkPermission}
946 * method with a {@code RuntimePermission("getClassLoader")}
947 * permission to ensure it's ok to access the class loader for the class.
950 * represents a primitive type or void, null is returned.
952 * @return the class loader that loaded the class or interface
953 * represented by this object.
954 * @throws SecurityException
955 * if a security manager exists and its
956 * {@code checkPermission} method denies
957 * access to the class loader for the class.
958 * @see java.lang.ClassLoader
959 * @see SecurityManager#checkPermission
960 * @see java.lang.RuntimePermission
962 public ClassLoader getClassLoader() {
963 throw new SecurityException();
966 // Package-private to allow ClassLoader access
967 native ClassLoader getClassLoader0();
970 * Returns the {@code Class} representing the component type of an
971 * array. If this class does not represent an array class this method
974 * @return the {@code Class} representing the component type of this
975 * class if this class is an array
976 * @see java.lang.reflect.Array
979 public Class<?> getComponentType() {
984 * Returns true if and only if this class was declared as an enum in the
987 * @return true if and only if this class was declared as an enum in the
991 public boolean isEnum() {
992 // An enum must both directly extend java.lang.Enum and have
993 // the ENUM bit set; classes for specialized enum constants
994 // don't do the former.
995 return (this.getModifiers() & ENUM) != 0 &&
996 this.getSuperclass() == java.lang.Enum.class;
1000 * Casts an object to the class or interface represented
1001 * by this {@code Class} object.
1003 * @param obj the object to be cast
1004 * @return the object after casting, or null if obj is null
1006 * @throws ClassCastException if the object is not
1007 * null and is not assignable to the type T.
1011 public T cast(Object obj) {
1012 if (obj != null && !isInstance(obj))
1013 throw new ClassCastException(cannotCastMsg(obj));
1017 private String cannotCastMsg(Object obj) {
1018 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
1022 * Casts this {@code Class} object to represent a subclass of the class
1023 * represented by the specified class object. Checks that that the cast
1024 * is valid, and throws a {@code ClassCastException} if it is not. If
1025 * this method succeeds, it always returns a reference to this class object.
1027 * <p>This method is useful when a client needs to "narrow" the type of
1028 * a {@code Class} object to pass it to an API that restricts the
1029 * {@code Class} objects that it is willing to accept. A cast would
1030 * generate a compile-time warning, as the correctness of the cast
1031 * could not be checked at runtime (because generic types are implemented
1034 * @return this {@code Class} object, cast to represent a subclass of
1035 * the specified class object.
1036 * @throws ClassCastException if this {@code Class} object does not
1037 * represent a subclass of the specified class (here "subclass" includes
1038 * the class itself).
1041 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
1042 if (clazz.isAssignableFrom(this))
1043 return (Class<? extends U>) this;
1045 throw new ClassCastException(this.toString());
1048 @JavaScriptBody(args = { "self", "ac" },
1051 + " return self.anno['L' + ac.jvmName + ';'];"
1052 + "} else return null;"
1054 private Object getAnnotationData(Class<?> annotationClass) {
1055 throw new UnsupportedOperationException();
1058 * @throws NullPointerException {@inheritDoc}
1061 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
1062 Object data = getAnnotationData(annotationClass);
1063 return data == null ? null : AnnotationImpl.create(annotationClass, data);
1067 * @throws NullPointerException {@inheritDoc}
1070 @JavaScriptBody(args = { "self", "ac" },
1071 body = "if (self.anno && self.anno['L' + ac.jvmName + ';']) { return true; }"
1072 + "else return false;"
1074 public boolean isAnnotationPresent(
1075 Class<? extends Annotation> annotationClass) {
1076 if (annotationClass == null)
1077 throw new NullPointerException();
1079 return getAnnotation(annotationClass) != null;
1082 @JavaScriptBody(args = "self", body = "return self.anno;")
1083 private Object getAnnotationData() {
1084 throw new UnsupportedOperationException();
1090 public Annotation[] getAnnotations() {
1091 Object data = getAnnotationData();
1092 return data == null ? new Annotation[0] : AnnotationImpl.create(data);
1098 public Annotation[] getDeclaredAnnotations() {
1099 throw new UnsupportedOperationException();
1102 @JavaScriptBody(args = "type", body = ""
1103 + "var c = vm.java_lang_Class(true);"
1104 + "c.jvmName = type;"
1105 + "c.primitive = true;"
1108 native static Class getPrimitiveClass(String type);
1110 public boolean desiredAssertionStatus() {