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.lang.annotation.Annotation;
31 * Instances of the class {@code Class} represent classes and
32 * interfaces in a running Java application. An enum is a kind of
33 * class and an annotation is a kind of interface. Every array also
34 * belongs to a class that is reflected as a {@code Class} object
35 * that is shared by all arrays with the same element type and number
36 * of dimensions. The primitive Java types ({@code boolean},
37 * {@code byte}, {@code char}, {@code short},
38 * {@code int}, {@code long}, {@code float}, and
39 * {@code double}), and the keyword {@code void} are also
40 * represented as {@code Class} objects.
42 * <p> {@code Class} has no public constructor. Instead {@code Class}
43 * objects are constructed automatically by the Java Virtual Machine as classes
44 * are loaded and by calls to the {@code defineClass} method in the class
47 * <p> The following example uses a {@code Class} object to print the
48 * class name of an object:
50 * <p> <blockquote><pre>
51 * void printClassName(Object obj) {
52 * System.out.println("The class of " + obj +
53 * " is " + obj.getClass().getName());
57 * <p> It is also possible to get the {@code Class} object for a named
58 * type (or for void) using a class literal. See Section 15.8.2 of
59 * <cite>The Java™ Language Specification</cite>.
63 * {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
66 * @param <T> the type of the class modeled by this {@code Class}
67 * object. For example, the type of {@code String.class} is {@code
68 * Class<String>}. Use {@code Class<?>} if the class being modeled is
72 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
76 class Class<T> implements java.io.Serializable {
77 // java.lang.reflect.GenericDeclaration,
78 // java.lang.reflect.Type,
79 // java.lang.reflect.AnnotatedElement {
80 private static final int ANNOTATION= 0x00002000;
81 private static final int ENUM = 0x00004000;
82 private static final int SYNTHETIC = 0x00001000;
85 * Constructor. Only the Java Virtual Machine creates Class
92 * Converts the object to a string. The string representation is the
93 * string "class" or "interface", followed by a space, and then by the
94 * fully qualified name of the class in the format returned by
95 * {@code getName}. If this {@code Class} object represents a
96 * primitive type, this method returns the name of the primitive type. If
97 * this {@code Class} object represents void this method returns
100 * @return a string representation of this class object.
102 public String toString() {
103 return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
109 * Returns the {@code Class} object associated with the class or
110 * interface with the given string name. Invoking this method is
114 * {@code Class.forName(className, true, currentLoader)}
117 * where {@code currentLoader} denotes the defining class loader of
120 * <p> For example, the following code fragment returns the
121 * runtime {@code Class} descriptor for the class named
122 * {@code java.lang.Thread}:
125 * {@code Class t = Class.forName("java.lang.Thread")}
128 * A call to {@code forName("X")} causes the class named
129 * {@code X} to be initialized.
131 * @param className the fully qualified name of the desired class.
132 * @return the {@code Class} object for the class with the
134 * @exception LinkageError if the linkage fails
135 * @exception ExceptionInInitializerError if the initialization provoked
136 * by this method fails
137 * @exception ClassNotFoundException if the class cannot be located
139 public static Class<?> forName(String className)
140 throws ClassNotFoundException {
141 throw new UnsupportedOperationException();
146 * Creates a new instance of the class represented by this {@code Class}
147 * object. The class is instantiated as if by a {@code new}
148 * expression with an empty argument list. The class is initialized if it
149 * has not already been initialized.
151 * <p>Note that this method propagates any exception thrown by the
152 * nullary constructor, including a checked exception. Use of
153 * this method effectively bypasses the compile-time exception
154 * checking that would otherwise be performed by the compiler.
156 * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
157 * Constructor.newInstance} method avoids this problem by wrapping
158 * any exception thrown by the constructor in a (checked) {@link
159 * java.lang.reflect.InvocationTargetException}.
161 * @return a newly allocated instance of the class represented by this
163 * @exception IllegalAccessException if the class or its nullary
164 * constructor is not accessible.
165 * @exception InstantiationException
166 * if this {@code Class} represents an abstract class,
167 * an interface, an array class, a primitive type, or void;
168 * or if the class has no nullary constructor;
169 * or if the instantiation fails for some other reason.
170 * @exception ExceptionInInitializerError if the initialization
171 * provoked by this method fails.
172 * @exception SecurityException
173 * If a security manager, <i>s</i>, is present and any of the
174 * following conditions is met:
179 * {@link SecurityManager#checkMemberAccess
180 * s.checkMemberAccess(this, Member.PUBLIC)} denies
181 * creation of new instances of this class
183 * <li> the caller's class loader is not the same as or an
184 * ancestor of the class loader for the current class and
185 * invocation of {@link SecurityManager#checkPackageAccess
186 * s.checkPackageAccess()} denies access to the package
192 public T newInstance()
193 throws InstantiationException, IllegalAccessException
195 throw new UnsupportedOperationException("Should be somehow supported");
199 * Determines if the specified {@code Object} is assignment-compatible
200 * with the object represented by this {@code Class}. This method is
201 * the dynamic equivalent of the Java language {@code instanceof}
202 * operator. The method returns {@code true} if the specified
203 * {@code Object} argument is non-null and can be cast to the
204 * reference type represented by this {@code Class} object without
205 * raising a {@code ClassCastException.} It returns {@code false}
208 * <p> Specifically, if this {@code Class} object represents a
209 * declared class, this method returns {@code true} if the specified
210 * {@code Object} argument is an instance of the represented class (or
211 * of any of its subclasses); it returns {@code false} otherwise. If
212 * this {@code Class} object represents an array class, this method
213 * returns {@code true} if the specified {@code Object} argument
214 * can be converted to an object of the array class by an identity
215 * conversion or by a widening reference conversion; it returns
216 * {@code false} otherwise. If this {@code Class} object
217 * represents an interface, this method returns {@code true} if the
218 * class or any superclass of the specified {@code Object} argument
219 * implements this interface; it returns {@code false} otherwise. If
220 * this {@code Class} object represents a primitive type, this method
221 * returns {@code false}.
223 * @param obj the object to check
224 * @return true if {@code obj} is an instance of this class
228 public native boolean isInstance(Object obj);
232 * Determines if the class or interface represented by this
233 * {@code Class} object is either the same as, or is a superclass or
234 * superinterface of, the class or interface represented by the specified
235 * {@code Class} parameter. It returns {@code true} if so;
236 * otherwise it returns {@code false}. If this {@code Class}
237 * object represents a primitive type, this method returns
238 * {@code true} if the specified {@code Class} parameter is
239 * exactly this {@code Class} object; otherwise it returns
242 * <p> Specifically, this method tests whether the type represented by the
243 * specified {@code Class} parameter can be converted to the type
244 * represented by this {@code Class} object via an identity conversion
245 * or via a widening reference conversion. See <em>The Java Language
246 * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
248 * @param cls the {@code Class} object to be checked
249 * @return the {@code boolean} value indicating whether objects of the
250 * type {@code cls} can be assigned to objects of this class
251 * @exception NullPointerException if the specified Class parameter is
255 public native boolean isAssignableFrom(Class<?> cls);
259 * Determines if the specified {@code Class} object represents an
262 * @return {@code true} if this object represents an interface;
263 * {@code false} otherwise.
265 public native boolean isInterface();
269 * Determines if this {@code Class} object represents an array class.
271 * @return {@code true} if this object represents an array class;
272 * {@code false} otherwise.
275 public native boolean isArray();
279 * Determines if the specified {@code Class} object represents a
282 * <p> There are nine predefined {@code Class} objects to represent
283 * the eight primitive types and void. These are created by the Java
284 * Virtual Machine, and have the same names as the primitive types that
285 * they represent, namely {@code boolean}, {@code byte},
286 * {@code char}, {@code short}, {@code int},
287 * {@code long}, {@code float}, and {@code double}.
289 * <p> These objects may only be accessed via the following public static
290 * final variables, and are the only {@code Class} objects for which
291 * this method returns {@code true}.
293 * @return true if and only if this class represents a primitive type
295 * @see java.lang.Boolean#TYPE
296 * @see java.lang.Character#TYPE
297 * @see java.lang.Byte#TYPE
298 * @see java.lang.Short#TYPE
299 * @see java.lang.Integer#TYPE
300 * @see java.lang.Long#TYPE
301 * @see java.lang.Float#TYPE
302 * @see java.lang.Double#TYPE
303 * @see java.lang.Void#TYPE
306 public native boolean isPrimitive();
309 * Returns true if this {@code Class} object represents an annotation
310 * type. Note that if this method returns true, {@link #isInterface()}
311 * would also return true, as all annotation types are also interfaces.
313 * @return {@code true} if this class object represents an annotation
314 * type; {@code false} otherwise
317 public boolean isAnnotation() {
318 return (getModifiers() & ANNOTATION) != 0;
322 * Returns {@code true} if this class is a synthetic class;
323 * returns {@code false} otherwise.
324 * @return {@code true} if and only if this class is a synthetic class as
325 * defined by the Java Language Specification.
328 public boolean isSynthetic() {
329 return (getModifiers() & SYNTHETIC) != 0;
333 * Returns the name of the entity (class, interface, array class,
334 * primitive type, or void) represented by this {@code Class} object,
335 * as a {@code String}.
337 * <p> If this class object represents a reference type that is not an
338 * array type then the binary name of the class is returned, as specified
340 * <cite>The Java™ Language Specification</cite>.
342 * <p> If this class object represents a primitive type or void, then the
343 * name returned is a {@code String} equal to the Java language
344 * keyword corresponding to the primitive type or void.
346 * <p> If this class object represents a class of arrays, then the internal
347 * form of the name consists of the name of the element type preceded by
348 * one or more '{@code [}' characters representing the depth of the array
349 * nesting. The encoding of element type names is as follows:
351 * <blockquote><table summary="Element types and encodings">
352 * <tr><th> Element Type <th> <th> Encoding
353 * <tr><td> boolean <td> <td align=center> Z
354 * <tr><td> byte <td> <td align=center> B
355 * <tr><td> char <td> <td align=center> C
356 * <tr><td> class or interface
357 * <td> <td align=center> L<i>classname</i>;
358 * <tr><td> double <td> <td align=center> D
359 * <tr><td> float <td> <td align=center> F
360 * <tr><td> int <td> <td align=center> I
361 * <tr><td> long <td> <td align=center> J
362 * <tr><td> short <td> <td align=center> S
363 * </table></blockquote>
365 * <p> The class or interface name <i>classname</i> is the binary name of
366 * the class specified above.
370 * String.class.getName()
371 * returns "java.lang.String"
372 * byte.class.getName()
374 * (new Object[3]).getClass().getName()
375 * returns "[Ljava.lang.Object;"
376 * (new int[3][4][5][6][7][8][9]).getClass().getName()
378 * </pre></blockquote>
380 * @return the name of the class or interface
381 * represented by this object.
383 public String getName() {
384 throw new UnsupportedOperationException();
385 // String name = this.name;
387 // this.name = name = getName0();
392 * Returns the {@code Class} representing the superclass of the entity
393 * (class, interface, primitive type or void) represented by this
394 * {@code Class}. If this {@code Class} represents either the
395 * {@code Object} class, an interface, a primitive type, or void, then
396 * null is returned. If this object represents an array class then the
397 * {@code Class} object representing the {@code Object} class is
400 * @return the superclass of the class represented by this object.
402 public native Class<? super T> getSuperclass();
405 * Returns the Java language modifiers for this class or interface, encoded
406 * in an integer. The modifiers consist of the Java Virtual Machine's
407 * constants for {@code public}, {@code protected},
408 * {@code private}, {@code final}, {@code static},
409 * {@code abstract} and {@code interface}; they should be decoded
410 * using the methods of class {@code Modifier}.
412 * <p> If the underlying class is an array class, then its
413 * {@code public}, {@code private} and {@code protected}
414 * modifiers are the same as those of its component type. If this
415 * {@code Class} represents a primitive type or void, its
416 * {@code public} modifier is always {@code true}, and its
417 * {@code protected} and {@code private} modifiers are always
418 * {@code false}. If this object represents an array class, a
419 * primitive type or void, then its {@code final} modifier is always
420 * {@code true} and its interface modifier is always
421 * {@code false}. The values of its other modifiers are not determined
422 * by this specification.
424 * <p> The modifier encodings are defined in <em>The Java Virtual Machine
425 * Specification</em>, table 4.1.
427 * @return the {@code int} representing the modifiers for this class
428 * @see java.lang.reflect.Modifier
431 public native int getModifiers();
435 * Returns the simple name of the underlying class as given in the
436 * source code. Returns an empty string if the underlying class is
439 * <p>The simple name of an array is the simple name of the
440 * component type with "[]" appended. In particular the simple
441 * name of an array whose component type is anonymous is "[]".
443 * @return the simple name of the underlying class
446 public String getSimpleName() {
447 throw new UnsupportedOperationException();
449 //// return getComponentType().getSimpleName()+"[]";
451 //// String simpleName = getSimpleBinaryName();
452 //// if (simpleName == null) { // top level class
453 //// simpleName = getName();
454 //// return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
456 //// // According to JLS3 "Binary Compatibility" (13.1) the binary
457 //// // name of non-package classes (not top level) is the binary
458 //// // name of the immediately enclosing class followed by a '$' followed by:
459 //// // (for nested and inner classes): the simple name.
460 //// // (for local classes): 1 or more digits followed by the simple name.
461 //// // (for anonymous classes): 1 or more digits.
463 //// // Since getSimpleBinaryName() will strip the binary name of
464 //// // the immediatly enclosing class, we are now looking at a
465 //// // string that matches the regular expression "\$[0-9]*"
466 //// // followed by a simple name (considering the simple of an
467 //// // anonymous class to be the empty string).
469 //// // Remove leading "\$[0-9]*" from the name
470 //// int length = simpleName.length();
471 //// if (length < 1 || simpleName.charAt(0) != '$')
472 //// throw new InternalError("Malformed class name");
474 //// while (index < length && isAsciiDigit(simpleName.charAt(index)))
476 //// // Eventually, this is the empty string iff this is an anonymous class
477 //// return simpleName.substring(index);
481 * Character.isDigit answers {@code true} to some non-ascii
482 * digits. This one does not.
484 private static boolean isAsciiDigit(char c) {
485 return '0' <= c && c <= '9';
489 * Returns the canonical name of the underlying class as
490 * defined by the Java Language Specification. Returns null if
491 * the underlying class does not have a canonical name (i.e., if
492 * it is a local or anonymous class or an array whose component
493 * type does not have a canonical name).
494 * @return the canonical name of the underlying class if it exists, and
495 * {@code null} otherwise.
498 public String getCanonicalName() {
499 throw new UnsupportedOperationException();
501 // String canonicalName = getComponentType().getCanonicalName();
502 // if (canonicalName != null)
503 // return canonicalName + "[]";
507 // if (isLocalOrAnonymousClass())
509 // Class<?> enclosingClass = getEnclosingClass();
510 // if (enclosingClass == null) { // top level class
513 // String enclosingName = enclosingClass.getCanonicalName();
514 // if (enclosingName == null)
516 // return enclosingName + "." + getSimpleName();
521 * Finds a resource with a given name. The rules for searching resources
522 * associated with a given class are implemented by the defining
523 * {@linkplain ClassLoader class loader} of the class. This method
524 * delegates to this object's class loader. If this object was loaded by
525 * the bootstrap class loader, the method delegates to {@link
526 * ClassLoader#getSystemResourceAsStream}.
528 * <p> Before delegation, an absolute resource name is constructed from the
529 * given resource name using this algorithm:
533 * <li> If the {@code name} begins with a {@code '/'}
534 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
535 * portion of the {@code name} following the {@code '/'}.
537 * <li> Otherwise, the absolute name is of the following form:
540 * {@code modified_package_name/name}
543 * <p> Where the {@code modified_package_name} is the package name of this
544 * object with {@code '/'} substituted for {@code '.'}
545 * (<tt>'\u002e'</tt>).
549 * @param name name of the desired resource
550 * @return A {@link java.io.InputStream} object or {@code null} if
551 * no resource with this name is found
552 * @throws NullPointerException If {@code name} is {@code null}
555 // public InputStream getResourceAsStream(String name) {
556 // name = resolveName(name);
557 // ClassLoader cl = getClassLoader0();
559 // // A system class.
560 // return ClassLoader.getSystemResourceAsStream(name);
562 // return cl.getResourceAsStream(name);
566 * Finds a resource with a given name. The rules for searching resources
567 * associated with a given class are implemented by the defining
568 * {@linkplain ClassLoader class loader} of the class. This method
569 * delegates to this object's class loader. If this object was loaded by
570 * the bootstrap class loader, the method delegates to {@link
571 * ClassLoader#getSystemResource}.
573 * <p> Before delegation, an absolute resource name is constructed from the
574 * given resource name using this algorithm:
578 * <li> If the {@code name} begins with a {@code '/'}
579 * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
580 * portion of the {@code name} following the {@code '/'}.
582 * <li> Otherwise, the absolute name is of the following form:
585 * {@code modified_package_name/name}
588 * <p> Where the {@code modified_package_name} is the package name of this
589 * object with {@code '/'} substituted for {@code '.'}
590 * (<tt>'\u002e'</tt>).
594 * @param name name of the desired resource
595 * @return A {@link java.net.URL} object or {@code null} if no
596 * resource with this name is found
599 // public java.net.URL getResource(String name) {
600 // name = resolveName(name);
601 // ClassLoader cl = getClassLoader0();
603 // // A system class.
604 // return ClassLoader.getSystemResource(name);
606 // return cl.getResource(name);
613 * Returns true if and only if this class was declared as an enum in the
616 * @return true if and only if this class was declared as an enum in the
620 public boolean isEnum() {
621 // An enum must both directly extend java.lang.Enum and have
622 // the ENUM bit set; classes for specialized enum constants
623 // don't do the former.
624 return (this.getModifiers() & ENUM) != 0 &&
625 this.getSuperclass() == java.lang.Enum.class;
629 * Casts an object to the class or interface represented
630 * by this {@code Class} object.
632 * @param obj the object to be cast
633 * @return the object after casting, or null if obj is null
635 * @throws ClassCastException if the object is not
636 * null and is not assignable to the type T.
640 public T cast(Object obj) {
641 if (obj != null && !isInstance(obj))
642 throw new ClassCastException(cannotCastMsg(obj));
646 private String cannotCastMsg(Object obj) {
647 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
651 * Casts this {@code Class} object to represent a subclass of the class
652 * represented by the specified class object. Checks that that the cast
653 * is valid, and throws a {@code ClassCastException} if it is not. If
654 * this method succeeds, it always returns a reference to this class object.
656 * <p>This method is useful when a client needs to "narrow" the type of
657 * a {@code Class} object to pass it to an API that restricts the
658 * {@code Class} objects that it is willing to accept. A cast would
659 * generate a compile-time warning, as the correctness of the cast
660 * could not be checked at runtime (because generic types are implemented
663 * @return this {@code Class} object, cast to represent a subclass of
664 * the specified class object.
665 * @throws ClassCastException if this {@code Class} object does not
666 * represent a subclass of the specified class (here "subclass" includes
670 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
671 if (clazz.isAssignableFrom(this))
672 return (Class<? extends U>) this;
674 throw new ClassCastException(this.toString());
678 * @throws NullPointerException {@inheritDoc}
681 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
682 throw new UnsupportedOperationException();
686 * @throws NullPointerException {@inheritDoc}
689 public boolean isAnnotationPresent(
690 Class<? extends Annotation> annotationClass) {
691 if (annotationClass == null)
692 throw new NullPointerException();
694 return getAnnotation(annotationClass) != null;
701 public Annotation[] getAnnotations() {
702 throw new UnsupportedOperationException();
708 public Annotation[] getDeclaredAnnotations() {
709 throw new UnsupportedOperationException();
712 static Class getPrimitiveClass(String type) {
717 public boolean desiredAssertionStatus() {