< prev index next >

src/java.base/share/classes/java/lang/Class.java

Print this page

 182  * A hidden class or interface is never an array class, but may be
 183  * the element type of an array. In all other respects, the fact that
 184  * a class or interface is hidden has no bearing on the characteristics
 185  * exposed by the methods of class {@code Class}.
 186  *
 187  * @param <T> the type of the class modeled by this {@code Class}
 188  * object.  For example, the type of {@code String.class} is {@code
 189  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
 190  * unknown.
 191  *
 192  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
 193  * @since   1.0
 194  * @jls 15.8.2 Class Literals
 195  */
 196 public final class Class<T> implements java.io.Serializable,
 197                               GenericDeclaration,
 198                               Type,
 199                               AnnotatedElement,
 200                               TypeDescriptor.OfField<Class<?>>,
 201                               Constable {
 202     private static final int ANNOTATION= 0x00002000;
 203     private static final int ENUM      = 0x00004000;
 204     private static final int SYNTHETIC = 0x00001000;



 205 
 206     private static native void registerNatives();
 207     static {
 208         registerNatives();
 209     }
 210 
 211     /*
 212      * Private constructor. Only the Java Virtual Machine creates Class objects.
 213      * This constructor is not used and prevents the default constructor being
 214      * generated.
 215      */
 216     private Class(ClassLoader loader, Class<?> arrayComponentType) {
 217         // Initialize final field for classLoader.  The initialization value of non-null
 218         // prevents future JIT optimizations from assuming this final field is null.
 219         classLoader = loader;
 220         componentType = arrayComponentType;
 221     }
 222 
 223     /**
 224      * Converts the object to a string. The string representation is the
 225      * string "class" or "interface", followed by a space, and then by the
 226      * name of the class in the format returned by {@code getName}.
 227      * If this {@code Class} object represents a primitive type,
 228      * this method returns the name of the primitive type.  If
 229      * this {@code Class} object represents void this method returns
 230      * "void". If this {@code Class} object represents an array type,
 231      * this method returns "class " followed by {@code getName}.
 232      *
 233      * @return a string representation of this {@code Class} object.
 234      */
 235     public String toString() {
 236         String kind = isInterface() ? "interface " : isPrimitive() ? "" : "class ";
 237         return kind.concat(getName());














 238     }
 239 
 240     /**
 241      * Returns a string describing this {@code Class}, including
 242      * information about modifiers and type parameters.
 243      *
 244      * The string is formatted as a list of type modifiers, if any,
 245      * followed by the kind of type (empty string for primitive types
 246      * and {@code class}, {@code enum}, {@code interface},
 247      * {@code @interface}, or {@code record} as appropriate), followed
 248      * by the type's name, followed by an angle-bracketed
 249      * comma-separated list of the type's type parameters, if any,
 250      * including informative bounds on the type parameters, if any.
 251      *
 252      * A space is used to separate modifiers from one another and to
 253      * separate any modifiers from the kind of type. The modifiers
 254      * occur in canonical order. If there are no type parameters, the
 255      * type parameter list is elided.
 256      *
 257      * For an array type, the string starts with the type name,

 278             Class<?> component = this;
 279             int arrayDepth = 0;
 280 
 281             if (isArray()) {
 282                 do {
 283                     arrayDepth++;
 284                     component = component.getComponentType();
 285                 } while (component.isArray());
 286                 sb.append(component.getName());
 287             } else {
 288                 // Class modifiers are a superset of interface modifiers
 289                 int modifiers = getModifiers() & Modifier.classModifiers();
 290                 if (modifiers != 0) {
 291                     sb.append(Modifier.toString(modifiers));
 292                     sb.append(' ');
 293                 }
 294 
 295                 if (isAnnotation()) {
 296                     sb.append('@');
 297                 }



 298                 if (isInterface()) { // Note: all annotation interfaces are interfaces
 299                     sb.append("interface");
 300                 } else {
 301                     if (isEnum())
 302                         sb.append("enum");
 303                     else if (isRecord())
 304                         sb.append("record");
 305                     else
 306                         sb.append("class");
 307                 }
 308                 sb.append(' ');
 309                 sb.append(getName());
 310             }
 311 
 312             TypeVariable<?>[] typeparms = component.getTypeParameters();
 313             if (typeparms.length > 0) {
 314                 sb.append(Arrays.stream(typeparms)
 315                           .map(Class::typeVarBounds)
 316                           .collect(Collectors.joining(",", "<", ">")));
 317             }

 473             throws ClassNotFoundException
 474     {
 475         @SuppressWarnings("removal")
 476         SecurityManager sm = System.getSecurityManager();
 477         if (sm != null) {
 478             // Reflective call to get caller class is only needed if a security manager
 479             // is present.  Avoid the overhead of making this call otherwise.
 480             if (loader == null) {
 481                 ClassLoader ccl = ClassLoader.getClassLoader(caller);
 482                 if (ccl != null) {
 483                     sm.checkPermission(
 484                             SecurityConstants.GET_CLASSLOADER_PERMISSION);
 485                 }
 486             }
 487         }
 488         return forName0(name, initialize, loader, caller);
 489     }
 490 
 491     /** Called after security check for system loader access checks have been made. */
 492     private static native Class<?> forName0(String name, boolean initialize,
 493                                             ClassLoader loader,
 494                                             Class<?> caller)
 495         throws ClassNotFoundException;
 496 
 497 
 498     /**
 499      * Returns the {@code Class} with the given <a href="ClassLoader.html#binary-name">
 500      * binary name</a> in the given module.
 501      *
 502      * <p> This method attempts to locate and load the class or interface.
 503      * It does not link the class, and does not run the class initializer.
 504      * If the class is not found, this method returns {@code null}. </p>
 505      *
 506      * <p> If the class loader of the given module defines other modules and
 507      * the given name is a class defined in a different module, this method
 508      * returns {@code null} after the class is loaded. </p>
 509      *
 510      * <p> This method does not check whether the requested class is
 511      * accessible to its caller. </p>
 512      *
 513      * @apiNote
 514      * This method returns {@code null} on failure rather than

 563         SecurityManager sm = System.getSecurityManager();
 564         if (sm != null) {
 565             if (caller != null && caller.getModule() != module) {
 566                 // if caller is null, Class.forName is the last java frame on the stack.
 567                 // java.base has all permissions
 568                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 569             }
 570             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
 571             cl = AccessController.doPrivileged(pa);
 572         } else {
 573             cl = module.getClassLoader();
 574         }
 575 
 576         if (cl != null) {
 577             return cl.loadClass(module, name);
 578         } else {
 579             return BootLoader.loadClass(module, name);
 580         }
 581     }
 582 

























































































































 583     /**
 584      * Creates a new instance of the class represented by this {@code Class}
 585      * object.  The class is instantiated as if by a {@code new}
 586      * expression with an empty argument list.  The class is initialized if it
 587      * has not already been initialized.
 588      *
 589      * @deprecated This method propagates any exception thrown by the
 590      * nullary constructor, including a checked exception.  Use of
 591      * this method effectively bypasses the compile-time exception
 592      * checking that would otherwise be performed by the compiler.
 593      * The {@link
 594      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
 595      * Constructor.newInstance} method avoids this problem by wrapping
 596      * any exception thrown by the constructor in a (checked) {@link
 597      * java.lang.reflect.InvocationTargetException}.
 598      *
 599      * <p>The call
 600      *
 601      * <pre>{@code
 602      * clazz.newInstance()

 707      * class or any superclass of the specified {@code Object} argument
 708      * implements this interface; it returns {@code false} otherwise. If
 709      * this {@code Class} object represents a primitive type, this method
 710      * returns {@code false}.
 711      *
 712      * @param   obj the object to check
 713      * @return  true if {@code obj} is an instance of this class
 714      *
 715      * @since 1.1
 716      */
 717     @IntrinsicCandidate
 718     public native boolean isInstance(Object obj);
 719 
 720 
 721     /**
 722      * Determines if the class or interface represented by this
 723      * {@code Class} object is either the same as, or is a superclass or
 724      * superinterface of, the class or interface represented by the specified
 725      * {@code Class} parameter. It returns {@code true} if so;
 726      * otherwise it returns {@code false}. If this {@code Class}




 727      * object represents a primitive type, this method returns
 728      * {@code true} if the specified {@code Class} parameter is
 729      * exactly this {@code Class} object; otherwise it returns
 730      * {@code false}.
 731      *
 732      * <p> Specifically, this method tests whether the type represented by the
 733      * specified {@code Class} parameter can be converted to the type
 734      * represented by this {@code Class} object via an identity conversion
 735      * or via a widening reference conversion. See <cite>The Java Language
 736      * Specification</cite>, sections {@jls 5.1.1} and {@jls 5.1.4},
 737      * for details.
 738      *
 739      * @param     cls the {@code Class} object to be checked
 740      * @return    the {@code boolean} value indicating whether objects of the
 741      *            type {@code cls} can be assigned to objects of this class
 742      * @throws    NullPointerException if the specified Class parameter is
 743      *            null.
 744      * @since     1.1
 745      */
 746     @IntrinsicCandidate
 747     public native boolean isAssignableFrom(Class<?> cls);
 748 
 749 
 750     /**
 751      * Determines if this {@code Class} object represents an
 752      * interface type.
 753      *
 754      * @return  {@code true} if this {@code Class} object represents an interface;
 755      *          {@code false} otherwise.
 756      */
 757     @IntrinsicCandidate

 845      *      {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
 846      *      Lookup::defineHiddenClass}, and {@code <suffix>} is an unqualified name.
 847      * </ul>
 848      *
 849      * <p> If this {@code Class} object represents an array class, then
 850      * the result is a string consisting of one or more '{@code [}' characters
 851      * representing the depth of the array nesting, followed by the element
 852      * type as encoded using the following table:
 853      *
 854      * <blockquote><table class="striped">
 855      * <caption style="display:none">Element types and encodings</caption>
 856      * <thead>
 857      * <tr><th scope="col"> Element Type <th scope="col"> Encoding
 858      * </thead>
 859      * <tbody style="text-align:left">
 860      * <tr><th scope="row"> {@code boolean} <td style="text-align:center"> {@code Z}
 861      * <tr><th scope="row"> {@code byte}    <td style="text-align:center"> {@code B}
 862      * <tr><th scope="row"> {@code char}    <td style="text-align:center"> {@code C}
 863      * <tr><th scope="row"> class or interface with <a href="ClassLoader.html#binary-name">binary name</a> <i>N</i>
 864      *                                      <td style="text-align:center"> {@code L}<em>N</em>{@code ;}


 865      * <tr><th scope="row"> {@code double}  <td style="text-align:center"> {@code D}
 866      * <tr><th scope="row"> {@code float}   <td style="text-align:center"> {@code F}
 867      * <tr><th scope="row"> {@code int}     <td style="text-align:center"> {@code I}
 868      * <tr><th scope="row"> {@code long}    <td style="text-align:center"> {@code J}
 869      * <tr><th scope="row"> {@code short}   <td style="text-align:center"> {@code S}
 870      * </tbody>
 871      * </table></blockquote>
 872      *
 873      * <p> If this {@code Class} object represents a primitive type or {@code void},
 874      * then the result is a string with the same spelling as the Java language
 875      * keyword which corresponds to the primitive type or {@code void}.
 876      *
 877      * <p> Examples:
 878      * <blockquote><pre>
 879      * String.class.getName()
 880      *     returns "java.lang.String"
 881      * byte.class.getName()
 882      *     returns "byte"


 883      * (new Object[3]).getClass().getName()
 884      *     returns "[Ljava.lang.Object;"




 885      * (new int[3][4][5][6][7][8][9]).getClass().getName()
 886      *     returns "[[[[[[[I"
 887      * </pre></blockquote>
 888      *
 889      * @return  the name of the class, interface, or other entity
 890      *          represented by this {@code Class} object.
 891      * @jls 13.1 The Form of a Binary
 892      */
 893     public String getName() {
 894         String name = this.name;
 895         return name != null ? name : initClassName();
 896     }
 897 
 898     // Cache the name to reduce the number of calls into the VM.
 899     // This field would be set by VM itself during initClassName call.
 900     private transient String name;
 901     private native String initClassName();
 902 
 903     /**
 904      * Returns the class loader for the class.  Some implementations may use

1298      * primitive type or void, then its {@code final} modifier is always
1299      * {@code true} and its interface modifier is always
1300      * {@code false}. The values of its other modifiers are not determined
1301      * by this specification.
1302      *
1303      * <p> The modifier encodings are defined in section {@jvms 4.1}
1304      * of <cite>The Java Virtual Machine Specification</cite>.
1305      *
1306      * @return the {@code int} representing the modifiers for this class
1307      * @see     java.lang.reflect.Modifier
1308      * @see <a
1309      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1310      * programming language and JVM modeling in core reflection</a>
1311      * @since 1.1
1312      * @jls 8.1.1 Class Modifiers
1313      * @jls 9.1.1. Interface Modifiers
1314      */
1315     @IntrinsicCandidate
1316     public native int getModifiers();
1317 
1318 
1319     /**
1320      * Gets the signers of this class.
1321      *
1322      * @return  the signers of this class, or null if there are no signers.  In
1323      *          particular, this method returns null if this {@code Class} object represents
1324      *          a primitive type or void.
1325      * @since   1.1
1326      */
1327     public native Object[] getSigners();
1328 
1329 
1330     /**
1331      * Set the signers of this class.
1332      */
1333     native void setSigners(Object[] signers);
1334 
1335 
1336     /**
1337      * If this {@code Class} object represents a local or anonymous
1338      * class within a method, returns a {@link
1339      * java.lang.reflect.Method Method} object representing the
1340      * immediately enclosing method of the underlying class. Returns
1341      * {@code null} otherwise.
1342      *
1343      * In particular, this method returns {@code null} if the underlying
1344      * class is a local or anonymous class immediately enclosed by a class or
1345      * interface declaration, instance initializer or static initializer.
1346      *
1347      * @return the immediately enclosing method of the underlying class, if
1348      *     that class is a local or anonymous class; otherwise {@code null}.
1349      *

1697             simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1698         }
1699         return simpleName;
1700     }
1701 
1702     /**
1703      * Return an informative string for the name of this class or interface.
1704      *
1705      * @return an informative string for the name of this class or interface
1706      * @since 1.8
1707      */
1708     public String getTypeName() {
1709         if (isArray()) {
1710             try {
1711                 Class<?> cl = this;
1712                 int dimensions = 0;
1713                 do {
1714                     dimensions++;
1715                     cl = cl.getComponentType();
1716                 } while (cl.isArray());
1717                 return cl.getName().concat("[]".repeat(dimensions));
1718             } catch (Throwable e) { /*FALLTHRU*/ }
1719         }
1720         return getName();





1721     }
1722 
1723     /**
1724      * Returns the canonical name of the underlying class as
1725      * defined by <cite>The Java Language Specification</cite>.
1726      * Returns {@code null} if the underlying class does not have a canonical
1727      * name. Classes without canonical names include:
1728      * <ul>
1729      * <li>a {@linkplain #isLocalClass() local class}
1730      * <li>a {@linkplain #isAnonymousClass() anonymous class}
1731      * <li>a {@linkplain #isHidden() hidden class}
1732      * <li>an array whose component type does not have a canonical name</li>
1733      * </ul>
1734      *
1735      * The canonical name for a primitive class is the keyword for the
1736      * corresponding primitive type ({@code byte}, {@code short},
1737      * {@code char}, {@code int}, and so on).
1738      *
1739      * <p>An array type has a canonical name if and only if its
1740      * component type has a canonical name. When an array type has a

3911                 throw new IllegalArgumentException(
3912                     getName() + " is not an enum class");
3913             directory = new HashMap<>((int)(universe.length / 0.75f) + 1);
3914             for (T constant : universe) {
3915                 directory.put(((Enum<?>)constant).name(), constant);
3916             }
3917             enumConstantDirectory = directory;
3918         }
3919         return directory;
3920     }
3921     private transient volatile Map<String, T> enumConstantDirectory;
3922 
3923     /**
3924      * Casts an object to the class or interface represented
3925      * by this {@code Class} object.
3926      *
3927      * @param obj the object to be cast
3928      * @return the object after casting, or null if obj is null
3929      *
3930      * @throws ClassCastException if the object is not
3931      * null and is not assignable to the type T.


3932      *
3933      * @since 1.5
3934      */
3935     @SuppressWarnings("unchecked")
3936     @IntrinsicCandidate
3937     public T cast(Object obj) {



3938         if (obj != null && !isInstance(obj))
3939             throw new ClassCastException(cannotCastMsg(obj));
3940         return (T) obj;
3941     }
3942 
3943     private String cannotCastMsg(Object obj) {
3944         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3945     }
3946 
3947     /**
3948      * Casts this {@code Class} object to represent a subclass of the class
3949      * represented by the specified class object.  Checks that the cast
3950      * is valid, and throws a {@code ClassCastException} if it is not.  If
3951      * this method succeeds, it always returns a reference to this {@code Class} object.
3952      *
3953      * <p>This method is useful when a client needs to "narrow" the type of
3954      * a {@code Class} object to pass it to an API that restricts the
3955      * {@code Class} objects that it is willing to accept.  A cast would
3956      * generate a compile-time warning, as the correctness of the cast
3957      * could not be checked at runtime (because generic types are implemented

4213      *
4214      * <p> If this {@code Class} object represents an interface, the return
4215      * value is an array containing objects representing the uses of interface
4216      * types to specify interfaces directly extended by the interface. The
4217      * order of the objects in the array corresponds to the order of the
4218      * interface types used in the 'extends' clause of the declaration of this
4219      * {@code Class} object.
4220      *
4221      * <p> If this {@code Class} object represents a class or interface whose
4222      * declaration does not explicitly indicate any annotated superinterfaces,
4223      * the return value is an array of length 0.
4224      *
4225      * <p> If this {@code Class} object represents either the {@code Object}
4226      * class, an array type, a primitive type, or void, the return value is an
4227      * array of length 0.
4228      *
4229      * @return an array representing the superinterfaces
4230      * @since 1.8
4231      */
4232     public AnnotatedType[] getAnnotatedInterfaces() {
4233          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
4234     }
4235 
4236     private native Class<?> getNestHost0();
4237 
4238     /**
4239      * Returns the nest host of the <a href=#nest>nest</a> to which the class
4240      * or interface represented by this {@code Class} object belongs.
4241      * Every class and interface belongs to exactly one nest.
4242      *
4243      * If the nest host of this class or interface has previously
4244      * been determined, then this method returns the nest host.
4245      * If the nest host of this class or interface has
4246      * not previously been determined, then this method determines the nest
4247      * host using the algorithm of JVMS 5.4.4, and returns it.
4248      *
4249      * Often, a class or interface belongs to a nest consisting only of itself,
4250      * in which case this method returns {@code this} to indicate that the class
4251      * or interface is the nest host.
4252      *
4253      * <p>If this {@code Class} object represents a primitive type, an array type,

4428      * {@code void}, then the result is a field descriptor string which
4429      * is a one-letter code corresponding to a primitive type or {@code void}
4430      * ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}).
4431      *
4432      * @apiNote
4433      * This is not a strict inverse of {@link #forName};
4434      * distinct classes which share a common name but have different class loaders
4435      * will have identical descriptor strings.
4436      *
4437      * @return the descriptor string for this {@code Class} object
4438      * @jvms 4.3.2 Field Descriptors
4439      * @since 12
4440      */
4441     @Override
4442     public String descriptorString() {
4443         if (isPrimitive())
4444             return Wrapper.forPrimitiveType(this).basicTypeString();
4445 
4446         if (isArray()) {
4447             return "[" + componentType.descriptorString();
4448         } else if (isHidden()) {


4449             String name = getName();
4450             int index = name.indexOf('/');
4451             return new StringBuilder(name.length() + 2)
4452                     .append('L')
4453                     .append(name.substring(0, index).replace('.', '/'))
4454                     .append('.')
4455                     .append(name, index + 1, name.length())
4456                     .append(';')
4457                     .toString();
4458         } else {
4459             String name = getName().replace('.', '/');
4460             return new StringBuilder(name.length() + 2)
4461                     .append('L')
4462                     .append(name)
4463                     .append(';')
4464                     .toString();
4465         }
4466     }
4467 
4468     /**
4469      * Returns the component type of this {@code Class}, if it describes
4470      * an array type, or {@code null} otherwise.
4471      *
4472      * @implSpec
4473      * Equivalent to {@link Class#getComponentType()}.
4474      *
4475      * @return a {@code Class} describing the component type, or {@code null}
4476      * if this {@code Class} does not describe an array type
4477      * @since 12
4478      */
4479     @Override
4480     public Class<?> componentType() {
4481         return isArray() ? componentType : null;

 182  * A hidden class or interface is never an array class, but may be
 183  * the element type of an array. In all other respects, the fact that
 184  * a class or interface is hidden has no bearing on the characteristics
 185  * exposed by the methods of class {@code Class}.
 186  *
 187  * @param <T> the type of the class modeled by this {@code Class}
 188  * object.  For example, the type of {@code String.class} is {@code
 189  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
 190  * unknown.
 191  *
 192  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
 193  * @since   1.0
 194  * @jls 15.8.2 Class Literals
 195  */
 196 public final class Class<T> implements java.io.Serializable,
 197                               GenericDeclaration,
 198                               Type,
 199                               AnnotatedElement,
 200                               TypeDescriptor.OfField<Class<?>>,
 201                               Constable {
 202     private static final int ANNOTATION = 0x00002000;
 203     private static final int ENUM       = 0x00004000;
 204     private static final int SYNTHETIC  = 0x00001000;
 205     private static final int VALUE_CLASS     = 0x00000040;
 206     private static final int PERMITS_VALUE   = 0x00000100;
 207     private static final int PRIMITIVE_CLASS = 0x00000800;
 208 
 209     private static native void registerNatives();
 210     static {
 211         registerNatives();
 212     }
 213 
 214     /*
 215      * Private constructor. Only the Java Virtual Machine creates Class objects.
 216      * This constructor is not used and prevents the default constructor being
 217      * generated.
 218      */
 219     private Class(ClassLoader loader, Class<?> arrayComponentType) {
 220         // Initialize final field for classLoader.  The initialization value of non-null
 221         // prevents future JIT optimizations from assuming this final field is null.
 222         classLoader = loader;
 223         componentType = arrayComponentType;
 224     }
 225 
 226     /**
 227      * Converts the object to a string. The string representation is the
 228      * string "class" or "interface", followed by a space, and then by the
 229      * name of the class in the format returned by {@code getName}.
 230      * If this {@code Class} object represents a primitive type,
 231      * this method returns the name of the primitive type.  If
 232      * this {@code Class} object represents void this method returns
 233      * "void". If this {@code Class} object represents an array type,
 234      * this method returns "class " followed by {@code getName}.
 235      *
 236      * @return a string representation of this {@code Class} object.
 237      */
 238     public String toString() {
 239         String s = isPrimitive() ? "" : "class ";
 240         if (isInterface()) {
 241             s = "interface ";
 242         }
 243         if (isValue()) {
 244             s = "value ";
 245         }
 246         if (isPrimitiveClass()) {
 247             s = "primitive ";
 248         }
 249         // Avoid invokedynamic based String concat, might be not available
 250         s = s.concat(getName());
 251         if (isPrimitiveClass() && isPrimaryType()) {
 252             s = s.concat(".ref");
 253         }
 254         return s;
 255     }
 256 
 257     /**
 258      * Returns a string describing this {@code Class}, including
 259      * information about modifiers and type parameters.
 260      *
 261      * The string is formatted as a list of type modifiers, if any,
 262      * followed by the kind of type (empty string for primitive types
 263      * and {@code class}, {@code enum}, {@code interface},
 264      * {@code @interface}, or {@code record} as appropriate), followed
 265      * by the type's name, followed by an angle-bracketed
 266      * comma-separated list of the type's type parameters, if any,
 267      * including informative bounds on the type parameters, if any.
 268      *
 269      * A space is used to separate modifiers from one another and to
 270      * separate any modifiers from the kind of type. The modifiers
 271      * occur in canonical order. If there are no type parameters, the
 272      * type parameter list is elided.
 273      *
 274      * For an array type, the string starts with the type name,

 295             Class<?> component = this;
 296             int arrayDepth = 0;
 297 
 298             if (isArray()) {
 299                 do {
 300                     arrayDepth++;
 301                     component = component.getComponentType();
 302                 } while (component.isArray());
 303                 sb.append(component.getName());
 304             } else {
 305                 // Class modifiers are a superset of interface modifiers
 306                 int modifiers = getModifiers() & Modifier.classModifiers();
 307                 if (modifiers != 0) {
 308                     sb.append(Modifier.toString(modifiers));
 309                     sb.append(' ');
 310                 }
 311 
 312                 if (isAnnotation()) {
 313                     sb.append('@');
 314                 }
 315                 if (isValue()) {
 316                     sb.append(isPrimitiveClass() ? "primitive" : "value");
 317                 }
 318                 if (isInterface()) { // Note: all annotation interfaces are interfaces
 319                     sb.append("interface");
 320                 } else {
 321                     if (isEnum())
 322                         sb.append("enum");
 323                     else if (isRecord())
 324                         sb.append("record");
 325                     else
 326                         sb.append("class");
 327                 }
 328                 sb.append(' ');
 329                 sb.append(getName());
 330             }
 331 
 332             TypeVariable<?>[] typeparms = component.getTypeParameters();
 333             if (typeparms.length > 0) {
 334                 sb.append(Arrays.stream(typeparms)
 335                           .map(Class::typeVarBounds)
 336                           .collect(Collectors.joining(",", "<", ">")));
 337             }

 493             throws ClassNotFoundException
 494     {
 495         @SuppressWarnings("removal")
 496         SecurityManager sm = System.getSecurityManager();
 497         if (sm != null) {
 498             // Reflective call to get caller class is only needed if a security manager
 499             // is present.  Avoid the overhead of making this call otherwise.
 500             if (loader == null) {
 501                 ClassLoader ccl = ClassLoader.getClassLoader(caller);
 502                 if (ccl != null) {
 503                     sm.checkPermission(
 504                             SecurityConstants.GET_CLASSLOADER_PERMISSION);
 505                 }
 506             }
 507         }
 508         return forName0(name, initialize, loader, caller);
 509     }
 510 
 511     /** Called after security check for system loader access checks have been made. */
 512     private static native Class<?> forName0(String name, boolean initialize,
 513                                     ClassLoader loader,
 514                                     Class<?> caller)
 515         throws ClassNotFoundException;
 516 
 517 
 518     /**
 519      * Returns the {@code Class} with the given <a href="ClassLoader.html#binary-name">
 520      * binary name</a> in the given module.
 521      *
 522      * <p> This method attempts to locate and load the class or interface.
 523      * It does not link the class, and does not run the class initializer.
 524      * If the class is not found, this method returns {@code null}. </p>
 525      *
 526      * <p> If the class loader of the given module defines other modules and
 527      * the given name is a class defined in a different module, this method
 528      * returns {@code null} after the class is loaded. </p>
 529      *
 530      * <p> This method does not check whether the requested class is
 531      * accessible to its caller. </p>
 532      *
 533      * @apiNote
 534      * This method returns {@code null} on failure rather than

 583         SecurityManager sm = System.getSecurityManager();
 584         if (sm != null) {
 585             if (caller != null && caller.getModule() != module) {
 586                 // if caller is null, Class.forName is the last java frame on the stack.
 587                 // java.base has all permissions
 588                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 589             }
 590             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
 591             cl = AccessController.doPrivileged(pa);
 592         } else {
 593             cl = module.getClassLoader();
 594         }
 595 
 596         if (cl != null) {
 597             return cl.loadClass(module, name);
 598         } else {
 599             return BootLoader.loadClass(module, name);
 600         }
 601     }
 602 
 603     // set by VM if this class is an exotic type such as primitive class
 604     // otherwise, these two fields are null
 605     private transient Class<T> primaryType;
 606     private transient Class<T> secondaryType;
 607 
 608     /**
 609      * Returns {@code true} if this class is a primitive class.
 610      * <p>
 611      * Each primitive class has a {@linkplain #isPrimaryType() primary type}
 612      * representing the <em>primitive reference type</em> and a
 613      * {@linkplain #isPrimitiveValueType() secondary type} representing
 614      * the <em>primitive value type</em>.  The primitive reference type
 615      * and primitive value type can be obtained by calling the
 616      * {@link #asPrimaryType()} and {@link #asValueType} method
 617      * of a primitive class respectively.
 618      * <p>
 619      * A primitive class is a {@linkplain #isValue() value class}.
 620      *
 621      * @return {@code true} if this class is a primitive class, otherwise {@code false}
 622      * @see #isValue()
 623      * @see #asPrimaryType()
 624      * @see #asValueType()
 625      * @since Valhalla
 626      */
 627     public boolean isPrimitiveClass() {
 628         return (this.getModifiers() & PRIMITIVE_CLASS) != 0;
 629     }
 630 
 631     /**
 632      * Returns {@code true} if this class is a value class.
 633      *
 634      * @return {@code true} if this class is a value class;
 635      * otherwise {@code false}
 636      * @since Valhalla
 637      */
 638     public boolean isValue() {
 639         return (this.getModifiers() & VALUE_CLASS) != 0;
 640     }
 641 
 642     /**
 643      * Returns a {@code Class} object representing the primary type
 644      * of this class or interface.
 645      * <p>
 646      * If this {@code Class} object represents a primitive type or an array type,
 647      * then this method returns this class.
 648      * <p>
 649      * If this {@code Class} object represents a {@linkplain #isPrimitiveClass()
 650      * primitive class}, then this method returns the <em>primitive reference type</em>
 651      * type of this primitive class.
 652      * <p>
 653      * Otherwise, this {@code Class} object represents a non-primitive class or interface
 654      * and this method returns this class.
 655      *
 656      * @return the {@code Class} representing the primary type of
 657      *         this class or interface
 658      * @since Valhalla
 659      */
 660     @IntrinsicCandidate
 661     public Class<?> asPrimaryType() {
 662         return isPrimitiveClass() ? primaryType : this;
 663     }
 664 
 665     /**
 666      * Returns a {@code Class} object representing the <em>primitive value type</em>
 667      * of this class if this class is a {@linkplain #isPrimitiveClass() primitive class}.
 668      *
 669      * @apiNote Alternatively, this method returns null if this class is not
 670      *          a primitive class rather than throwing UOE.
 671      *
 672      * @return the {@code Class} representing the {@linkplain #isPrimitiveValueType()
 673      * primitive value type} of this class if this class is a primitive class
 674      * @throws UnsupportedOperationException if this class or interface
 675      *         is not a primitive class
 676      * @since Valhalla
 677      */
 678     @IntrinsicCandidate
 679     public Class<?> asValueType() {
 680         if (isPrimitiveClass())
 681             return secondaryType;
 682 
 683         throw new UnsupportedOperationException(this.getName().concat(" is not a primitive class"));
 684     }
 685 
 686     /**
 687      * Returns {@code true} if this {@code Class} object represents the primary type
 688      * of this class or interface.
 689      * <p>
 690      * If this {@code Class} object represents a primitive type or an array type,
 691      * then this method returns {@code true}.
 692      * <p>
 693      * If this {@code Class} object represents a {@linkplain #isPrimitiveClass()
 694      * primitive}, then this method returns {@code true} if this {@code Class}
 695      * object represents a primitive reference type, or returns {@code false}
 696      * if this {@code Class} object represents a primitive value type.
 697      * <p>
 698      * If this {@code Class} object represents a non-primitive class or interface,
 699      * then this method returns {@code true}.
 700      *
 701      * @return {@code true} if this {@code Class} object represents
 702      * the primary type of this class or interface
 703      * @since Valhalla
 704      */
 705     public boolean isPrimaryType() {
 706         if (isPrimitiveClass()) {
 707             return this == primaryType;
 708         }
 709         return true;
 710     }
 711 
 712     /**
 713      * Returns {@code true} if this {@code Class} object represents
 714      * a {@linkplain #isPrimitiveClass() primitive} value type.
 715      *
 716      * @return {@code true} if this {@code Class} object represents
 717      * the value type of a primitive class
 718      * @since Valhalla
 719      */
 720     public boolean isPrimitiveValueType() {
 721         return isPrimitiveClass() && this == secondaryType;
 722     }
 723 
 724     /**
 725      * Creates a new instance of the class represented by this {@code Class}
 726      * object.  The class is instantiated as if by a {@code new}
 727      * expression with an empty argument list.  The class is initialized if it
 728      * has not already been initialized.
 729      *
 730      * @deprecated This method propagates any exception thrown by the
 731      * nullary constructor, including a checked exception.  Use of
 732      * this method effectively bypasses the compile-time exception
 733      * checking that would otherwise be performed by the compiler.
 734      * The {@link
 735      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
 736      * Constructor.newInstance} method avoids this problem by wrapping
 737      * any exception thrown by the constructor in a (checked) {@link
 738      * java.lang.reflect.InvocationTargetException}.
 739      *
 740      * <p>The call
 741      *
 742      * <pre>{@code
 743      * clazz.newInstance()

 848      * class or any superclass of the specified {@code Object} argument
 849      * implements this interface; it returns {@code false} otherwise. If
 850      * this {@code Class} object represents a primitive type, this method
 851      * returns {@code false}.
 852      *
 853      * @param   obj the object to check
 854      * @return  true if {@code obj} is an instance of this class
 855      *
 856      * @since 1.1
 857      */
 858     @IntrinsicCandidate
 859     public native boolean isInstance(Object obj);
 860 
 861 
 862     /**
 863      * Determines if the class or interface represented by this
 864      * {@code Class} object is either the same as, or is a superclass or
 865      * superinterface of, the class or interface represented by the specified
 866      * {@code Class} parameter. It returns {@code true} if so;
 867      * otherwise it returns {@code false}. If this {@code Class}
 868      * object represents the {@linkplain #isPrimaryType() reference type}
 869      * of a {@linkplain #isPrimitiveClass() primitive class}, this method
 870      * return {@code true} if the specified {@code Class} parameter represents
 871      * the same primitive class. If this {@code Class}
 872      * object represents a primitive type, this method returns
 873      * {@code true} if the specified {@code Class} parameter is
 874      * exactly this {@code Class} object; otherwise it returns
 875      * {@code false}.
 876      *
 877      * <p> Specifically, this method tests whether the type represented by the
 878      * specified {@code Class} parameter can be converted to the type
 879      * represented by this {@code Class} object via an identity conversion
 880      * or via a widening reference conversion or via a primitive widening
 881      * conversion. See <cite>The Java Language Specification</cite>,
 882      * sections {@jls 5.1.1} and {@jls 5.1.4}, for details.
 883      *
 884      * @param     cls the {@code Class} object to be checked
 885      * @return    the {@code boolean} value indicating whether objects of the
 886      *            type {@code cls} can be assigned to objects of this class
 887      * @throws    NullPointerException if the specified Class parameter is
 888      *            null.
 889      * @since     1.1
 890      */
 891     @IntrinsicCandidate
 892     public native boolean isAssignableFrom(Class<?> cls);
 893 
 894 
 895     /**
 896      * Determines if this {@code Class} object represents an
 897      * interface type.
 898      *
 899      * @return  {@code true} if this {@code Class} object represents an interface;
 900      *          {@code false} otherwise.
 901      */
 902     @IntrinsicCandidate

 990      *      {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
 991      *      Lookup::defineHiddenClass}, and {@code <suffix>} is an unqualified name.
 992      * </ul>
 993      *
 994      * <p> If this {@code Class} object represents an array class, then
 995      * the result is a string consisting of one or more '{@code [}' characters
 996      * representing the depth of the array nesting, followed by the element
 997      * type as encoded using the following table:
 998      *
 999      * <blockquote><table class="striped">
1000      * <caption style="display:none">Element types and encodings</caption>
1001      * <thead>
1002      * <tr><th scope="col"> Element Type <th scope="col"> Encoding
1003      * </thead>
1004      * <tbody style="text-align:left">
1005      * <tr><th scope="row"> {@code boolean} <td style="text-align:center"> {@code Z}
1006      * <tr><th scope="row"> {@code byte}    <td style="text-align:center"> {@code B}
1007      * <tr><th scope="row"> {@code char}    <td style="text-align:center"> {@code C}
1008      * <tr><th scope="row"> class or interface with <a href="ClassLoader.html#binary-name">binary name</a> <i>N</i>
1009      *                                      <td style="text-align:center"> {@code L}<em>N</em>{@code ;}
1010      * <tr><th scope="row"> {@linkplain #isPrimitiveClass() primitive class} with <a href="ClassLoader.html#binary-name">binary name</a> <i>N</i>
1011      *                                      <td style="text-align:center"> {@code Q}<em>N</em>{@code ;}
1012      * <tr><th scope="row"> {@code double}  <td style="text-align:center"> {@code D}
1013      * <tr><th scope="row"> {@code float}   <td style="text-align:center"> {@code F}
1014      * <tr><th scope="row"> {@code int}     <td style="text-align:center"> {@code I}
1015      * <tr><th scope="row"> {@code long}    <td style="text-align:center"> {@code J}
1016      * <tr><th scope="row"> {@code short}   <td style="text-align:center"> {@code S}
1017      * </tbody>
1018      * </table></blockquote>
1019      *
1020      * <p> If this {@code Class} object represents a primitive type or {@code void},
1021      * then the result is a string with the same spelling as the Java language
1022      * keyword which corresponds to the primitive type or {@code void}.
1023      *
1024      * <p> Examples:
1025      * <blockquote><pre>
1026      * String.class.getName()
1027      *     returns "java.lang.String"
1028      * byte.class.getName()
1029      *     returns "byte"
1030      * Point.class.getName()
1031      *     returns "Point"
1032      * (new Object[3]).getClass().getName()
1033      *     returns "[Ljava.lang.Object;"
1034      * (new Point[3]).getClass().getName()
1035      *     returns "[QPoint;"
1036      * (new Point.ref[3][4]).getClass().getName()
1037      *     returns "[[LPoint;"
1038      * (new int[3][4][5][6][7][8][9]).getClass().getName()
1039      *     returns "[[[[[[[I"
1040      * </pre></blockquote>
1041      *
1042      * @return  the name of the class, interface, or other entity
1043      *          represented by this {@code Class} object.
1044      * @jls 13.1 The Form of a Binary
1045      */
1046     public String getName() {
1047         String name = this.name;
1048         return name != null ? name : initClassName();
1049     }
1050 
1051     // Cache the name to reduce the number of calls into the VM.
1052     // This field would be set by VM itself during initClassName call.
1053     private transient String name;
1054     private native String initClassName();
1055 
1056     /**
1057      * Returns the class loader for the class.  Some implementations may use

1451      * primitive type or void, then its {@code final} modifier is always
1452      * {@code true} and its interface modifier is always
1453      * {@code false}. The values of its other modifiers are not determined
1454      * by this specification.
1455      *
1456      * <p> The modifier encodings are defined in section {@jvms 4.1}
1457      * of <cite>The Java Virtual Machine Specification</cite>.
1458      *
1459      * @return the {@code int} representing the modifiers for this class
1460      * @see     java.lang.reflect.Modifier
1461      * @see <a
1462      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1463      * programming language and JVM modeling in core reflection</a>
1464      * @since 1.1
1465      * @jls 8.1.1 Class Modifiers
1466      * @jls 9.1.1. Interface Modifiers
1467      */
1468     @IntrinsicCandidate
1469     public native int getModifiers();
1470 

1471     /**
1472      * Gets the signers of this class.
1473      *
1474      * @return  the signers of this class, or null if there are no signers.  In
1475      *          particular, this method returns null if this {@code Class} object represents
1476      *          a primitive type or void.
1477      * @since   1.1
1478      */
1479     public native Object[] getSigners();
1480 

1481     /**
1482      * Set the signers of this class.
1483      */
1484     native void setSigners(Object[] signers);
1485 
1486 
1487     /**
1488      * If this {@code Class} object represents a local or anonymous
1489      * class within a method, returns a {@link
1490      * java.lang.reflect.Method Method} object representing the
1491      * immediately enclosing method of the underlying class. Returns
1492      * {@code null} otherwise.
1493      *
1494      * In particular, this method returns {@code null} if the underlying
1495      * class is a local or anonymous class immediately enclosed by a class or
1496      * interface declaration, instance initializer or static initializer.
1497      *
1498      * @return the immediately enclosing method of the underlying class, if
1499      *     that class is a local or anonymous class; otherwise {@code null}.
1500      *

1848             simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1849         }
1850         return simpleName;
1851     }
1852 
1853     /**
1854      * Return an informative string for the name of this class or interface.
1855      *
1856      * @return an informative string for the name of this class or interface
1857      * @since 1.8
1858      */
1859     public String getTypeName() {
1860         if (isArray()) {
1861             try {
1862                 Class<?> cl = this;
1863                 int dimensions = 0;
1864                 do {
1865                     dimensions++;
1866                     cl = cl.getComponentType();
1867                 } while (cl.isArray());
1868                 return cl.getTypeName().concat("[]".repeat(dimensions));
1869             } catch (Throwable e) { /*FALLTHRU*/ }
1870         }
1871         if (isPrimitiveClass()) {
1872             // TODO: null-default
1873             return isPrimaryType() ? getName().concat(".ref") : getName();
1874         } else {
1875             return getName();
1876         }
1877     }
1878 
1879     /**
1880      * Returns the canonical name of the underlying class as
1881      * defined by <cite>The Java Language Specification</cite>.
1882      * Returns {@code null} if the underlying class does not have a canonical
1883      * name. Classes without canonical names include:
1884      * <ul>
1885      * <li>a {@linkplain #isLocalClass() local class}
1886      * <li>a {@linkplain #isAnonymousClass() anonymous class}
1887      * <li>a {@linkplain #isHidden() hidden class}
1888      * <li>an array whose component type does not have a canonical name</li>
1889      * </ul>
1890      *
1891      * The canonical name for a primitive class is the keyword for the
1892      * corresponding primitive type ({@code byte}, {@code short},
1893      * {@code char}, {@code int}, and so on).
1894      *
1895      * <p>An array type has a canonical name if and only if its
1896      * component type has a canonical name. When an array type has a

4067                 throw new IllegalArgumentException(
4068                     getName() + " is not an enum class");
4069             directory = new HashMap<>((int)(universe.length / 0.75f) + 1);
4070             for (T constant : universe) {
4071                 directory.put(((Enum<?>)constant).name(), constant);
4072             }
4073             enumConstantDirectory = directory;
4074         }
4075         return directory;
4076     }
4077     private transient volatile Map<String, T> enumConstantDirectory;
4078 
4079     /**
4080      * Casts an object to the class or interface represented
4081      * by this {@code Class} object.
4082      *
4083      * @param obj the object to be cast
4084      * @return the object after casting, or null if obj is null
4085      *
4086      * @throws ClassCastException if the object is not
4087      * {@code null} and is not assignable to the type T.
4088      * @throws NullPointerException if this class is an {@linkplain #isPrimitiveValueType()
4089      * primitive value type} and the object is {@code null}
4090      *
4091      * @since 1.5
4092      */
4093     @SuppressWarnings("unchecked")
4094     @IntrinsicCandidate
4095     public T cast(Object obj) {
4096         if (isPrimitiveValueType() && obj == null)
4097             throw new NullPointerException(getName() + " is a primitive value type");
4098 
4099         if (obj != null && !isInstance(obj))
4100             throw new ClassCastException(cannotCastMsg(obj));
4101         return (T) obj;
4102     }
4103 
4104     private String cannotCastMsg(Object obj) {
4105         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
4106     }
4107 
4108     /**
4109      * Casts this {@code Class} object to represent a subclass of the class
4110      * represented by the specified class object.  Checks that the cast
4111      * is valid, and throws a {@code ClassCastException} if it is not.  If
4112      * this method succeeds, it always returns a reference to this {@code Class} object.
4113      *
4114      * <p>This method is useful when a client needs to "narrow" the type of
4115      * a {@code Class} object to pass it to an API that restricts the
4116      * {@code Class} objects that it is willing to accept.  A cast would
4117      * generate a compile-time warning, as the correctness of the cast
4118      * could not be checked at runtime (because generic types are implemented

4374      *
4375      * <p> If this {@code Class} object represents an interface, the return
4376      * value is an array containing objects representing the uses of interface
4377      * types to specify interfaces directly extended by the interface. The
4378      * order of the objects in the array corresponds to the order of the
4379      * interface types used in the 'extends' clause of the declaration of this
4380      * {@code Class} object.
4381      *
4382      * <p> If this {@code Class} object represents a class or interface whose
4383      * declaration does not explicitly indicate any annotated superinterfaces,
4384      * the return value is an array of length 0.
4385      *
4386      * <p> If this {@code Class} object represents either the {@code Object}
4387      * class, an array type, a primitive type, or void, the return value is an
4388      * array of length 0.
4389      *
4390      * @return an array representing the superinterfaces
4391      * @since 1.8
4392      */
4393     public AnnotatedType[] getAnnotatedInterfaces() {
4394         return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
4395     }
4396 
4397     private native Class<?> getNestHost0();
4398 
4399     /**
4400      * Returns the nest host of the <a href=#nest>nest</a> to which the class
4401      * or interface represented by this {@code Class} object belongs.
4402      * Every class and interface belongs to exactly one nest.
4403      *
4404      * If the nest host of this class or interface has previously
4405      * been determined, then this method returns the nest host.
4406      * If the nest host of this class or interface has
4407      * not previously been determined, then this method determines the nest
4408      * host using the algorithm of JVMS 5.4.4, and returns it.
4409      *
4410      * Often, a class or interface belongs to a nest consisting only of itself,
4411      * in which case this method returns {@code this} to indicate that the class
4412      * or interface is the nest host.
4413      *
4414      * <p>If this {@code Class} object represents a primitive type, an array type,

4589      * {@code void}, then the result is a field descriptor string which
4590      * is a one-letter code corresponding to a primitive type or {@code void}
4591      * ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}).
4592      *
4593      * @apiNote
4594      * This is not a strict inverse of {@link #forName};
4595      * distinct classes which share a common name but have different class loaders
4596      * will have identical descriptor strings.
4597      *
4598      * @return the descriptor string for this {@code Class} object
4599      * @jvms 4.3.2 Field Descriptors
4600      * @since 12
4601      */
4602     @Override
4603     public String descriptorString() {
4604         if (isPrimitive())
4605             return Wrapper.forPrimitiveType(this).basicTypeString();
4606 
4607         if (isArray()) {
4608             return "[" + componentType.descriptorString();
4609         }
4610         char typeDesc = isPrimitiveValueType() ? 'Q' : 'L';
4611         if (isHidden()) {
4612             String name = getName();
4613             int index = name.indexOf('/');
4614             return new StringBuilder(name.length() + 2)
4615                     .append(typeDesc)
4616                     .append(name.substring(0, index).replace('.', '/'))
4617                     .append('.')
4618                     .append(name, index + 1, name.length())
4619                     .append(';')
4620                     .toString();
4621         } else {
4622             String name = getName().replace('.', '/');
4623             return new StringBuilder(name.length() + 2)
4624                     .append(typeDesc)
4625                     .append(name)
4626                     .append(';')
4627                     .toString();
4628         }
4629     }
4630 
4631     /**
4632      * Returns the component type of this {@code Class}, if it describes
4633      * an array type, or {@code null} otherwise.
4634      *
4635      * @implSpec
4636      * Equivalent to {@link Class#getComponentType()}.
4637      *
4638      * @return a {@code Class} describing the component type, or {@code null}
4639      * if this {@code Class} does not describe an array type
4640      * @since 12
4641      */
4642     @Override
4643     public Class<?> componentType() {
4644         return isArray() ? componentType : null;
< prev index next >