< prev index next >

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

Print this page

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

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











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

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



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

 452         Class<?> caller = null;
 453         @SuppressWarnings("removal")
 454         SecurityManager sm = System.getSecurityManager();
 455         if (sm != null) {
 456             // Reflective call to get caller class is only needed if a security manager
 457             // is present.  Avoid the overhead of making this call otherwise.
 458             caller = Reflection.getCallerClass();
 459             if (loader == null) {
 460                 ClassLoader ccl = ClassLoader.getClassLoader(caller);
 461                 if (ccl != null) {
 462                     sm.checkPermission(
 463                         SecurityConstants.GET_CLASSLOADER_PERMISSION);
 464                 }
 465             }
 466         }
 467         return forName0(name, initialize, loader, caller);
 468     }
 469 
 470     /** Called after security check for system loader access checks have been made. */
 471     private static native Class<?> forName0(String name, boolean initialize,
 472                                             ClassLoader loader,
 473                                             Class<?> caller)
 474         throws ClassNotFoundException;
 475 
 476 
 477     /**
 478      * Returns the {@code Class} with the given <a href="ClassLoader.html#binary-name">
 479      * binary name</a> in the given module.
 480      *
 481      * <p> This method attempts to locate and load the class or interface.
 482      * It does not link the class, and does not run the class initializer.
 483      * If the class is not found, this method returns {@code null}. </p>
 484      *
 485      * <p> If the class loader of the given module defines other modules and
 486      * the given name is a class defined in a different module, this method
 487      * returns {@code null} after the class is loaded. </p>
 488      *
 489      * <p> This method does not check whether the requested class is
 490      * accessible to its caller. </p>
 491      *
 492      * @apiNote
 493      * This method returns {@code null} on failure rather than

 531         if (sm != null) {
 532             Class<?> caller = Reflection.getCallerClass();
 533             if (caller != null && caller.getModule() != module) {
 534                 // if caller is null, Class.forName is the last java frame on the stack.
 535                 // java.base has all permissions
 536                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 537             }
 538             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
 539             cl = AccessController.doPrivileged(pa);
 540         } else {
 541             cl = module.getClassLoader();
 542         }
 543 
 544         if (cl != null) {
 545             return cl.loadClass(module, name);
 546         } else {
 547             return BootLoader.loadClass(module, name);
 548         }
 549     }
 550 











































































































 551     /**
 552      * Creates a new instance of the class represented by this {@code Class}
 553      * object.  The class is instantiated as if by a {@code new}
 554      * expression with an empty argument list.  The class is initialized if it
 555      * has not already been initialized.
 556      *
 557      * @deprecated This method propagates any exception thrown by the
 558      * nullary constructor, including a checked exception.  Use of
 559      * this method effectively bypasses the compile-time exception
 560      * checking that would otherwise be performed by the compiler.
 561      * The {@link
 562      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
 563      * Constructor.newInstance} method avoids this problem by wrapping
 564      * any exception thrown by the constructor in a (checked) {@link
 565      * java.lang.reflect.InvocationTargetException}.
 566      *
 567      * <p>The call
 568      *
 569      * <pre>{@code
 570      * clazz.newInstance()

 675      * class or any superclass of the specified {@code Object} argument
 676      * implements this interface; it returns {@code false} otherwise. If
 677      * this {@code Class} object represents a primitive type, this method
 678      * returns {@code false}.
 679      *
 680      * @param   obj the object to check
 681      * @return  true if {@code obj} is an instance of this class
 682      *
 683      * @since 1.1
 684      */
 685     @IntrinsicCandidate
 686     public native boolean isInstance(Object obj);
 687 
 688 
 689     /**
 690      * Determines if the class or interface represented by this
 691      * {@code Class} object is either the same as, or is a superclass or
 692      * superinterface of, the class or interface represented by the specified
 693      * {@code Class} parameter. It returns {@code true} if so;
 694      * otherwise it returns {@code false}. If this {@code Class}




 695      * object represents a primitive type, this method returns
 696      * {@code true} if the specified {@code Class} parameter is
 697      * exactly this {@code Class} object; otherwise it returns
 698      * {@code false}.
 699      *
 700      * <p> Specifically, this method tests whether the type represented by the
 701      * specified {@code Class} parameter can be converted to the type
 702      * represented by this {@code Class} object via an identity conversion
 703      * or via a widening reference conversion. See <cite>The Java Language
 704      * Specification</cite>, sections {@jls 5.1.1} and {@jls 5.1.4},
 705      * for details.
 706      *
 707      * @param     cls the {@code Class} object to be checked
 708      * @return    the {@code boolean} value indicating whether objects of the
 709      *            type {@code cls} can be assigned to objects of this class
 710      * @throws    NullPointerException if the specified Class parameter is
 711      *            null.
 712      * @since     1.1
 713      */
 714     @IntrinsicCandidate
 715     public native boolean isAssignableFrom(Class<?> cls);
 716 
 717 
 718     /**
 719      * Determines if this {@code Class} object represents an
 720      * interface type.
 721      *
 722      * @return  {@code true} if this {@code Class} object represents an interface;
 723      *          {@code false} otherwise.
 724      */
 725     @IntrinsicCandidate

 813      *      {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
 814      *      Lookup::defineHiddenClass}, and {@code <suffix>} is an unqualified name.
 815      * </ul>
 816      *
 817      * <p> If this {@code Class} object represents an array class, then
 818      * the result is a string consisting of one or more '{@code [}' characters
 819      * representing the depth of the array nesting, followed by the element
 820      * type as encoded using the following table:
 821      *
 822      * <blockquote><table class="striped">
 823      * <caption style="display:none">Element types and encodings</caption>
 824      * <thead>
 825      * <tr><th scope="col"> Element Type <th scope="col"> Encoding
 826      * </thead>
 827      * <tbody style="text-align:left">
 828      * <tr><th scope="row"> {@code boolean} <td style="text-align:center"> {@code Z}
 829      * <tr><th scope="row"> {@code byte}    <td style="text-align:center"> {@code B}
 830      * <tr><th scope="row"> {@code char}    <td style="text-align:center"> {@code C}
 831      * <tr><th scope="row"> class or interface with <a href="ClassLoader.html#binary-name">binary name</a> <i>N</i>
 832      *                                      <td style="text-align:center"> {@code L}<em>N</em>{@code ;}


 833      * <tr><th scope="row"> {@code double}  <td style="text-align:center"> {@code D}
 834      * <tr><th scope="row"> {@code float}   <td style="text-align:center"> {@code F}
 835      * <tr><th scope="row"> {@code int}     <td style="text-align:center"> {@code I}
 836      * <tr><th scope="row"> {@code long}    <td style="text-align:center"> {@code J}
 837      * <tr><th scope="row"> {@code short}   <td style="text-align:center"> {@code S}
 838      * </tbody>
 839      * </table></blockquote>
 840      *
 841      * <p> If this {@code Class} object represents a primitive type or {@code void},
 842      * then the result is a string with the same spelling as the Java language
 843      * keyword which corresponds to the primitive type or {@code void}.
 844      *
 845      * <p> Examples:
 846      * <blockquote><pre>
 847      * String.class.getName()
 848      *     returns "java.lang.String"
 849      * byte.class.getName()
 850      *     returns "byte"


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




 853      * (new int[3][4][5][6][7][8][9]).getClass().getName()
 854      *     returns "[[[[[[[I"
 855      * </pre></blockquote>
 856      *
 857      * @return  the name of the class, interface, or other entity
 858      *          represented by this {@code Class} object.
 859      * @jls 13.1 The Form of a Binary
 860      */
 861     public String getName() {
 862         String name = this.name;
 863         return name != null ? name : initClassName();
 864     }
 865 
 866     // Cache the name to reduce the number of calls into the VM.
 867     // This field would be set by VM itself during initClassName call.
 868     private transient String name;
 869     private native String initClassName();
 870 
 871     /**
 872      * Returns the class loader for the class.  Some implementations may use

1266      * primitive type or void, then its {@code final} modifier is always
1267      * {@code true} and its interface modifier is always
1268      * {@code false}. The values of its other modifiers are not determined
1269      * by this specification.
1270      *
1271      * <p> The modifier encodings are defined in section {@jvms 4.1}
1272      * of <cite>The Java Virtual Machine Specification</cite>.
1273      *
1274      * @return the {@code int} representing the modifiers for this class
1275      * @see     java.lang.reflect.Modifier
1276      * @see <a
1277      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1278      * programming language and JVM modeling in core reflection</a>
1279      * @since 1.1
1280      * @jls 8.1.1 Class Modifiers
1281      * @jls 9.1.1. Interface Modifiers
1282      */
1283     @IntrinsicCandidate
1284     public native int getModifiers();
1285 
1286 
1287     /**
1288      * Gets the signers of this class.
1289      *
1290      * @return  the signers of this class, or null if there are no signers.  In
1291      *          particular, this method returns null if this {@code Class} object represents
1292      *          a primitive type or void.
1293      * @since   1.1
1294      */
1295     public native Object[] getSigners();
1296 
1297 
1298     /**
1299      * Set the signers of this class.
1300      */
1301     native void setSigners(Object[] signers);
1302 
1303 
1304     /**
1305      * If this {@code Class} object represents a local or anonymous
1306      * class within a method, returns a {@link
1307      * java.lang.reflect.Method Method} object representing the
1308      * immediately enclosing method of the underlying class. Returns
1309      * {@code null} otherwise.
1310      *
1311      * In particular, this method returns {@code null} if the underlying
1312      * class is a local or anonymous class immediately enclosed by a class or
1313      * interface declaration, instance initializer or static initializer.
1314      *
1315      * @return the immediately enclosing method of the underlying class, if
1316      *     that class is a local or anonymous class; otherwise {@code null}.
1317      *

1665             simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1666         }
1667         return simpleName;
1668     }
1669 
1670     /**
1671      * Return an informative string for the name of this class or interface.
1672      *
1673      * @return an informative string for the name of this class or interface
1674      * @since 1.8
1675      */
1676     public String getTypeName() {
1677         if (isArray()) {
1678             try {
1679                 Class<?> cl = this;
1680                 int dimensions = 0;
1681                 do {
1682                     dimensions++;
1683                     cl = cl.getComponentType();
1684                 } while (cl.isArray());
1685                 return cl.getName().concat("[]".repeat(dimensions));
1686             } catch (Throwable e) { /*FALLTHRU*/ }
1687         }
1688         return getName();





1689     }
1690 
1691     /**
1692      * Returns the canonical name of the underlying class as
1693      * defined by <cite>The Java Language Specification</cite>.
1694      * Returns {@code null} if the underlying class does not have a canonical
1695      * name. Classes without canonical names include:
1696      * <ul>
1697      * <li>a {@linkplain #isLocalClass() local class}
1698      * <li>a {@linkplain #isAnonymousClass() anonymous class}
1699      * <li>a {@linkplain #isHidden() hidden class}
1700      * <li>an array whose component type does not have a canonical name</li>
1701      * </ul>
1702      *
1703      * @return the canonical name of the underlying class if it exists, and
1704      * {@code null} otherwise.
1705      * @since 1.5
1706      */
1707     public String getCanonicalName() {
1708         ReflectionData<T> rd = reflectionData();

3861                 throw new IllegalArgumentException(
3862                     getName() + " is not an enum class");
3863             directory = new HashMap<>((int)(universe.length / 0.75f) + 1);
3864             for (T constant : universe) {
3865                 directory.put(((Enum<?>)constant).name(), constant);
3866             }
3867             enumConstantDirectory = directory;
3868         }
3869         return directory;
3870     }
3871     private transient volatile Map<String, T> enumConstantDirectory;
3872 
3873     /**
3874      * Casts an object to the class or interface represented
3875      * by this {@code Class} object.
3876      *
3877      * @param obj the object to be cast
3878      * @return the object after casting, or null if obj is null
3879      *
3880      * @throws ClassCastException if the object is not
3881      * null and is not assignable to the type T.


3882      *
3883      * @since 1.5
3884      */
3885     @SuppressWarnings("unchecked")
3886     @IntrinsicCandidate
3887     public T cast(Object obj) {



3888         if (obj != null && !isInstance(obj))
3889             throw new ClassCastException(cannotCastMsg(obj));
3890         return (T) obj;
3891     }
3892 
3893     private String cannotCastMsg(Object obj) {
3894         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3895     }
3896 
3897     /**
3898      * Casts this {@code Class} object to represent a subclass of the class
3899      * represented by the specified class object.  Checks that the cast
3900      * is valid, and throws a {@code ClassCastException} if it is not.  If
3901      * this method succeeds, it always returns a reference to this {@code Class} object.
3902      *
3903      * <p>This method is useful when a client needs to "narrow" the type of
3904      * a {@code Class} object to pass it to an API that restricts the
3905      * {@code Class} objects that it is willing to accept.  A cast would
3906      * generate a compile-time warning, as the correctness of the cast
3907      * could not be checked at runtime (because generic types are implemented

4163      *
4164      * <p> If this {@code Class} object represents an interface, the return
4165      * value is an array containing objects representing the uses of interface
4166      * types to specify interfaces directly extended by the interface. The
4167      * order of the objects in the array corresponds to the order of the
4168      * interface types used in the 'extends' clause of the declaration of this
4169      * {@code Class} object.
4170      *
4171      * <p> If this {@code Class} object represents a class or interface whose
4172      * declaration does not explicitly indicate any annotated superinterfaces,
4173      * the return value is an array of length 0.
4174      *
4175      * <p> If this {@code Class} object represents either the {@code Object}
4176      * class, an array type, a primitive type, or void, the return value is an
4177      * array of length 0.
4178      *
4179      * @return an array representing the superinterfaces
4180      * @since 1.8
4181      */
4182     public AnnotatedType[] getAnnotatedInterfaces() {
4183          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
4184     }
4185 
4186     private native Class<?> getNestHost0();
4187 
4188     /**
4189      * Returns the nest host of the <a href=#nest>nest</a> to which the class
4190      * or interface represented by this {@code Class} object belongs.
4191      * Every class and interface belongs to exactly one nest.
4192      *
4193      * If the nest host of this class or interface has previously
4194      * been determined, then this method returns the nest host.
4195      * If the nest host of this class or interface has
4196      * not previously been determined, then this method determines the nest
4197      * host using the algorithm of JVMS 5.4.4, and returns it.
4198      *
4199      * Often, a class or interface belongs to a nest consisting only of itself,
4200      * in which case this method returns {@code this} to indicate that the class
4201      * or interface is the nest host.
4202      *
4203      * <p>If this {@code Class} object represents a primitive type, an array type,

4378      * {@code void}, then the result is a field descriptor string which
4379      * is a one-letter code corresponding to a primitive type or {@code void}
4380      * ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}).
4381      *
4382      * @apiNote
4383      * This is not a strict inverse of {@link #forName};
4384      * distinct classes which share a common name but have different class loaders
4385      * will have identical descriptor strings.
4386      *
4387      * @return the descriptor string for this {@code Class} object
4388      * @jvms 4.3.2 Field Descriptors
4389      * @since 12
4390      */
4391     @Override
4392     public String descriptorString() {
4393         if (isPrimitive())
4394             return Wrapper.forPrimitiveType(this).basicTypeString();
4395 
4396         if (isArray()) {
4397             return "[" + componentType.descriptorString();
4398         } else if (isHidden()) {


4399             String name = getName();
4400             int index = name.indexOf('/');
4401             return new StringBuilder(name.length() + 2)
4402                     .append('L')
4403                     .append(name.substring(0, index).replace('.', '/'))
4404                     .append('.')
4405                     .append(name, index + 1, name.length())
4406                     .append(';')
4407                     .toString();
4408         } else {
4409             String name = getName().replace('.', '/');
4410             return new StringBuilder(name.length() + 2)
4411                     .append('L')
4412                     .append(name)
4413                     .append(';')
4414                     .toString();
4415         }
4416     }
4417 
4418     /**
4419      * Returns the component type of this {@code Class}, if it describes
4420      * an array type, or {@code null} otherwise.
4421      *
4422      * @implSpec
4423      * Equivalent to {@link Class#getComponentType()}.
4424      *
4425      * @return a {@code Class} describing the component type, or {@code null}
4426      * if this {@code Class} does not describe an array type
4427      * @since 12
4428      */
4429     @Override
4430     public Class<?> componentType() {
4431         return isArray() ? componentType : null;

 181  * A hidden class or interface is never an array class, but may be
 182  * the element type of an array. In all other respects, the fact that
 183  * a class or interface is hidden has no bearing on the characteristics
 184  * exposed by the methods of class {@code Class}.
 185  *
 186  * @param <T> the type of the class modeled by this {@code Class}
 187  * object.  For example, the type of {@code String.class} is {@code
 188  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
 189  * unknown.
 190  *
 191  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
 192  * @since   1.0
 193  * @jls 15.8.2 Class Literals
 194  */
 195 public final class Class<T> implements java.io.Serializable,
 196                               GenericDeclaration,
 197                               Type,
 198                               AnnotatedElement,
 199                               TypeDescriptor.OfField<Class<?>>,
 200                               Constable {
 201     private static final int ANNOTATION = 0x00002000;
 202     private static final int ENUM       = 0x00004000;
 203     private static final int SYNTHETIC  = 0x00001000;
 204     private static final int PRIMITIVE_CLASS = 0x00000100;
 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 s = isPrimitive() ? "" : "class ";
 237         if (isInterface()) {
 238             s = "interface ";
 239         }
 240         if (isPrimitiveClass()) {
 241             s = "primitive ";
 242         }
 243         // Avoid invokedynamic based String concat, might be not available
 244         s = s.concat(getName());
 245         if (isPrimitiveClass() && isPrimaryType()) {
 246             s = s.concat(".ref");
 247         }
 248         return s;
 249     }
 250 
 251     /**
 252      * Returns a string describing this {@code Class}, including
 253      * information about modifiers and type parameters.
 254      *
 255      * The string is formatted as a list of type modifiers, if any,
 256      * followed by the kind of type (empty string for primitive types
 257      * and {@code class}, {@code enum}, {@code interface},
 258      * {@code @interface}, or {@code record} as appropriate), followed
 259      * by the type's name, followed by an angle-bracketed
 260      * comma-separated list of the type's type parameters, if any,
 261      * including informative bounds on the type parameters, if any.
 262      *
 263      * A space is used to separate modifiers from one another and to
 264      * separate any modifiers from the kind of type. The modifiers
 265      * occur in canonical order. If there are no type parameters, the
 266      * type parameter list is elided.
 267      *
 268      * For an array type, the string starts with the type name,

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

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

 546         if (sm != null) {
 547             Class<?> caller = Reflection.getCallerClass();
 548             if (caller != null && caller.getModule() != module) {
 549                 // if caller is null, Class.forName is the last java frame on the stack.
 550                 // java.base has all permissions
 551                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 552             }
 553             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
 554             cl = AccessController.doPrivileged(pa);
 555         } else {
 556             cl = module.getClassLoader();
 557         }
 558 
 559         if (cl != null) {
 560             return cl.loadClass(module, name);
 561         } else {
 562             return BootLoader.loadClass(module, name);
 563         }
 564     }
 565 
 566     // set by VM if this class is an exotic type such as primitive class
 567     // otherwise, these two fields are null
 568     private transient Class<T> primaryType;
 569     private transient Class<T> secondaryType;
 570 
 571     /**
 572      * Returns {@code true} if this class is a primitive class.
 573      * <p>
 574      * Each primitive class has a {@linkplain #isPrimaryType() primary type}
 575      * representing the <em>primitive reference type</em> and a
 576      * {@linkplain #isValueType() secondary type} representing
 577      * the <em>primitive value type</em>.  The primitive reference type
 578      * and primitive value type can be obtained by calling the
 579      * {@link #asPrimaryType()} and {@link #asValueType} method
 580      * of a primitive class respectively.
 581      *
 582      * @return {@code true} if this class is a primitive class, otherwise {@code false}
 583      * @see #asPrimaryType()
 584      * @see #asValueType()
 585      * @since Valhalla
 586      */
 587     public boolean isPrimitiveClass() {
 588         return (this.getModifiers() & PRIMITIVE_CLASS) != 0;
 589     }
 590 
 591     /**
 592      * Returns a {@code Class} object representing the primary type
 593      * of this class or interface.
 594      * <p>
 595      * If this {@code Class} object represents a primitive type or an array type,
 596      * then this method returns this class.
 597      * <p>
 598      * If this {@code Class} object represents a {@linkplain #isPrimitiveClass()
 599      * primitive class}, then this method returns the <em>primitive reference type</em>
 600      * type of this primitive class.
 601      * <p>
 602      * Otherwise, this {@code Class} object represents a non-primitive class or interface
 603      * and this method returns this class.
 604      *
 605      * @return the {@code Class} representing the primary type of
 606      *         this class or interface
 607      * @since Valhalla
 608      */
 609     @IntrinsicCandidate
 610     public Class<?> asPrimaryType() {
 611         return isPrimitiveClass() ? primaryType : this;
 612     }
 613 
 614     /**
 615      * Returns a {@code Class} object representing the <em>primitive value type</em>
 616      * of this class if this class is a {@linkplain #isPrimitiveClass() primitive class}.
 617      *
 618      * @apiNote Alternatively, this method returns null if this class is not
 619      *          a primitive class rather than throwing UOE.
 620      *
 621      * @return the {@code Class} representing the {@linkplain #isValueType()
 622      * primitive value type} of this class if this class is a primitive class
 623      * @throws UnsupportedOperationException if this class or interface
 624      *         is not a primitive class
 625      * @since Valhalla
 626      */
 627     @IntrinsicCandidate
 628     public Class<?> asValueType() {
 629         if (isPrimitiveClass())
 630             return secondaryType;
 631 
 632         throw new UnsupportedOperationException(this.getName().concat(" is not a primitive class"));
 633     }
 634 
 635     /**
 636      * Returns {@code true} if this {@code Class} object represents the primary type
 637      * of this class or interface.
 638      * <p>
 639      * If this {@code Class} object represents a primitive type or an array type,
 640      * then this method returns {@code true}.
 641      * <p>
 642      * If this {@code Class} object represents a {@linkplain #isPrimitiveClass()
 643      * primitive}, then this method returns {@code true} if this {@code Class}
 644      * object represents a primitive reference type, or returns {@code false}
 645      * if this {@code Class} object represents a primitive value type.
 646      * <p>
 647      * If this {@code Class} object represents a non-primitive class or interface,
 648      * then this method returns {@code true}.
 649      *
 650      * @return {@code true} if this {@code Class} object represents
 651      * the primary type of this class or interface
 652      * @since Valhalla
 653      */
 654     public boolean isPrimaryType() {
 655         if (isPrimitiveClass()) {
 656             return this == primaryType;
 657         }
 658         return true;
 659     }
 660 
 661     /**
 662      * Returns {@code true} if this {@code Class} object represents
 663      * a {@linkplain #isPrimitiveClass() primitive} value type.
 664      *
 665      * @return {@code true} if this {@code Class} object represents the
 666      * value type of a primitive class
 667      * @since Valhalla
 668      */
 669     public boolean isValueType() {
 670         return isPrimitiveClass() && this == secondaryType;
 671     }
 672 
 673     /**
 674      * Creates a new instance of the class represented by this {@code Class}
 675      * object.  The class is instantiated as if by a {@code new}
 676      * expression with an empty argument list.  The class is initialized if it
 677      * has not already been initialized.
 678      *
 679      * @deprecated This method propagates any exception thrown by the
 680      * nullary constructor, including a checked exception.  Use of
 681      * this method effectively bypasses the compile-time exception
 682      * checking that would otherwise be performed by the compiler.
 683      * The {@link
 684      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
 685      * Constructor.newInstance} method avoids this problem by wrapping
 686      * any exception thrown by the constructor in a (checked) {@link
 687      * java.lang.reflect.InvocationTargetException}.
 688      *
 689      * <p>The call
 690      *
 691      * <pre>{@code
 692      * clazz.newInstance()

 797      * class or any superclass of the specified {@code Object} argument
 798      * implements this interface; it returns {@code false} otherwise. If
 799      * this {@code Class} object represents a primitive type, this method
 800      * returns {@code false}.
 801      *
 802      * @param   obj the object to check
 803      * @return  true if {@code obj} is an instance of this class
 804      *
 805      * @since 1.1
 806      */
 807     @IntrinsicCandidate
 808     public native boolean isInstance(Object obj);
 809 
 810 
 811     /**
 812      * Determines if the class or interface represented by this
 813      * {@code Class} object is either the same as, or is a superclass or
 814      * superinterface of, the class or interface represented by the specified
 815      * {@code Class} parameter. It returns {@code true} if so;
 816      * otherwise it returns {@code false}. If this {@code Class}
 817      * object represents the {@linkplain #isPrimaryType() reference type}
 818      * of a {@linkplain #isPrimitiveClass() primitive class}, this method
 819      * return {@code true} if the specified {@code Class} parameter represents
 820      * the same primitive class. If this {@code Class}
 821      * object represents a primitive type, this method returns
 822      * {@code true} if the specified {@code Class} parameter is
 823      * exactly this {@code Class} object; otherwise it returns
 824      * {@code false}.
 825      *
 826      * <p> Specifically, this method tests whether the type represented by the
 827      * specified {@code Class} parameter can be converted to the type
 828      * represented by this {@code Class} object via an identity conversion
 829      * or via a widening reference conversion or via a primitive widening
 830      * conversion. See <cite>The Java Language Specification</cite>,
 831      * sections {@jls 5.1.1} and {@jls 5.1.4}, for details.
 832      *
 833      * @param     cls the {@code Class} object to be checked
 834      * @return    the {@code boolean} value indicating whether objects of the
 835      *            type {@code cls} can be assigned to objects of this class
 836      * @throws    NullPointerException if the specified Class parameter is
 837      *            null.
 838      * @since     1.1
 839      */
 840     @IntrinsicCandidate
 841     public native boolean isAssignableFrom(Class<?> cls);
 842 
 843 
 844     /**
 845      * Determines if this {@code Class} object represents an
 846      * interface type.
 847      *
 848      * @return  {@code true} if this {@code Class} object represents an interface;
 849      *          {@code false} otherwise.
 850      */
 851     @IntrinsicCandidate

 939      *      {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
 940      *      Lookup::defineHiddenClass}, and {@code <suffix>} is an unqualified name.
 941      * </ul>
 942      *
 943      * <p> If this {@code Class} object represents an array class, then
 944      * the result is a string consisting of one or more '{@code [}' characters
 945      * representing the depth of the array nesting, followed by the element
 946      * type as encoded using the following table:
 947      *
 948      * <blockquote><table class="striped">
 949      * <caption style="display:none">Element types and encodings</caption>
 950      * <thead>
 951      * <tr><th scope="col"> Element Type <th scope="col"> Encoding
 952      * </thead>
 953      * <tbody style="text-align:left">
 954      * <tr><th scope="row"> {@code boolean} <td style="text-align:center"> {@code Z}
 955      * <tr><th scope="row"> {@code byte}    <td style="text-align:center"> {@code B}
 956      * <tr><th scope="row"> {@code char}    <td style="text-align:center"> {@code C}
 957      * <tr><th scope="row"> class or interface with <a href="ClassLoader.html#binary-name">binary name</a> <i>N</i>
 958      *                                      <td style="text-align:center"> {@code L}<em>N</em>{@code ;}
 959      * <tr><th scope="row"> {@linkplain #isPrimitiveClass() primitive class} with <a href="ClassLoader.html#binary-name">binary name</a> <i>N</i>
 960      *                                      <td style="text-align:center"> {@code Q}<em>N</em>{@code ;}
 961      * <tr><th scope="row"> {@code double}  <td style="text-align:center"> {@code D}
 962      * <tr><th scope="row"> {@code float}   <td style="text-align:center"> {@code F}
 963      * <tr><th scope="row"> {@code int}     <td style="text-align:center"> {@code I}
 964      * <tr><th scope="row"> {@code long}    <td style="text-align:center"> {@code J}
 965      * <tr><th scope="row"> {@code short}   <td style="text-align:center"> {@code S}
 966      * </tbody>
 967      * </table></blockquote>
 968      *
 969      * <p> If this {@code Class} object represents a primitive type or {@code void},
 970      * then the result is a string with the same spelling as the Java language
 971      * keyword which corresponds to the primitive type or {@code void}.
 972      *
 973      * <p> Examples:
 974      * <blockquote><pre>
 975      * String.class.getName()
 976      *     returns "java.lang.String"
 977      * byte.class.getName()
 978      *     returns "byte"
 979      * Point.class.getName()
 980      *     returns "Point"
 981      * (new Object[3]).getClass().getName()
 982      *     returns "[Ljava.lang.Object;"
 983      * (new Point[3]).getClass().getName()
 984      *     returns "[QPoint;"
 985      * (new Point.ref[3][4]).getClass().getName()
 986      *     returns "[[LPoint;"
 987      * (new int[3][4][5][6][7][8][9]).getClass().getName()
 988      *     returns "[[[[[[[I"
 989      * </pre></blockquote>
 990      *
 991      * @return  the name of the class, interface, or other entity
 992      *          represented by this {@code Class} object.
 993      * @jls 13.1 The Form of a Binary
 994      */
 995     public String getName() {
 996         String name = this.name;
 997         return name != null ? name : initClassName();
 998     }
 999 
1000     // Cache the name to reduce the number of calls into the VM.
1001     // This field would be set by VM itself during initClassName call.
1002     private transient String name;
1003     private native String initClassName();
1004 
1005     /**
1006      * Returns the class loader for the class.  Some implementations may use

1400      * primitive type or void, then its {@code final} modifier is always
1401      * {@code true} and its interface modifier is always
1402      * {@code false}. The values of its other modifiers are not determined
1403      * by this specification.
1404      *
1405      * <p> The modifier encodings are defined in section {@jvms 4.1}
1406      * of <cite>The Java Virtual Machine Specification</cite>.
1407      *
1408      * @return the {@code int} representing the modifiers for this class
1409      * @see     java.lang.reflect.Modifier
1410      * @see <a
1411      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1412      * programming language and JVM modeling in core reflection</a>
1413      * @since 1.1
1414      * @jls 8.1.1 Class Modifiers
1415      * @jls 9.1.1. Interface Modifiers
1416      */
1417     @IntrinsicCandidate
1418     public native int getModifiers();
1419 

1420     /**
1421      * Gets the signers of this class.
1422      *
1423      * @return  the signers of this class, or null if there are no signers.  In
1424      *          particular, this method returns null if this {@code Class} object represents
1425      *          a primitive type or void.
1426      * @since   1.1
1427      */
1428     public native Object[] getSigners();
1429 

1430     /**
1431      * Set the signers of this class.
1432      */
1433     native void setSigners(Object[] signers);
1434 
1435 
1436     /**
1437      * If this {@code Class} object represents a local or anonymous
1438      * class within a method, returns a {@link
1439      * java.lang.reflect.Method Method} object representing the
1440      * immediately enclosing method of the underlying class. Returns
1441      * {@code null} otherwise.
1442      *
1443      * In particular, this method returns {@code null} if the underlying
1444      * class is a local or anonymous class immediately enclosed by a class or
1445      * interface declaration, instance initializer or static initializer.
1446      *
1447      * @return the immediately enclosing method of the underlying class, if
1448      *     that class is a local or anonymous class; otherwise {@code null}.
1449      *

1797             simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1798         }
1799         return simpleName;
1800     }
1801 
1802     /**
1803      * Return an informative string for the name of this class or interface.
1804      *
1805      * @return an informative string for the name of this class or interface
1806      * @since 1.8
1807      */
1808     public String getTypeName() {
1809         if (isArray()) {
1810             try {
1811                 Class<?> cl = this;
1812                 int dimensions = 0;
1813                 do {
1814                     dimensions++;
1815                     cl = cl.getComponentType();
1816                 } while (cl.isArray());
1817                 return cl.getTypeName().concat("[]".repeat(dimensions));
1818             } catch (Throwable e) { /*FALLTHRU*/ }
1819         }
1820         if (isPrimitiveClass()) {
1821             // TODO: null-default
1822             return isPrimaryType() ? getName().concat(".ref") : getName();
1823         } else {
1824             return getName();
1825         }
1826     }
1827 
1828     /**
1829      * Returns the canonical name of the underlying class as
1830      * defined by <cite>The Java Language Specification</cite>.
1831      * Returns {@code null} if the underlying class does not have a canonical
1832      * name. Classes without canonical names include:
1833      * <ul>
1834      * <li>a {@linkplain #isLocalClass() local class}
1835      * <li>a {@linkplain #isAnonymousClass() anonymous class}
1836      * <li>a {@linkplain #isHidden() hidden class}
1837      * <li>an array whose component type does not have a canonical name</li>
1838      * </ul>
1839      *
1840      * @return the canonical name of the underlying class if it exists, and
1841      * {@code null} otherwise.
1842      * @since 1.5
1843      */
1844     public String getCanonicalName() {
1845         ReflectionData<T> rd = reflectionData();

3998                 throw new IllegalArgumentException(
3999                     getName() + " is not an enum class");
4000             directory = new HashMap<>((int)(universe.length / 0.75f) + 1);
4001             for (T constant : universe) {
4002                 directory.put(((Enum<?>)constant).name(), constant);
4003             }
4004             enumConstantDirectory = directory;
4005         }
4006         return directory;
4007     }
4008     private transient volatile Map<String, T> enumConstantDirectory;
4009 
4010     /**
4011      * Casts an object to the class or interface represented
4012      * by this {@code Class} object.
4013      *
4014      * @param obj the object to be cast
4015      * @return the object after casting, or null if obj is null
4016      *
4017      * @throws ClassCastException if the object is not
4018      * {@code null} and is not assignable to the type T.
4019      * @throws NullPointerException if this class is an {@linkplain #isValueType()
4020      * primitive value type} and the object is {@code null}
4021      *
4022      * @since 1.5
4023      */
4024     @SuppressWarnings("unchecked")
4025     @IntrinsicCandidate
4026     public T cast(Object obj) {
4027         if (isValueType() && obj == null)
4028             throw new NullPointerException(getName() + " is a primitive value type");
4029 
4030         if (obj != null && !isInstance(obj))
4031             throw new ClassCastException(cannotCastMsg(obj));
4032         return (T) obj;
4033     }
4034 
4035     private String cannotCastMsg(Object obj) {
4036         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
4037     }
4038 
4039     /**
4040      * Casts this {@code Class} object to represent a subclass of the class
4041      * represented by the specified class object.  Checks that the cast
4042      * is valid, and throws a {@code ClassCastException} if it is not.  If
4043      * this method succeeds, it always returns a reference to this {@code Class} object.
4044      *
4045      * <p>This method is useful when a client needs to "narrow" the type of
4046      * a {@code Class} object to pass it to an API that restricts the
4047      * {@code Class} objects that it is willing to accept.  A cast would
4048      * generate a compile-time warning, as the correctness of the cast
4049      * could not be checked at runtime (because generic types are implemented

4305      *
4306      * <p> If this {@code Class} object represents an interface, the return
4307      * value is an array containing objects representing the uses of interface
4308      * types to specify interfaces directly extended by the interface. The
4309      * order of the objects in the array corresponds to the order of the
4310      * interface types used in the 'extends' clause of the declaration of this
4311      * {@code Class} object.
4312      *
4313      * <p> If this {@code Class} object represents a class or interface whose
4314      * declaration does not explicitly indicate any annotated superinterfaces,
4315      * the return value is an array of length 0.
4316      *
4317      * <p> If this {@code Class} object represents either the {@code Object}
4318      * class, an array type, a primitive type, or void, the return value is an
4319      * array of length 0.
4320      *
4321      * @return an array representing the superinterfaces
4322      * @since 1.8
4323      */
4324     public AnnotatedType[] getAnnotatedInterfaces() {
4325         return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
4326     }
4327 
4328     private native Class<?> getNestHost0();
4329 
4330     /**
4331      * Returns the nest host of the <a href=#nest>nest</a> to which the class
4332      * or interface represented by this {@code Class} object belongs.
4333      * Every class and interface belongs to exactly one nest.
4334      *
4335      * If the nest host of this class or interface has previously
4336      * been determined, then this method returns the nest host.
4337      * If the nest host of this class or interface has
4338      * not previously been determined, then this method determines the nest
4339      * host using the algorithm of JVMS 5.4.4, and returns it.
4340      *
4341      * Often, a class or interface belongs to a nest consisting only of itself,
4342      * in which case this method returns {@code this} to indicate that the class
4343      * or interface is the nest host.
4344      *
4345      * <p>If this {@code Class} object represents a primitive type, an array type,

4520      * {@code void}, then the result is a field descriptor string which
4521      * is a one-letter code corresponding to a primitive type or {@code void}
4522      * ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}).
4523      *
4524      * @apiNote
4525      * This is not a strict inverse of {@link #forName};
4526      * distinct classes which share a common name but have different class loaders
4527      * will have identical descriptor strings.
4528      *
4529      * @return the descriptor string for this {@code Class} object
4530      * @jvms 4.3.2 Field Descriptors
4531      * @since 12
4532      */
4533     @Override
4534     public String descriptorString() {
4535         if (isPrimitive())
4536             return Wrapper.forPrimitiveType(this).basicTypeString();
4537 
4538         if (isArray()) {
4539             return "[" + componentType.descriptorString();
4540         }
4541         char typeDesc = isValueType() ? 'Q' : 'L';
4542         if (isHidden()) {
4543             String name = getName();
4544             int index = name.indexOf('/');
4545             return new StringBuilder(name.length() + 2)
4546                     .append(typeDesc)
4547                     .append(name.substring(0, index).replace('.', '/'))
4548                     .append('.')
4549                     .append(name, index + 1, name.length())
4550                     .append(';')
4551                     .toString();
4552         } else {
4553             String name = getName().replace('.', '/');
4554             return new StringBuilder(name.length() + 2)
4555                     .append(typeDesc)
4556                     .append(name)
4557                     .append(';')
4558                     .toString();
4559         }
4560     }
4561 
4562     /**
4563      * Returns the component type of this {@code Class}, if it describes
4564      * an array type, or {@code null} otherwise.
4565      *
4566      * @implSpec
4567      * Equivalent to {@link Class#getComponentType()}.
4568      *
4569      * @return a {@code Class} describing the component type, or {@code null}
4570      * if this {@code Class} does not describe an array type
4571      * @since 12
4572      */
4573     @Override
4574     public Class<?> componentType() {
4575         return isArray() ? componentType : null;
< prev index next >