< prev index next >

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

Print this page
rev 55127 : 8223351: [lworld] Primary mirror and nullable mirror for inline type
Reviewed-by: tbd


  45 import java.lang.reflect.Member;
  46 import java.lang.reflect.Method;
  47 import java.lang.reflect.Modifier;
  48 import java.lang.reflect.Proxy;
  49 import java.lang.reflect.Type;
  50 import java.lang.reflect.TypeVariable;
  51 import java.lang.constant.Constable;
  52 import java.net.URL;
  53 import java.security.AccessController;
  54 import java.security.PrivilegedAction;
  55 import java.util.ArrayList;
  56 import java.util.Arrays;
  57 import java.util.Collection;
  58 import java.util.HashMap;
  59 import java.util.LinkedHashMap;
  60 import java.util.LinkedHashSet;
  61 import java.util.List;
  62 import java.util.Map;
  63 import java.util.Objects;
  64 import java.util.Optional;
  65 import java.util.StringJoiner;
  66 import java.util.stream.Stream;
  67 import java.util.stream.Collectors;
  68 
  69 import jdk.internal.HotSpotIntrinsicCandidate;
  70 import jdk.internal.loader.BootLoader;
  71 import jdk.internal.loader.BuiltinClassLoader;
  72 import jdk.internal.misc.Unsafe;
  73 import jdk.internal.module.Resources;
  74 import jdk.internal.reflect.CallerSensitive;
  75 import jdk.internal.reflect.ConstantPool;
  76 import jdk.internal.reflect.Reflection;
  77 import jdk.internal.reflect.ReflectionFactory;
  78 import jdk.internal.vm.annotation.ForceInline;
  79 import sun.invoke.util.Wrapper;
  80 import sun.reflect.generics.factory.CoreReflectionFactory;
  81 import sun.reflect.generics.factory.GenericsFactory;
  82 import sun.reflect.generics.repository.ClassRepository;
  83 import sun.reflect.generics.repository.MethodRepository;
  84 import sun.reflect.generics.repository.ConstructorRepository;
  85 import sun.reflect.generics.scope.ClassScope;
  86 import sun.security.util.SecurityConstants;


 180     private Class(ClassLoader loader, Class<?> arrayComponentType) {
 181         // Initialize final field for classLoader.  The initialization value of non-null
 182         // prevents future JIT optimizations from assuming this final field is null.
 183         classLoader = loader;
 184         componentType = arrayComponentType;
 185     }
 186 
 187     /**
 188      * Converts the object to a string. The string representation is the
 189      * string "class" or "interface", followed by a space, and then by the
 190      * fully qualified name of the class in the format returned by
 191      * {@code getName}.  If this {@code Class} object represents a
 192      * primitive type, this method returns the name of the primitive type.  If
 193      * this {@code Class} object represents void this method returns
 194      * "void". If this {@code Class} object represents an array type,
 195      * this method returns "class " followed by {@code getName}.
 196      *
 197      * @return a string representation of this class object.
 198      */
 199     public String toString() {
 200         return (isValue() ? "inline " : "")
 201                + (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
 202                + getName() + (isValue() && isBoxType() ? "?" : "");
 203     }
 204 
 205     /**
 206      * Returns a string describing this {@code Class}, including
 207      * information about modifiers and type parameters.
 208      *
 209      * The string is formatted as a list of type modifiers, if any,
 210      * followed by the kind of type (empty string for primitive types
 211      * and {@code class}, {@code enum}, {@code interface}, or
 212      * <code>@</code>{@code interface}, as appropriate), followed
 213      * by the type's name, followed by an angle-bracketed
 214      * comma-separated list of the type's type parameters, if any,
 215      * including informative bounds on the type parameters, if any.
 216      *
 217      * A space is used to separate modifiers from one another and to
 218      * separate any modifiers from the kind of type. The modifiers
 219      * occur in canonical order. If there are no type parameters, the
 220      * type parameter list is elided.
 221      *
 222      * For an array type, the string starts with the type name,


 243             Class<?> component = this;
 244             int arrayDepth = 0;
 245 
 246             if (isArray()) {
 247                 do {
 248                     arrayDepth++;
 249                     component = component.getComponentType();
 250                 } while (component.isArray());
 251                 sb.append(component.getName());
 252             } else {
 253                 // Class modifiers are a superset of interface modifiers
 254                 int modifiers = getModifiers() & Modifier.classModifiers();
 255                 if (modifiers != 0) {
 256                     sb.append(Modifier.toString(modifiers));
 257                     sb.append(' ');
 258                 }
 259 
 260                 if (isAnnotation()) {
 261                     sb.append('@');
 262                 }
 263                 if (isValue()) {
 264                     sb.append("value");
 265                     sb.append(' ');
 266                 }
 267                 if (isInterface()) { // Note: all annotation types are interfaces
 268                     sb.append("interface");
 269                 } else {
 270                     if (isEnum())
 271                         sb.append("enum");
 272                     else
 273                         sb.append("class");
 274                 }
 275                 sb.append(' ');
 276                 sb.append(getName());
 277             }
 278 
 279             TypeVariable<?>[] typeparms = component.getTypeParameters();
 280             if (typeparms.length > 0) {
 281                 sb.append(Arrays.stream(typeparms)
 282                           .map(Class::typeVarBounds)
 283                           .collect(Collectors.joining(",", "<", ">")));


 345      * Returns the {@code Class} object associated with the class or
 346      * interface with the given string name, using the given class loader.
 347      * Given the fully qualified name for a class or interface (in the same
 348      * format returned by {@code getName}) this method attempts to
 349      * locate, load, and link the class or interface.  The specified class
 350      * loader is used to load the class or interface.  If the parameter
 351      * {@code loader} is null, the class is loaded through the bootstrap
 352      * class loader.  The class is initialized only if the
 353      * {@code initialize} parameter is {@code true} and if it has
 354      * not been initialized earlier.
 355      *
 356      * <p> If {@code name} denotes a primitive type or void, an attempt
 357      * will be made to locate a user-defined class in the unnamed package whose
 358      * name is {@code name}. Therefore, this method cannot be used to
 359      * obtain any of the {@code Class} objects representing primitive
 360      * types or void.
 361      *
 362      * <p> If {@code name} denotes an array class, the component type of
 363      * the array class is loaded but not initialized.
 364      *
 365      * <p> If {@code name} denotes a value class, this method returns
 366      * the {@code Class} object representing the
 367      * {@linkplain #asBoxType() box value type}.
 368      *
 369      * <p> For example, in an instance method the expression:
 370      *
 371      * <blockquote>
 372      *  {@code Class.forName("Foo")}
 373      * </blockquote>
 374      *
 375      * is equivalent to:
 376      *
 377      * <blockquote>
 378      *  {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
 379      * </blockquote>
 380      *
 381      * Note that this method throws errors related to loading, linking or
 382      * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
 383      * Java Language Specification</em>.
 384      * Note that this method does not check whether the requested class
 385      * is accessible to its caller.
 386      *
 387      * @param name       fully qualified name of the desired class
 388      * @param initialize if {@code true} the class will be initialized.


 429 
 430     /** Called after security check for system loader access checks have been made. */
 431     private static native Class<?> forName0(String name, boolean initialize,
 432                                     ClassLoader loader,
 433                                     Class<?> caller)
 434         throws ClassNotFoundException;
 435 
 436 
 437     /**
 438      * Returns the {@code Class} with the given <a href="ClassLoader.html#binary-name">
 439      * binary name</a> in the given module.
 440      *
 441      * <p> This method attempts to locate, load, and link the class or interface.
 442      * It does not run the class initializer.  If the class is not found, this
 443      * method returns {@code null}. </p>
 444      *
 445      * <p> If the class loader of the given module defines other modules and
 446      * the given name is a class defined in a different module, this method
 447      * returns {@code null} after the class is loaded. </p>
 448      *
 449      * <p> If {@code name} denotes a value class, this method returns
 450      * the {@code Class} object representing the
 451      * {@linkplain #asBoxType() box value type}. </p>
 452      *
 453      * <p> This method does not check whether the requested class is
 454      * accessible to its caller. </p>
 455      *
 456      * @apiNote
 457      * This method returns {@code null} on failure rather than
 458      * throwing a {@link ClassNotFoundException}, as is done by
 459      * the {@link #forName(String, boolean, ClassLoader)} method.
 460      * The security check is a stack-based permission check if the caller
 461      * loads a class in another module.
 462      *
 463      * @param  module   A module
 464      * @param  name     The <a href="ClassLoader.html#binary-name">binary name</a>
 465      *                  of the class
 466      * @return {@code Class} object of the given name defined in the given module;
 467      *         {@code null} if not found.
 468      *
 469      * @throws NullPointerException if the given module or name is {@code null}
 470      *
 471      * @throws LinkageError if the linkage fails
 472      *


 495             if (caller != null && caller.getModule() != module) {
 496                 // if caller is null, Class.forName is the last java frame on the stack.
 497                 // java.base has all permissions
 498                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 499             }
 500             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
 501             cl = AccessController.doPrivileged(pa);
 502         } else {
 503             cl = module.getClassLoader();
 504         }
 505 
 506         if (cl != null) {
 507             return cl.loadClass(module, name);
 508         } else {
 509             return BootLoader.loadClass(module, name);
 510         }
 511     }
 512 
 513 
 514     /**
 515      * Returns {@code true} if this class is a value class.
 516      *
 517      * @return {@code true} if this class is a value class.
 518      */
 519     public boolean isValue() {
 520         int mods = this.getModifiers();
 521         if ((mods & VALUE_TYPE) != 0) {
 522             if ((mods & (Modifier.INTERFACE | Modifier.ABSTRACT)) != 0) {
 523                 throw new InternalError("inline class can't have ACC_INTERFACE or ACC_ABSTRACT set");
 524             }
 525             if (getSuperclass() != Object.class) {
 526                 throw new InternalError("Super class of an inline class must be java.lang.Object");
 527             }
 528             return true;
 529         }
 530         return false;
 531     }
 532 
 533     /**
 534      * Returns a {@code Class} object representing the <em>box type</em>
 535      * of this class if this class is a {@linkplain #isValue() value class};
 536      * otherwise, returns this class.
 537      *
 538      * <p> A value class has two {@code Class} representations,
 539      * a null-free type or a nullable box type, that can be obtained
 540      * by calling {@link #asValueType()} or {@link #asBoxType()} method
 541      * for conversion.
 542      *
 543      * @return the box type of this class if this class is a value class;
 544      *         otherwise, this class.
 545      */
 546     @HotSpotIntrinsicCandidate
 547     public Class<T> asBoxType() {
 548         return isValue() ? boxType : this;
 549     }
 550 
 551     /**
 552      * Returns a {@code Class} object representing the <em>null-free value type</em>
 553      * of this class if this class is a {@linkplain #isValue() value class};
 554      * otherwise, returns {@code null}.
 555      *
 556      * <p> A value class has two {@code Class} representations,
 557      * a null-free type or a nullable box type, that can be obtained
 558      * by calling {@link #asValueType()} or {@link #asBoxType()} method
 559      * for conversion.
 560      *
 561      * @return the unbox value type of this class if this class is a value class;
 562      *         otherwise, {@code null}.
 563      */
 564     @HotSpotIntrinsicCandidate
 565     public Class<T> asValueType() {
 566         return isValue() ? valueType : null;
 567     }
 568 
 569     /*
 570      * Returns true if this class is a non-value class or a box value class.




 571      */
 572     boolean isBoxType() {
 573         return boxType == null || this == boxType;
 574     }
 575 
 576     // set by VM if this class is a value type
 577     private transient Class<T> boxType;
 578     private transient Class<T> valueType;

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


 618      * @throws  InstantiationException
 619      *          if this {@code Class} represents an abstract class,
 620      *          an interface, an array class, a primitive type, or void;
 621      *          or if the class has no nullary constructor;
 622      *          or if the instantiation fails for some other reason.
 623      * @throws  ExceptionInInitializerError if the initialization
 624      *          provoked by this method fails.
 625      * @throws  SecurityException
 626      *          If a security manager, <i>s</i>, is present and
 627      *          the caller's class loader is not the same as or an
 628      *          ancestor of the class loader for the current class and
 629      *          invocation of {@link SecurityManager#checkPackageAccess
 630      *          s.checkPackageAccess()} denies access to the package
 631      *          of this class.
 632      */
 633     @CallerSensitive
 634     @Deprecated(since="9")
 635     public T newInstance()
 636         throws InstantiationException, IllegalAccessException
 637     {
 638         if (this.isValue()) {
 639             throw new IllegalAccessException(
 640                 "cannot create new instance of an inline class " + this.getName());
 641         }
 642 
 643         SecurityManager sm = System.getSecurityManager();
 644         if (sm != null) {
 645             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false);
 646         }
 647 
 648         // Constructor lookup
 649         Constructor<T> tmpConstructor = cachedConstructor;
 650         if (tmpConstructor == null) {
 651             if (this == Class.class) {
 652                 throw new IllegalAccessException(
 653                     "Can not call newInstance() on the Class for java.lang.Class"
 654                 );
 655             }
 656             try {
 657                 Class<?>[] empty = {};
 658                 final Constructor<T> c = getReflectionFactory().copyConstructor(


 838      * <p> If this class object represents a primitive type or void, then the
 839      * name returned is a {@code String} equal to the Java language
 840      * keyword corresponding to the primitive type or void.
 841      *
 842      * <p> If this class object represents a class of arrays, then the internal
 843      * form of the name consists of the name of the element type preceded by
 844      * one or more '{@code [}' characters representing the depth of the array
 845      * nesting.  The encoding of element type names is as follows:
 846      *
 847      * <blockquote><table class="striped">
 848      * <caption style="display:none">Element types and encodings</caption>
 849      * <thead>
 850      * <tr><th scope="col"> Element Type <th scope="col"> Encoding
 851      * </thead>
 852      * <tbody style="text-align:left">
 853      * <tr><th scope="row"> boolean      <td style="text-align:center"> Z
 854      * <tr><th scope="row"> byte         <td style="text-align:center"> B
 855      * <tr><th scope="row"> char         <td style="text-align:center"> C
 856      * <tr><th scope="row"> class or interface
 857      *                                   <td style="text-align:center"> L<i>classname</i>;
 858      * <tr><th scope="row"> {@linkplain #asValueType() regular value class}
 859      *                                   <td style="text-align:center"> Q<i>classname</i>;
 860      * <tr><th scope="row"> double       <td style="text-align:center"> D
 861      * <tr><th scope="row"> float        <td style="text-align:center"> F
 862      * <tr><th scope="row"> int          <td style="text-align:center"> I
 863      * <tr><th scope="row"> long         <td style="text-align:center"> J
 864      * <tr><th scope="row"> short        <td style="text-align:center"> S
 865      * </tbody>
 866      * </table></blockquote>
 867      *
 868      * <p> The class or interface name <i>classname</i> is the binary name of
 869      * the class specified above.
 870      *
 871      * <p> Examples:
 872      * <blockquote><pre>
 873      * String.class.getName()
 874      *     returns "java.lang.String"
 875      * byte.class.getName()
 876      *     returns "byte"
 877      * Point.class.getName()
 878      *     returns "p.Point"
 879      * (new Object[3]).getClass().getName()
 880      *     returns "[Ljava.lang.Object;"
 881      * (new Point[3]).getClass().getName()
 882      *     returns "[QPoint;"


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


1281      *
1282      * <p> The modifier encodings are defined in <em>The Java Virtual Machine
1283      * Specification</em>, table 4.1.
1284      *
1285      * @return the {@code int} representing the modifiers for this class
1286      * @see     java.lang.reflect.Modifier
1287      * @since 1.1
1288      */
1289     @HotSpotIntrinsicCandidate
1290     public native int getModifiers();
1291 
1292     /**
1293      * Gets the signers of this class.
1294      *
1295      * @return  the signers of this class, or null if there are no signers.  In
1296      *          particular, this method returns null if this object represents
1297      *          a primitive type or void.
1298      * @since   1.1
1299      */
1300     public Object[] getSigners() {
1301         Class<?> c = (isValue() && !isBoxType()) ? asBoxType() : this;
1302         return c.getSigners0();
1303     }
1304 
1305     private native Object[] getSigners0();
1306 
1307     /**
1308      * Set the signers of this class.
1309      */
1310     void setSigners(Object[] signers) {
1311         Class<?> c = (isValue() && !isBoxType()) ? asBoxType() : this;
1312         c.setSigners0(signers);
1313     }
1314 
1315     native void setSigners0(Object[] signers);
1316 
1317 
1318     /**
1319      * If this {@code Class} object represents a local or anonymous
1320      * class within a method, returns a {@link
1321      * java.lang.reflect.Method Method} object representing the
1322      * immediately enclosing method of the underlying class. Returns
1323      * {@code null} otherwise.
1324      *
1325      * In particular, this method returns {@code null} if the underlying
1326      * class is a local or anonymous class immediately enclosed by a type
1327      * declaration, instance initializer or static initializer.
1328      *
1329      * @return the immediately enclosing method of the underlying class, if
1330      *     that class is a local or anonymous class; otherwise {@code null}.
1331      *


1633 
1634         if (enclosingCandidate != null) {
1635             SecurityManager sm = System.getSecurityManager();
1636             if (sm != null) {
1637                 enclosingCandidate.checkPackageAccess(sm,
1638                     ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
1639             }
1640         }
1641         return enclosingCandidate;
1642     }
1643 
1644     /**
1645      * Returns the simple name of the underlying class as given in the
1646      * source code. Returns an empty string if the underlying class is
1647      * anonymous.
1648      *
1649      * <p>The simple name of an array is the simple name of the
1650      * component type with "[]" appended.  In particular the simple
1651      * name of an array whose component type is anonymous is "[]".
1652      *
1653      * <p>The simple name of a value type is the simple name of
1654      * this class with {@code ".box"} appended.
1655      *
1656      * @return the simple name of the underlying class
1657      * @since 1.5
1658      */
1659     public String getSimpleName() {
1660         ReflectionData<T> rd = reflectionData();
1661         String simpleName = rd.simpleName;
1662         if (simpleName == null) {
1663             rd.simpleName = simpleName = getSimpleName0();
1664         }
1665         return simpleName;
1666     }
1667 
1668     private String getSimpleName0() {
1669         if (isArray()) {
1670             return getComponentType().getSimpleName() + "[]";
1671         }
1672         String simpleName = getSimpleBinaryName();
1673         if (simpleName == null) { // top level class
1674             simpleName = getName();
1675             simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1676         }
1677         return isValue() && isBoxType() ? simpleName + ".box" : simpleName;
1678     }
1679 
1680     /**
1681      * Return an informative string for the name of this type.
1682      *
1683      * @return an informative string for the name of this type
1684      * @since 1.8
1685      */
1686     public String getTypeName() {
1687         if (isArray()) {
1688             try {
1689                 Class<?> cl = this;
1690                 int dimensions = 0;
1691                 do {
1692                     dimensions++;
1693                     cl = cl.getComponentType();
1694                 } while (cl.isArray());
1695                 StringBuilder sb = new StringBuilder();
1696                 sb.append(cl.getTypeName());
1697                 for (int i = 0; i < dimensions; i++) {
1698                     sb.append("[]");
1699                 }
1700                 return sb.toString();
1701             } catch (Throwable e) { /*FALLTHRU*/ }
1702         }
1703         // ## append "/box" to box value type instead?
1704         return isBoxType() ? getName() : getName() + "/val";
1705     }
1706 
1707     /**
1708      * Returns the canonical name of the underlying class as
1709      * defined by the Java Language Specification.  Returns null if
1710      * the underlying class does not have a canonical name (i.e., if
1711      * it is a local or anonymous class or an array whose component
1712      * type does not have a canonical name).
1713      * @return the canonical name of the underlying class if it exists, and
1714      * {@code null} otherwise.
1715      * @since 1.5
1716      */
1717     public String getCanonicalName() {
1718         ReflectionData<T> rd = reflectionData();
1719         String canonicalName = rd.canonicalName;
1720         if (canonicalName == null) {
1721             rd.canonicalName = canonicalName = getCanonicalName0();
1722         }
1723         return canonicalName == ReflectionData.NULL_SENTINEL? null : canonicalName;
1724     }


3509         ReflectionFactory fact = getReflectionFactory();
3510         for (int i = 0; i < out.length; i++) {
3511             out[i] = fact.copyConstructor(out[i]);
3512         }
3513         return out;
3514     }
3515 
3516     private native Field[]       getDeclaredFields0(boolean publicOnly);
3517     private native Method[]      getDeclaredMethods0(boolean publicOnly);
3518     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3519     private native Class<?>[]   getDeclaredClasses0();
3520 
3521     /**
3522      * Helper method to get the method name from arguments.
3523      */
3524     private String methodToString(String name, Class<?>[] argTypes) {
3525         StringBuilder sb = new StringBuilder();
3526         sb.append(getName() + "." + name + "(");
3527         if (argTypes != null) {
3528             sb.append(Arrays.stream(argTypes)
3529                       .map(c -> (c == null) ? "null" : c.getName())
3530                       .collect(Collectors.joining(",")));
3531         }
3532         sb.append(")");
3533         return sb.toString();
3534     }
3535 








3536     /** use serialVersionUID from JDK 1.1 for interoperability */
3537     private static final long serialVersionUID = 3206093459760846163L;
3538 
3539 
3540     /**
3541      * Class Class is special cased within the Serialization Stream Protocol.
3542      *
3543      * A Class instance is written initially into an ObjectOutputStream in the
3544      * following format:
3545      * <pre>
3546      *      {@code TC_CLASS} ClassDescriptor
3547      *      A ClassDescriptor is a special cased serialization of
3548      *      a {@code java.io.ObjectStreamClass} instance.
3549      * </pre>
3550      * A new handle is generated for the initial time the class descriptor
3551      * is written into the stream. Future references to the class descriptor
3552      * are written as references to the initial class descriptor instance.
3553      *
3554      * @see java.io.ObjectStreamClass
3555      */


3690                     getName() + " is not an enum type");
3691             directory = new HashMap<>((int)(universe.length / 0.75f) + 1);
3692             for (T constant : universe) {
3693                 directory.put(((Enum<?>)constant).name(), constant);
3694             }
3695             enumConstantDirectory = directory;
3696         }
3697         return directory;
3698     }
3699     private transient volatile Map<String, T> enumConstantDirectory;
3700 
3701     /**
3702      * Casts an object to the class or interface represented
3703      * by this {@code Class} object.
3704      *
3705      * @param obj the object to be cast
3706      * @return the object after casting, or null if obj is null
3707      *
3708      * @throws ClassCastException if the object is not
3709      * {@code null} and is not assignable to the type T.
3710      * @throws NullPointerException if this class is a {@linkplain #asValueType()
3711      * null-free value class} and the object is {@code null}
3712      *
3713      * @since 1.5
3714      */
3715     @SuppressWarnings("unchecked")
3716     @HotSpotIntrinsicCandidate
3717     public T cast(Object obj) {
3718         if (isValue() && !isBoxType() && obj == null)
3719             throw new NullPointerException(getName() + " is non-nullable value class");
3720 
3721         if (obj != null && !isInstance(obj))
3722             throw new ClassCastException(cannotCastMsg(obj));
3723         return (T) obj;
3724     }
3725 
3726     private String cannotCastMsg(Object obj) {
3727         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3728     }
3729 
3730     /**
3731      * Casts this {@code Class} object to represent a subclass of the class
3732      * represented by the specified class object.  Checks that the cast
3733      * is valid, and throws a {@code ClassCastException} if it is not.  If
3734      * this method succeeds, it always returns a reference to this class object.
3735      *
3736      * <p>This method is useful when a client needs to "narrow" the type of
3737      * a {@code Class} object to pass it to an API that restricts the
3738      * {@code Class} objects that it is willing to accept.  A cast would
3739      * generate a compile-time warning, as the correctness of the cast




  45 import java.lang.reflect.Member;
  46 import java.lang.reflect.Method;
  47 import java.lang.reflect.Modifier;
  48 import java.lang.reflect.Proxy;
  49 import java.lang.reflect.Type;
  50 import java.lang.reflect.TypeVariable;
  51 import java.lang.constant.Constable;
  52 import java.net.URL;
  53 import java.security.AccessController;
  54 import java.security.PrivilegedAction;
  55 import java.util.ArrayList;
  56 import java.util.Arrays;
  57 import java.util.Collection;
  58 import java.util.HashMap;
  59 import java.util.LinkedHashMap;
  60 import java.util.LinkedHashSet;
  61 import java.util.List;
  62 import java.util.Map;
  63 import java.util.Objects;
  64 import java.util.Optional;


  65 import java.util.stream.Collectors;
  66 
  67 import jdk.internal.HotSpotIntrinsicCandidate;
  68 import jdk.internal.loader.BootLoader;
  69 import jdk.internal.loader.BuiltinClassLoader;
  70 import jdk.internal.misc.Unsafe;
  71 import jdk.internal.module.Resources;
  72 import jdk.internal.reflect.CallerSensitive;
  73 import jdk.internal.reflect.ConstantPool;
  74 import jdk.internal.reflect.Reflection;
  75 import jdk.internal.reflect.ReflectionFactory;
  76 import jdk.internal.vm.annotation.ForceInline;
  77 import sun.invoke.util.Wrapper;
  78 import sun.reflect.generics.factory.CoreReflectionFactory;
  79 import sun.reflect.generics.factory.GenericsFactory;
  80 import sun.reflect.generics.repository.ClassRepository;
  81 import sun.reflect.generics.repository.MethodRepository;
  82 import sun.reflect.generics.repository.ConstructorRepository;
  83 import sun.reflect.generics.scope.ClassScope;
  84 import sun.security.util.SecurityConstants;


 178     private Class(ClassLoader loader, Class<?> arrayComponentType) {
 179         // Initialize final field for classLoader.  The initialization value of non-null
 180         // prevents future JIT optimizations from assuming this final field is null.
 181         classLoader = loader;
 182         componentType = arrayComponentType;
 183     }
 184 
 185     /**
 186      * Converts the object to a string. The string representation is the
 187      * string "class" or "interface", followed by a space, and then by the
 188      * fully qualified name of the class in the format returned by
 189      * {@code getName}.  If this {@code Class} object represents a
 190      * primitive type, this method returns the name of the primitive type.  If
 191      * this {@code Class} object represents void this method returns
 192      * "void". If this {@code Class} object represents an array type,
 193      * this method returns "class " followed by {@code getName}.
 194      *
 195      * @return a string representation of this class object.
 196      */
 197     public String toString() {
 198         return (isInlineClass() ? "inline " : "")
 199                + (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
 200                + getName() + (isInlineClass() && isNullableType() ? "?" : "");
 201     }
 202 
 203     /**
 204      * Returns a string describing this {@code Class}, including
 205      * information about modifiers and type parameters.
 206      *
 207      * The string is formatted as a list of type modifiers, if any,
 208      * followed by the kind of type (empty string for primitive types
 209      * and {@code class}, {@code enum}, {@code interface}, or
 210      * <code>@</code>{@code interface}, as appropriate), followed
 211      * by the type's name, followed by an angle-bracketed
 212      * comma-separated list of the type's type parameters, if any,
 213      * including informative bounds on the type parameters, if any.
 214      *
 215      * A space is used to separate modifiers from one another and to
 216      * separate any modifiers from the kind of type. The modifiers
 217      * occur in canonical order. If there are no type parameters, the
 218      * type parameter list is elided.
 219      *
 220      * For an array type, the string starts with the type name,


 241             Class<?> component = this;
 242             int arrayDepth = 0;
 243 
 244             if (isArray()) {
 245                 do {
 246                     arrayDepth++;
 247                     component = component.getComponentType();
 248                 } while (component.isArray());
 249                 sb.append(component.getName());
 250             } else {
 251                 // Class modifiers are a superset of interface modifiers
 252                 int modifiers = getModifiers() & Modifier.classModifiers();
 253                 if (modifiers != 0) {
 254                     sb.append(Modifier.toString(modifiers));
 255                     sb.append(' ');
 256                 }
 257 
 258                 if (isAnnotation()) {
 259                     sb.append('@');
 260                 }
 261                 if (isInlineClass()) {
 262                     sb.append("value");
 263                     sb.append(' ');
 264                 }
 265                 if (isInterface()) { // Note: all annotation types are interfaces
 266                     sb.append("interface");
 267                 } else {
 268                     if (isEnum())
 269                         sb.append("enum");
 270                     else
 271                         sb.append("class");
 272                 }
 273                 sb.append(' ');
 274                 sb.append(getName());
 275             }
 276 
 277             TypeVariable<?>[] typeparms = component.getTypeParameters();
 278             if (typeparms.length > 0) {
 279                 sb.append(Arrays.stream(typeparms)
 280                           .map(Class::typeVarBounds)
 281                           .collect(Collectors.joining(",", "<", ">")));


 343      * Returns the {@code Class} object associated with the class or
 344      * interface with the given string name, using the given class loader.
 345      * Given the fully qualified name for a class or interface (in the same
 346      * format returned by {@code getName}) this method attempts to
 347      * locate, load, and link the class or interface.  The specified class
 348      * loader is used to load the class or interface.  If the parameter
 349      * {@code loader} is null, the class is loaded through the bootstrap
 350      * class loader.  The class is initialized only if the
 351      * {@code initialize} parameter is {@code true} and if it has
 352      * not been initialized earlier.
 353      *
 354      * <p> If {@code name} denotes a primitive type or void, an attempt
 355      * will be made to locate a user-defined class in the unnamed package whose
 356      * name is {@code name}. Therefore, this method cannot be used to
 357      * obtain any of the {@code Class} objects representing primitive
 358      * types or void.
 359      *
 360      * <p> If {@code name} denotes an array class, the component type of
 361      * the array class is loaded but not initialized.
 362      *




 363      * <p> For example, in an instance method the expression:
 364      *
 365      * <blockquote>
 366      *  {@code Class.forName("Foo")}
 367      * </blockquote>
 368      *
 369      * is equivalent to:
 370      *
 371      * <blockquote>
 372      *  {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
 373      * </blockquote>
 374      *
 375      * Note that this method throws errors related to loading, linking or
 376      * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
 377      * Java Language Specification</em>.
 378      * Note that this method does not check whether the requested class
 379      * is accessible to its caller.
 380      *
 381      * @param name       fully qualified name of the desired class
 382      * @param initialize if {@code true} the class will be initialized.


 423 
 424     /** Called after security check for system loader access checks have been made. */
 425     private static native Class<?> forName0(String name, boolean initialize,
 426                                     ClassLoader loader,
 427                                     Class<?> caller)
 428         throws ClassNotFoundException;
 429 
 430 
 431     /**
 432      * Returns the {@code Class} with the given <a href="ClassLoader.html#binary-name">
 433      * binary name</a> in the given module.
 434      *
 435      * <p> This method attempts to locate, load, and link the class or interface.
 436      * It does not run the class initializer.  If the class is not found, this
 437      * method returns {@code null}. </p>
 438      *
 439      * <p> If the class loader of the given module defines other modules and
 440      * the given name is a class defined in a different module, this method
 441      * returns {@code null} after the class is loaded. </p>
 442      *




 443      * <p> This method does not check whether the requested class is
 444      * accessible to its caller. </p>
 445      *
 446      * @apiNote
 447      * This method returns {@code null} on failure rather than
 448      * throwing a {@link ClassNotFoundException}, as is done by
 449      * the {@link #forName(String, boolean, ClassLoader)} method.
 450      * The security check is a stack-based permission check if the caller
 451      * loads a class in another module.
 452      *
 453      * @param  module   A module
 454      * @param  name     The <a href="ClassLoader.html#binary-name">binary name</a>
 455      *                  of the class
 456      * @return {@code Class} object of the given name defined in the given module;
 457      *         {@code null} if not found.
 458      *
 459      * @throws NullPointerException if the given module or name is {@code null}
 460      *
 461      * @throws LinkageError if the linkage fails
 462      *


 485             if (caller != null && caller.getModule() != module) {
 486                 // if caller is null, Class.forName is the last java frame on the stack.
 487                 // java.base has all permissions
 488                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 489             }
 490             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
 491             cl = AccessController.doPrivileged(pa);
 492         } else {
 493             cl = module.getClassLoader();
 494         }
 495 
 496         if (cl != null) {
 497             return cl.loadClass(module, name);
 498         } else {
 499             return BootLoader.loadClass(module, name);
 500         }
 501     }
 502 
 503 
 504     /**
 505      * Returns {@code true} if this class is an inline class.
 506      *
 507      * @return {@code true} if this class is an inline class.
 508      */
 509     public boolean isInlineClass() {
 510         int mods = this.getModifiers();
 511         if ((mods & VALUE_TYPE) != 0) {
 512             if ((mods & (Modifier.INTERFACE | Modifier.ABSTRACT)) != 0) {
 513                 throw new InternalError("inline class can't have ACC_INTERFACE or ACC_ABSTRACT set");
 514             }
 515             if (getSuperclass() != Object.class) {
 516                 throw new InternalError("Super class of an inline class must be java.lang.Object");
 517             }
 518             return true;
 519         }
 520         return false;
 521     }
 522 
 523     /**
 524      * Returns a {@code Class} object representing the <em>nullable-projection</em>
 525      * type if this class is an {@linkplain #isInlineClass() inline class};
 526      * otherwise, returns this class.
 527      *
 528      * <p> An inline class has two {@code Class} representations,
 529      * the zero-default inline class and the nullable-projection type
 530      * that can be obtained by calling {@link #asPrimaryType()} or
 531      * {@link #asNullableType()} method respectively.
 532      *
 533      * @return the {@code Class} object representing the nullable-projection of
 534      *         this class if this class is an inline class; otherwise, this class.
 535      */
 536     @HotSpotIntrinsicCandidate
 537     public Class<T> asNullableType() {
 538         return isInlineClass() ? nullableType : this;
 539     }
 540 
 541     /**
 542      * Returns a {@code Class} object representing this <em>zero-default</em>
 543      * inline class if this class is an {@linkplain #isInlineClass() inline class};
 544      * otherwise, returns this class.
 545      *
 546      * <p> An inline class has two {@code Class} representations,
 547      * the zero-default inline class and the nullable-projection type
 548      * that can be obtained by calling {@link #asPrimaryType()} or
 549      * {@link #asNullableType()} method respectively.
 550      *
 551      * @return the {@code Class} object representing the zero-default inline class
 552      *         if this class is an inline class; otherwise, this class.
 553      */
 554     @HotSpotIntrinsicCandidate
 555     public Class<T> asPrimaryType() {
 556         return isInlineClass() ? inlineType : this;
 557     }
 558 
 559     /**
 560      * Returns {@code true} if this class is a nullable type.  A nullable type
 561      * can be a reference class or interface and
 562      * a {@linkplain #asNullableType nullable-projection type}.
 563      *
 564      * @return {@code true} if this class is a nullable type.
 565      */
 566     public boolean isNullableType() {
 567         return nullableType == null || this == nullableType;
 568     }
 569 
 570     // set by VM if this class is an inline type
 571     // otherwise, these two fields are null
 572     private transient Class<T> inlineType;
 573     private transient Class<T> nullableType;
 574 
 575     /**
 576      * Creates a new instance of the class represented by this {@code Class}
 577      * object.  The class is instantiated as if by a {@code new}
 578      * expression with an empty argument list.  The class is initialized if it
 579      * has not already been initialized.
 580      *
 581      * @deprecated This method propagates any exception thrown by the
 582      * nullary constructor, including a checked exception.  Use of
 583      * this method effectively bypasses the compile-time exception
 584      * checking that would otherwise be performed by the compiler.
 585      * The {@link
 586      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
 587      * Constructor.newInstance} method avoids this problem by wrapping
 588      * any exception thrown by the constructor in a (checked) {@link
 589      * java.lang.reflect.InvocationTargetException}.
 590      *
 591      * <p>The call
 592      *
 593      * <pre>{@code


 613      * @throws  InstantiationException
 614      *          if this {@code Class} represents an abstract class,
 615      *          an interface, an array class, a primitive type, or void;
 616      *          or if the class has no nullary constructor;
 617      *          or if the instantiation fails for some other reason.
 618      * @throws  ExceptionInInitializerError if the initialization
 619      *          provoked by this method fails.
 620      * @throws  SecurityException
 621      *          If a security manager, <i>s</i>, is present and
 622      *          the caller's class loader is not the same as or an
 623      *          ancestor of the class loader for the current class and
 624      *          invocation of {@link SecurityManager#checkPackageAccess
 625      *          s.checkPackageAccess()} denies access to the package
 626      *          of this class.
 627      */
 628     @CallerSensitive
 629     @Deprecated(since="9")
 630     public T newInstance()
 631         throws InstantiationException, IllegalAccessException
 632     {
 633         if (this.isInlineClass()) {
 634             throw new IllegalAccessException(
 635                 "cannot create new instance of an inline class " + this.getName());
 636         }
 637 
 638         SecurityManager sm = System.getSecurityManager();
 639         if (sm != null) {
 640             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false);
 641         }
 642 
 643         // Constructor lookup
 644         Constructor<T> tmpConstructor = cachedConstructor;
 645         if (tmpConstructor == null) {
 646             if (this == Class.class) {
 647                 throw new IllegalAccessException(
 648                     "Can not call newInstance() on the Class for java.lang.Class"
 649                 );
 650             }
 651             try {
 652                 Class<?>[] empty = {};
 653                 final Constructor<T> c = getReflectionFactory().copyConstructor(


 833      * <p> If this class object represents a primitive type or void, then the
 834      * name returned is a {@code String} equal to the Java language
 835      * keyword corresponding to the primitive type or void.
 836      *
 837      * <p> If this class object represents a class of arrays, then the internal
 838      * form of the name consists of the name of the element type preceded by
 839      * one or more '{@code [}' characters representing the depth of the array
 840      * nesting.  The encoding of element type names is as follows:
 841      *
 842      * <blockquote><table class="striped">
 843      * <caption style="display:none">Element types and encodings</caption>
 844      * <thead>
 845      * <tr><th scope="col"> Element Type <th scope="col"> Encoding
 846      * </thead>
 847      * <tbody style="text-align:left">
 848      * <tr><th scope="row"> boolean      <td style="text-align:center"> Z
 849      * <tr><th scope="row"> byte         <td style="text-align:center"> B
 850      * <tr><th scope="row"> char         <td style="text-align:center"> C
 851      * <tr><th scope="row"> class or interface
 852      *                                   <td style="text-align:center"> L<i>classname</i>;
 853      * <tr><th scope="row"> {@linkplain #asPrimaryType() inline class}
 854      *                                   <td style="text-align:center"> Q<i>classname</i>;
 855      * <tr><th scope="row"> double       <td style="text-align:center"> D
 856      * <tr><th scope="row"> float        <td style="text-align:center"> F
 857      * <tr><th scope="row"> int          <td style="text-align:center"> I
 858      * <tr><th scope="row"> long         <td style="text-align:center"> J
 859      * <tr><th scope="row"> short        <td style="text-align:center"> S
 860      * </tbody>
 861      * </table></blockquote>
 862      *
 863      * <p> The class or interface name <i>classname</i> is the binary name of
 864      * the class specified above.
 865      *
 866      * <p> Examples:
 867      * <blockquote><pre>
 868      * String.class.getName()
 869      *     returns "java.lang.String"
 870      * byte.class.getName()
 871      *     returns "byte"
 872      * Point.class.getName()
 873      *     returns "Point"
 874      * (new Object[3]).getClass().getName()
 875      *     returns "[Ljava.lang.Object;"
 876      * (new Point[3]).getClass().getName()
 877      *     returns "[QPoint;"
 878      * (new Point?[3][4]).getClass().getName()
 879      *     returns "[[LPoint;"
 880      * (new int[3][4][5][6][7][8][9]).getClass().getName()
 881      *     returns "[[[[[[[I"
 882      * </pre></blockquote>
 883      *
 884      * @return  the name of the class or interface
 885      *          represented by this object.
 886      */
 887     public String getName() {
 888         String name = this.name;
 889         return name != null ? name : initClassName();
 890     }
 891 
 892     // Cache the name to reduce the number of calls into the VM.
 893     // This field would be set by VM itself during initClassName call.
 894     private transient String name;
 895     private native String initClassName();
 896 
 897     /**
 898      * Returns the class loader for the class.  Some implementations may use
 899      * null to represent the bootstrap class loader. This method will return


1278      *
1279      * <p> The modifier encodings are defined in <em>The Java Virtual Machine
1280      * Specification</em>, table 4.1.
1281      *
1282      * @return the {@code int} representing the modifiers for this class
1283      * @see     java.lang.reflect.Modifier
1284      * @since 1.1
1285      */
1286     @HotSpotIntrinsicCandidate
1287     public native int getModifiers();
1288 
1289     /**
1290      * Gets the signers of this class.
1291      *
1292      * @return  the signers of this class, or null if there are no signers.  In
1293      *          particular, this method returns null if this object represents
1294      *          a primitive type or void.
1295      * @since   1.1
1296      */
1297     public Object[] getSigners() {
1298         Class<?> c = isInlineClass() && isNullableType() ? asPrimaryType() : this;
1299         return c.getSigners0();
1300     }
1301 
1302     private native Object[] getSigners0();
1303 
1304     /**
1305      * Set the signers of this class.
1306      */
1307     void setSigners(Object[] signers) {
1308         Class<?> c = isInlineClass() && isNullableType() ? asPrimaryType() : this;
1309         c.setSigners0(signers);
1310     }
1311 
1312     native void setSigners0(Object[] signers);
1313 
1314 
1315     /**
1316      * If this {@code Class} object represents a local or anonymous
1317      * class within a method, returns a {@link
1318      * java.lang.reflect.Method Method} object representing the
1319      * immediately enclosing method of the underlying class. Returns
1320      * {@code null} otherwise.
1321      *
1322      * In particular, this method returns {@code null} if the underlying
1323      * class is a local or anonymous class immediately enclosed by a type
1324      * declaration, instance initializer or static initializer.
1325      *
1326      * @return the immediately enclosing method of the underlying class, if
1327      *     that class is a local or anonymous class; otherwise {@code null}.
1328      *


1630 
1631         if (enclosingCandidate != null) {
1632             SecurityManager sm = System.getSecurityManager();
1633             if (sm != null) {
1634                 enclosingCandidate.checkPackageAccess(sm,
1635                     ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
1636             }
1637         }
1638         return enclosingCandidate;
1639     }
1640 
1641     /**
1642      * Returns the simple name of the underlying class as given in the
1643      * source code. Returns an empty string if the underlying class is
1644      * anonymous.
1645      *
1646      * <p>The simple name of an array is the simple name of the
1647      * component type with "[]" appended.  In particular the simple
1648      * name of an array whose component type is anonymous is "[]".
1649      *



1650      * @return the simple name of the underlying class
1651      * @since 1.5
1652      */
1653     public String getSimpleName() {
1654         ReflectionData<T> rd = reflectionData();
1655         String simpleName = rd.simpleName;
1656         if (simpleName == null) {
1657             rd.simpleName = simpleName = getSimpleName0();
1658         }
1659         return simpleName;
1660     }
1661 
1662     private String getSimpleName0() {
1663         if (isArray()) {
1664             return getComponentType().getSimpleName() + "[]";
1665         }
1666         String simpleName = getSimpleBinaryName();
1667         if (simpleName == null) { // top level class
1668             simpleName = getName();
1669             simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1670         }
1671         return simpleName;
1672     }
1673 
1674     /**
1675      * Return an informative string for the name of this type.
1676      *
1677      * @return an informative string for the name of this type
1678      * @since 1.8
1679      */
1680     public String getTypeName() {
1681         if (isArray()) {
1682             try {
1683                 Class<?> cl = this;
1684                 int dimensions = 0;
1685                 do {
1686                     dimensions++;
1687                     cl = cl.getComponentType();
1688                 } while (cl.isArray());
1689                 StringBuilder sb = new StringBuilder();
1690                 sb.append(cl.getTypeName());
1691                 for (int i = 0; i < dimensions; i++) {
1692                     sb.append("[]");
1693                 }
1694                 return sb.toString();
1695             } catch (Throwable e) { /*FALLTHRU*/ }
1696         }
1697         return toTypeName();

1698     }
1699 
1700     /**
1701      * Returns the canonical name of the underlying class as
1702      * defined by the Java Language Specification.  Returns null if
1703      * the underlying class does not have a canonical name (i.e., if
1704      * it is a local or anonymous class or an array whose component
1705      * type does not have a canonical name).
1706      * @return the canonical name of the underlying class if it exists, and
1707      * {@code null} otherwise.
1708      * @since 1.5
1709      */
1710     public String getCanonicalName() {
1711         ReflectionData<T> rd = reflectionData();
1712         String canonicalName = rd.canonicalName;
1713         if (canonicalName == null) {
1714             rd.canonicalName = canonicalName = getCanonicalName0();
1715         }
1716         return canonicalName == ReflectionData.NULL_SENTINEL? null : canonicalName;
1717     }


3502         ReflectionFactory fact = getReflectionFactory();
3503         for (int i = 0; i < out.length; i++) {
3504             out[i] = fact.copyConstructor(out[i]);
3505         }
3506         return out;
3507     }
3508 
3509     private native Field[]       getDeclaredFields0(boolean publicOnly);
3510     private native Method[]      getDeclaredMethods0(boolean publicOnly);
3511     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3512     private native Class<?>[]   getDeclaredClasses0();
3513 
3514     /**
3515      * Helper method to get the method name from arguments.
3516      */
3517     private String methodToString(String name, Class<?>[] argTypes) {
3518         StringBuilder sb = new StringBuilder();
3519         sb.append(getName() + "." + name + "(");
3520         if (argTypes != null) {
3521             sb.append(Arrays.stream(argTypes)
3522                       .map(c -> (c == null) ? "null" : c.toTypeName())
3523                       .collect(Collectors.joining(",")));
3524         }
3525         sb.append(")");
3526         return sb.toString();
3527     }
3528 
3529     /*
3530      * Returns the class name appended with "?" if it is the nullable projection
3531      * of an inline class.
3532      */
3533     private String toTypeName() {
3534         return isInlineClass() && isNullableType() ? getName() + "?" : getName();
3535     }
3536 
3537     /** use serialVersionUID from JDK 1.1 for interoperability */
3538     private static final long serialVersionUID = 3206093459760846163L;
3539 
3540 
3541     /**
3542      * Class Class is special cased within the Serialization Stream Protocol.
3543      *
3544      * A Class instance is written initially into an ObjectOutputStream in the
3545      * following format:
3546      * <pre>
3547      *      {@code TC_CLASS} ClassDescriptor
3548      *      A ClassDescriptor is a special cased serialization of
3549      *      a {@code java.io.ObjectStreamClass} instance.
3550      * </pre>
3551      * A new handle is generated for the initial time the class descriptor
3552      * is written into the stream. Future references to the class descriptor
3553      * are written as references to the initial class descriptor instance.
3554      *
3555      * @see java.io.ObjectStreamClass
3556      */


3691                     getName() + " is not an enum type");
3692             directory = new HashMap<>((int)(universe.length / 0.75f) + 1);
3693             for (T constant : universe) {
3694                 directory.put(((Enum<?>)constant).name(), constant);
3695             }
3696             enumConstantDirectory = directory;
3697         }
3698         return directory;
3699     }
3700     private transient volatile Map<String, T> enumConstantDirectory;
3701 
3702     /**
3703      * Casts an object to the class or interface represented
3704      * by this {@code Class} object.
3705      *
3706      * @param obj the object to be cast
3707      * @return the object after casting, or null if obj is null
3708      *
3709      * @throws ClassCastException if the object is not
3710      * {@code null} and is not assignable to the type T.
3711      * @throws NullPointerException if this class is an {@linkplain #asPrimaryType()
3712      * inline class} and the object is {@code null}
3713      *
3714      * @since 1.5
3715      */
3716     @SuppressWarnings("unchecked")
3717     @HotSpotIntrinsicCandidate
3718     public T cast(Object obj) {
3719         if (isInlineClass() && !isNullableType() && obj == null)
3720             throw new NullPointerException(getName() + " is an inline class");
3721 
3722         if (obj != null && !isInstance(obj))
3723             throw new ClassCastException(cannotCastMsg(obj));
3724         return (T) obj;
3725     }
3726 
3727     private String cannotCastMsg(Object obj) {
3728         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3729     }
3730 
3731     /**
3732      * Casts this {@code Class} object to represent a subclass of the class
3733      * represented by the specified class object.  Checks that the cast
3734      * is valid, and throws a {@code ClassCastException} if it is not.  If
3735      * this method succeeds, it always returns a reference to this class object.
3736      *
3737      * <p>This method is useful when a client needs to "narrow" the type of
3738      * a {@code Class} object to pass it to an API that restricts the
3739      * {@code Class} objects that it is willing to accept.  A cast would
3740      * generate a compile-time warning, as the correctness of the cast


< prev index next >