< prev index next >

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

Print this page

  52 import java.lang.reflect.Type;
  53 import java.lang.reflect.TypeVariable;
  54 import java.lang.constant.Constable;
  55 import java.net.URL;
  56 import java.security.AccessController;
  57 import java.security.PrivilegedAction;
  58 import java.util.ArrayList;
  59 import java.util.Arrays;
  60 import java.util.Collection;
  61 import java.util.HashMap;
  62 import java.util.HashSet;
  63 import java.util.LinkedHashMap;
  64 import java.util.LinkedHashSet;
  65 import java.util.List;
  66 import java.util.Map;
  67 import java.util.Objects;
  68 import java.util.Optional;
  69 import java.util.Set;
  70 import java.util.stream.Collectors;
  71 

  72 import jdk.internal.loader.BootLoader;
  73 import jdk.internal.loader.BuiltinClassLoader;
  74 import jdk.internal.misc.Unsafe;
  75 import jdk.internal.module.Resources;
  76 import jdk.internal.reflect.CallerSensitive;
  77 import jdk.internal.reflect.CallerSensitiveAdapter;
  78 import jdk.internal.reflect.ConstantPool;
  79 import jdk.internal.reflect.Reflection;
  80 import jdk.internal.reflect.ReflectionFactory;

  81 import jdk.internal.vm.annotation.ForceInline;
  82 import jdk.internal.vm.annotation.IntrinsicCandidate;
  83 import sun.invoke.util.Wrapper;
  84 import sun.reflect.generics.factory.CoreReflectionFactory;
  85 import sun.reflect.generics.factory.GenericsFactory;
  86 import sun.reflect.generics.repository.ClassRepository;
  87 import sun.reflect.generics.repository.MethodRepository;
  88 import sun.reflect.generics.repository.ConstructorRepository;
  89 import sun.reflect.generics.scope.ClassScope;
  90 import sun.security.util.SecurityConstants;
  91 import sun.reflect.annotation.*;
  92 import sun.reflect.misc.ReflectUtil;
  93 
  94 /**
  95  * Instances of the class {@code Class} represent classes and
  96  * interfaces in a running Java application. An enum class and a record
  97  * class are kinds of class; an annotation interface is a kind of
  98  * interface. Every array also belongs to a class that is reflected as
  99  * a {@code Class} object that is shared by all arrays with the same
 100  * element type and number of dimensions.  The primitive Java types

 183  * A hidden class or interface is never an array class, but may be
 184  * the element type of an array. In all other respects, the fact that
 185  * a class or interface is hidden has no bearing on the characteristics
 186  * exposed by the methods of class {@code Class}.
 187  *
 188  * @param <T> the type of the class modeled by this {@code Class}
 189  * object.  For example, the type of {@code String.class} is {@code
 190  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
 191  * unknown.
 192  *
 193  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
 194  * @since   1.0
 195  * @jls 15.8.2 Class Literals
 196  */
 197 public final class Class<T> implements java.io.Serializable,
 198                               GenericDeclaration,
 199                               Type,
 200                               AnnotatedElement,
 201                               TypeDescriptor.OfField<Class<?>>,
 202                               Constable {
 203     private static final int ANNOTATION= 0x00002000;
 204     private static final int ENUM      = 0x00004000;
 205     private static final int SYNTHETIC = 0x00001000;
 206 
 207     private static native void registerNatives();
 208     static {
 209         registerNatives();
 210     }
 211 
 212     /*
 213      * Private constructor. Only the Java Virtual Machine creates Class objects.
 214      * This constructor is not used and prevents the default constructor being
 215      * generated.
 216      */
 217     private Class(ClassLoader loader, Class<?> arrayComponentType) {
 218         // Initialize final field for classLoader.  The initialization value of non-null
 219         // prevents future JIT optimizations from assuming this final field is null.
 220         classLoader = loader;
 221         componentType = arrayComponentType;
 222     }
 223 
 224     /**
 225      * Converts the object to a string. The string representation is the
 226      * string "class" or "interface", followed by a space, and then by the
 227      * name of the class in the format returned by {@code getName}.
 228      * If this {@code Class} object represents a primitive type,
 229      * this method returns the name of the primitive type.  If
 230      * this {@code Class} object represents void this method returns
 231      * "void". If this {@code Class} object represents an array type,
 232      * this method returns "class " followed by {@code getName}.
 233      *
 234      * @return a string representation of this {@code Class} object.
 235      */
 236     public String toString() {
 237         String kind = isInterface() ? "interface " : isPrimitive() ? "" : "class ";
 238         return kind.concat(getName());














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

 271      *
 272      * @since 1.8
 273      */
 274     public String toGenericString() {
 275         if (isPrimitive()) {
 276             return toString();
 277         } else {
 278             StringBuilder sb = new StringBuilder();
 279             Class<?> component = this;
 280             int arrayDepth = 0;
 281 
 282             if (isArray()) {
 283                 do {
 284                     arrayDepth++;
 285                     component = component.getComponentType();
 286                 } while (component.isArray());
 287                 sb.append(component.getName());
 288             } else {
 289                 // Class modifiers are a superset of interface modifiers
 290                 int modifiers = getModifiers() & Modifier.classModifiers();


 291                 if (modifiers != 0) {
 292                     sb.append(Modifier.toString(modifiers));
 293                     sb.append(' ');
 294                 }
 295 
 296                 if (isAnnotation()) {
 297                     sb.append('@');
 298                 }



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

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

 571         SecurityManager sm = System.getSecurityManager();
 572         if (sm != null) {
 573             if (caller != null && caller.getModule() != module) {
 574                 // if caller is null, Class.forName is the last java frame on the stack.
 575                 // java.base has all permissions
 576                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 577             }
 578             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
 579             cl = AccessController.doPrivileged(pa);
 580         } else {
 581             cl = module.getClassLoader();
 582         }
 583 
 584         if (cl != null) {
 585             return cl.loadClass(module, name);
 586         } else {
 587             return BootLoader.loadClass(module, name);
 588         }
 589     }
 590 










































































































































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

1278      * If this class does not represent an array class, then this method returns
1279      * {@code null}.
1280      */
1281     private Class<?> elementType() {
1282         if (!isArray()) return null;
1283 
1284         Class<?> c = this;
1285         while (c.isArray()) {
1286             c = c.getComponentType();
1287         }
1288         return c;
1289     }
1290 
1291     /**
1292      * Returns the Java language modifiers for this class or interface, encoded
1293      * in an integer. The modifiers consist of the Java Virtual Machine's
1294      * constants for {@code public}, {@code protected},
1295      * {@code private}, {@code final}, {@code static},
1296      * {@code abstract} and {@code interface}; they should be decoded
1297      * using the methods of class {@code Modifier}.


1298      *
1299      * <p> If the underlying class is an array class:
1300      * <ul>
1301      * <li> its {@code public}, {@code private} and {@code protected}
1302      *      modifiers are the same as those of its component type
1303      * <li> its {@code abstract} and {@code final} modifiers are always
1304      *      {@code true}
1305      * <li> its interface modifier is always {@code false}, even when
1306      *      the component type is an interface
1307      * </ul>
1308      * If this {@code Class} object represents a primitive type or
1309      * void, its {@code public}, {@code abstract}, and {@code final}
1310      * modifiers are always {@code true}.
1311      * For {@code Class} objects representing void, primitive types, and
1312      * arrays, the values of other modifiers are {@code false} other
1313      * than as specified above.
1314      *
1315      * <p> The modifier encodings are defined in section {@jvms 4.1}
1316      * of <cite>The Java Virtual Machine Specification</cite>.
1317      *
1318      * @return the {@code int} representing the modifiers for this class
1319      * @see     java.lang.reflect.Modifier
1320      * @see #accessFlags()
1321      * @see <a
1322      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1323      * programming language and JVM modeling in core reflection</a>
1324      * @since 1.1
1325      * @jls 8.1.1 Class Modifiers
1326      * @jls 9.1.1. Interface Modifiers
1327      * @jvms 4.1 The {@code ClassFile} Structure
1328      */
1329     @IntrinsicCandidate
1330     public native int getModifiers();
1331 
1332     /**
1333      * {@return an unmodifiable set of the {@linkplain AccessFlag access
1334      * flags} for this class, possibly empty}
1335      *
1336      * <p> If the underlying class is an array class:
1337      * <ul>
1338      * <li> its {@code PUBLIC}, {@code PRIVATE} and {@code PROTECTED}
1339      *      access flags are the same as those of its component type
1340      * <li> its {@code ABSTRACT} and {@code FINAL} flags are present
1341      * <li> its {@code INTERFACE} flag is absent, even when the
1342      *      component type is an interface
1343      * </ul>
1344      * If this {@code Class} object represents a primitive type or
1345      * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
1346      * {@code FINAL}.
1347      * For {@code Class} objects representing void, primitive types, and
1348      * arrays, access flags are absent other than as specified above.
1349      *
1350      * @see #getModifiers()
1351      * @jvms 4.1 The ClassFile Structure
1352      * @jvms 4.7.6 The InnerClasses Attribute
1353      * @since 20
1354      */
1355     public Set<AccessFlag> accessFlags() {
1356         // Location.CLASS allows SUPER and AccessFlag.MODULE which
1357         // INNER_CLASS forbids. INNER_CLASS allows PRIVATE, PROTECTED,
1358         // and STATIC, which are not allowed on Location.CLASS.
1359         // Use getClassAccessFlagsRaw to expose SUPER status.
1360         var location = (isMemberClass() || isLocalClass() ||
1361                         isAnonymousClass() || isArray()) ?
1362             AccessFlag.Location.INNER_CLASS :
1363             AccessFlag.Location.CLASS;
1364         return AccessFlag.maskToAccessFlags((location == AccessFlag.Location.CLASS) ?
1365                                             getClassAccessFlagsRaw() :
1366                                             getModifiers(),
1367                                             location);
1368     }
1369 
1370     /**
1371      * Gets the signers of this class.
1372      *
1373      * @return  the signers of this class, or null if there are no signers.  In
1374      *          particular, this method returns null if this {@code Class} object represents
1375      *          a primitive type or void.
1376      * @since   1.1
1377      */
1378     public native Object[] getSigners();
1379 
1380 
1381     /**
1382      * Set the signers of this class.
1383      */
1384     native void setSigners(Object[] signers);
1385 
1386 
1387     /**
1388      * If this {@code Class} object represents a local or anonymous
1389      * class within a method, returns a {@link
1390      * java.lang.reflect.Method Method} object representing the
1391      * immediately enclosing method of the underlying class. Returns
1392      * {@code null} otherwise.
1393      *
1394      * In particular, this method returns {@code null} if the underlying
1395      * class is a local or anonymous class immediately enclosed by a class or
1396      * interface declaration, instance initializer or static initializer.
1397      *
1398      * @return the immediately enclosing method of the underlying class, if
1399      *     that class is a local or anonymous class; otherwise {@code null}.
1400      *
1401      * @throws SecurityException
1402      *         If a security manager, <i>s</i>, is present and any of the
1403      *         following conditions is met:
1404      *
1405      *         <ul>
1406      *

1507                 // the immediately enclosing method or constructor's
1508                 // descriptor (null iff name is).
1509                 String descriptor = (String)enclosingInfo[2];
1510                 assert((name != null && descriptor != null) || name == descriptor);
1511             } catch (ClassCastException cce) {
1512                 throw new InternalError("Invalid type in enclosing method information", cce);
1513             }
1514         }
1515 
1516         EnclosingMethodInfo(Object[] enclosingInfo) {
1517             validate(enclosingInfo);
1518             this.enclosingClass = (Class<?>)enclosingInfo[0];
1519             this.name = (String)enclosingInfo[1];
1520             this.descriptor = (String)enclosingInfo[2];
1521         }
1522 
1523         boolean isPartial() {
1524             return enclosingClass == null || name == null || descriptor == null;
1525         }
1526 
1527         boolean isConstructor() { return !isPartial() && "<init>".equals(name); }
1528 
1529         boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }




1530 
1531         Class<?> getEnclosingClass() { return enclosingClass; }
1532 
1533         String getName() { return name; }
1534 
1535         String getDescriptor() { return descriptor; }
1536 
1537     }
1538 
1539     private static Class<?> toClass(Type o) {
1540         if (o instanceof GenericArrayType)
1541             return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
1542                                      0)
1543                 .getClass();
1544         return (Class<?>)o;
1545      }
1546 
1547     /**
1548      * If this {@code Class} object represents a local or anonymous
1549      * class within a constructor, returns a {@link

1568      *         s.checkPermission} method with
1569      *         {@code RuntimePermission("accessDeclaredMembers")}
1570      *         denies access to the constructors within the enclosing class
1571      *
1572      *         <li> the caller's class loader is not the same as or an
1573      *         ancestor of the class loader for the enclosing class and
1574      *         invocation of {@link SecurityManager#checkPackageAccess
1575      *         s.checkPackageAccess()} denies access to the package
1576      *         of the enclosing class
1577      *
1578      *         </ul>
1579      * @since 1.5
1580      */
1581     @CallerSensitive
1582     public Constructor<?> getEnclosingConstructor() throws SecurityException {
1583         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1584 
1585         if (enclosingInfo == null)
1586             return null;
1587         else {
1588             if (!enclosingInfo.isConstructor())
1589                 return null;
1590 
1591             ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
1592                                                                         getFactory());
1593             Type []    parameterTypes   = typeInfo.getParameterTypes();
1594             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1595 
1596             // Convert Types to Classes; returned types *should*
1597             // be class objects since the methodDescriptor's used
1598             // don't have generics information
1599             for(int i = 0; i < parameterClasses.length; i++)
1600                 parameterClasses[i] = toClass(parameterTypes[i]);
1601 
1602             // Perform access check
1603             final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1604             @SuppressWarnings("removal")
1605             SecurityManager sm = System.getSecurityManager();
1606             if (sm != null) {
1607                 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED,
1608                                                      Reflection.getCallerClass(), true);

1748             simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1749         }
1750         return simpleName;
1751     }
1752 
1753     /**
1754      * Return an informative string for the name of this class or interface.
1755      *
1756      * @return an informative string for the name of this class or interface
1757      * @since 1.8
1758      */
1759     public String getTypeName() {
1760         if (isArray()) {
1761             try {
1762                 Class<?> cl = this;
1763                 int dimensions = 0;
1764                 do {
1765                     dimensions++;
1766                     cl = cl.getComponentType();
1767                 } while (cl.isArray());
1768                 return cl.getName().concat("[]".repeat(dimensions));
1769             } catch (Throwable e) { /*FALLTHRU*/ }
1770         }
1771         return getName();





1772     }
1773 
1774     /**
1775      * Returns the canonical name of the underlying class as
1776      * defined by <cite>The Java Language Specification</cite>.
1777      * Returns {@code null} if the underlying class does not have a canonical
1778      * name. Classes without canonical names include:
1779      * <ul>
1780      * <li>a {@linkplain #isLocalClass() local class}
1781      * <li>a {@linkplain #isAnonymousClass() anonymous class}
1782      * <li>a {@linkplain #isHidden() hidden class}
1783      * <li>an array whose component type does not have a canonical name</li>
1784      * </ul>
1785      *
1786      * The canonical name for a primitive class is the keyword for the
1787      * corresponding primitive type ({@code byte}, {@code short},
1788      * {@code char}, {@code int}, and so on).
1789      *
1790      * <p>An array type has a canonical name if and only if its
1791      * component type has a canonical name. When an array type has a

3665                                               /* includeStatic */ false));
3666         }
3667 
3668         return res;
3669     }
3670 
3671     // Returns a "root" Constructor object. This Constructor object must NOT
3672     // be propagated to the outside world, but must instead be copied
3673     // via ReflectionFactory.copyConstructor.
3674     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3675                                         int which) throws NoSuchMethodException
3676     {
3677         ReflectionFactory fact = getReflectionFactory();
3678         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3679         for (Constructor<T> constructor : constructors) {
3680             if (arrayContentsEq(parameterTypes,
3681                                 fact.getExecutableSharedParameterTypes(constructor))) {
3682                 return constructor;
3683             }
3684         }
3685         throw new NoSuchMethodException(methodToString("<init>", parameterTypes));
3686     }
3687 
3688     //
3689     // Other helpers and base implementation
3690     //
3691 
3692     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3693         if (a1 == null) {
3694             return a2 == null || a2.length == 0;
3695         }
3696 
3697         if (a2 == null) {
3698             return a1.length == 0;
3699         }
3700 
3701         if (a1.length != a2.length) {
3702             return false;
3703         }
3704 
3705         for (int i = 0; i < a1.length; i++) {

3970         }
3971         return directory;
3972     }
3973     private transient volatile Map<String, T> enumConstantDirectory;
3974 
3975     /**
3976      * Casts an object to the class or interface represented
3977      * by this {@code Class} object.
3978      *
3979      * @param obj the object to be cast
3980      * @return the object after casting, or null if obj is null
3981      *
3982      * @throws ClassCastException if the object is not
3983      * null and is not assignable to the type T.
3984      *
3985      * @since 1.5
3986      */
3987     @SuppressWarnings("unchecked")
3988     @IntrinsicCandidate
3989     public T cast(Object obj) {



3990         if (obj != null && !isInstance(obj))
3991             throw new ClassCastException(cannotCastMsg(obj));
3992         return (T) obj;
3993     }
3994 
3995     private String cannotCastMsg(Object obj) {
3996         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3997     }
3998 
3999     /**
4000      * Casts this {@code Class} object to represent a subclass of the class
4001      * represented by the specified class object.  Checks that the cast
4002      * is valid, and throws a {@code ClassCastException} if it is not.  If
4003      * this method succeeds, it always returns a reference to this {@code Class} object.
4004      *
4005      * <p>This method is useful when a client needs to "narrow" the type of
4006      * a {@code Class} object to pass it to an API that restricts the
4007      * {@code Class} objects that it is willing to accept.  A cast would
4008      * generate a compile-time warning, as the correctness of the cast
4009      * could not be checked at runtime (because generic types are implemented

4265      *
4266      * <p> If this {@code Class} object represents an interface, the return
4267      * value is an array containing objects representing the uses of interface
4268      * types to specify interfaces directly extended by the interface. The
4269      * order of the objects in the array corresponds to the order of the
4270      * interface types used in the 'extends' clause of the declaration of this
4271      * {@code Class} object.
4272      *
4273      * <p> If this {@code Class} object represents a class or interface whose
4274      * declaration does not explicitly indicate any annotated superinterfaces,
4275      * the return value is an array of length 0.
4276      *
4277      * <p> If this {@code Class} object represents either the {@code Object}
4278      * class, an array type, a primitive type, or void, the return value is an
4279      * array of length 0.
4280      *
4281      * @return an array representing the superinterfaces
4282      * @since 1.8
4283      */
4284     public AnnotatedType[] getAnnotatedInterfaces() {
4285          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
4286     }
4287 
4288     private native Class<?> getNestHost0();
4289 
4290     /**
4291      * Returns the nest host of the <a href=#nest>nest</a> to which the class
4292      * or interface represented by this {@code Class} object belongs.
4293      * Every class and interface belongs to exactly one nest.
4294      *
4295      * If the nest host of this class or interface has previously
4296      * been determined, then this method returns the nest host.
4297      * If the nest host of this class or interface has
4298      * not previously been determined, then this method determines the nest
4299      * host using the algorithm of JVMS 5.4.4, and returns it.
4300      *
4301      * Often, a class or interface belongs to a nest consisting only of itself,
4302      * in which case this method returns {@code this} to indicate that the class
4303      * or interface is the nest host.
4304      *
4305      * <p>If this {@code Class} object represents a primitive type, an array type,

4480      * {@code void}, then the result is a field descriptor string which
4481      * is a one-letter code corresponding to a primitive type or {@code void}
4482      * ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}).
4483      *
4484      * @apiNote
4485      * This is not a strict inverse of {@link #forName};
4486      * distinct classes which share a common name but have different class loaders
4487      * will have identical descriptor strings.
4488      *
4489      * @return the descriptor string for this {@code Class} object
4490      * @jvms 4.3.2 Field Descriptors
4491      * @since 12
4492      */
4493     @Override
4494     public String descriptorString() {
4495         if (isPrimitive())
4496             return Wrapper.forPrimitiveType(this).basicTypeString();
4497 
4498         if (isArray()) {
4499             return "[" + componentType.descriptorString();
4500         } else if (isHidden()) {


4501             String name = getName();
4502             int index = name.indexOf('/');
4503             return new StringBuilder(name.length() + 2)
4504                     .append('L')
4505                     .append(name.substring(0, index).replace('.', '/'))
4506                     .append('.')
4507                     .append(name, index + 1, name.length())
4508                     .append(';')
4509                     .toString();
4510         } else {
4511             String name = getName().replace('.', '/');
4512             return new StringBuilder(name.length() + 2)
4513                     .append('L')
4514                     .append(name)
4515                     .append(';')
4516                     .toString();
4517         }
4518     }
4519 
4520     /**
4521      * Returns the component type of this {@code Class}, if it describes
4522      * an array type, or {@code null} otherwise.
4523      *
4524      * @implSpec
4525      * Equivalent to {@link Class#getComponentType()}.
4526      *
4527      * @return a {@code Class} describing the component type, or {@code null}
4528      * if this {@code Class} does not describe an array type
4529      * @since 12
4530      */
4531     @Override
4532     public Class<?> componentType() {
4533         return isArray() ? componentType : null;

  52 import java.lang.reflect.Type;
  53 import java.lang.reflect.TypeVariable;
  54 import java.lang.constant.Constable;
  55 import java.net.URL;
  56 import java.security.AccessController;
  57 import java.security.PrivilegedAction;
  58 import java.util.ArrayList;
  59 import java.util.Arrays;
  60 import java.util.Collection;
  61 import java.util.HashMap;
  62 import java.util.HashSet;
  63 import java.util.LinkedHashMap;
  64 import java.util.LinkedHashSet;
  65 import java.util.List;
  66 import java.util.Map;
  67 import java.util.Objects;
  68 import java.util.Optional;
  69 import java.util.Set;
  70 import java.util.stream.Collectors;
  71 
  72 import jdk.internal.javac.PreviewFeature;
  73 import jdk.internal.loader.BootLoader;
  74 import jdk.internal.loader.BuiltinClassLoader;
  75 import jdk.internal.misc.Unsafe;
  76 import jdk.internal.module.Resources;
  77 import jdk.internal.reflect.CallerSensitive;
  78 import jdk.internal.reflect.CallerSensitiveAdapter;
  79 import jdk.internal.reflect.ConstantPool;
  80 import jdk.internal.reflect.Reflection;
  81 import jdk.internal.reflect.ReflectionFactory;
  82 import jdk.internal.value.PrimitiveClass;
  83 import jdk.internal.vm.annotation.ForceInline;
  84 import jdk.internal.vm.annotation.IntrinsicCandidate;
  85 import sun.invoke.util.Wrapper;
  86 import sun.reflect.generics.factory.CoreReflectionFactory;
  87 import sun.reflect.generics.factory.GenericsFactory;
  88 import sun.reflect.generics.repository.ClassRepository;
  89 import sun.reflect.generics.repository.MethodRepository;
  90 import sun.reflect.generics.repository.ConstructorRepository;
  91 import sun.reflect.generics.scope.ClassScope;
  92 import sun.security.util.SecurityConstants;
  93 import sun.reflect.annotation.*;
  94 import sun.reflect.misc.ReflectUtil;
  95 
  96 /**
  97  * Instances of the class {@code Class} represent classes and
  98  * interfaces in a running Java application. An enum class and a record
  99  * class are kinds of class; an annotation interface is a kind of
 100  * interface. Every array also belongs to a class that is reflected as
 101  * a {@code Class} object that is shared by all arrays with the same
 102  * element type and number of dimensions.  The primitive Java types

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

 287      *
 288      * @since 1.8
 289      */
 290     public String toGenericString() {
 291         if (isPrimitive()) {
 292             return toString();
 293         } else {
 294             StringBuilder sb = new StringBuilder();
 295             Class<?> component = this;
 296             int arrayDepth = 0;
 297 
 298             if (isArray()) {
 299                 do {
 300                     arrayDepth++;
 301                     component = component.getComponentType();
 302                 } while (component.isArray());
 303                 sb.append(component.getName());
 304             } else {
 305                 // Class modifiers are a superset of interface modifiers
 306                 int modifiers = getModifiers() & Modifier.classModifiers();
 307                 // Modifier.toString() below mis-interprets SYNCHRONIZED, STRICT, and VOLATILE bits
 308                 modifiers &= ~(Modifier.SYNCHRONIZED | Modifier.STRICT | Modifier.VOLATILE);
 309                 if (modifiers != 0) {
 310                     sb.append(Modifier.toString(modifiers));
 311                     sb.append(' ');
 312                 }
 313 
 314                 if (isAnnotation()) {
 315                     sb.append('@');
 316                 }
 317                 if (isValue()) {
 318                     sb.append(isPrimitiveClass() ? "primitive " : "value ");
 319                 }
 320                 if (isInterface()) { // Note: all annotation interfaces are interfaces
 321                     sb.append("interface");
 322                 } else {
 323                     if (isEnum())
 324                         sb.append("enum");
 325                     else if (isRecord())
 326                         sb.append("record");
 327                     else
 328                         sb.append("class");
 329                 }
 330                 sb.append(' ');
 331                 sb.append(getName());
 332             }
 333 
 334             TypeVariable<?>[] typeparms = component.getTypeParameters();
 335             if (typeparms.length > 0) {
 336                 sb.append(Arrays.stream(typeparms)
 337                           .map(Class::typeVarBounds)
 338                           .collect(Collectors.joining(",", "<", ">")));
 339             }

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

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

1437      * If this class does not represent an array class, then this method returns
1438      * {@code null}.
1439      */
1440     private Class<?> elementType() {
1441         if (!isArray()) return null;
1442 
1443         Class<?> c = this;
1444         while (c.isArray()) {
1445             c = c.getComponentType();
1446         }
1447         return c;
1448     }
1449 
1450     /**
1451      * Returns the Java language modifiers for this class or interface, encoded
1452      * in an integer. The modifiers consist of the Java Virtual Machine's
1453      * constants for {@code public}, {@code protected},
1454      * {@code private}, {@code final}, {@code static},
1455      * {@code abstract} and {@code interface}; they should be decoded
1456      * using the methods of class {@code Modifier}.
1457      * The modifiers also include the Java Virtual Machine's constants for
1458      * {@code identity class} and {@code value class}.
1459      *
1460      * <p> If the underlying class is an array class:
1461      * <ul>
1462      * <li> its {@code public}, {@code private} and {@code protected}
1463      *      modifiers are the same as those of its component type
1464      * <li> its {@code abstract} and {@code final} modifiers are always
1465      *      {@code true}
1466      * <li> its interface modifier is always {@code false}, even when
1467      *      the component type is an interface
1468      * </ul>
1469      * If this {@code Class} object represents a primitive type or
1470      * void, its {@code public}, {@code abstract}, and {@code final}
1471      * modifiers are always {@code true}.
1472      * For {@code Class} objects representing void, primitive types, and
1473      * arrays, the values of other modifiers are {@code false} other
1474      * than as specified above.
1475      *
1476      * <p> The modifier encodings are defined in section {@jvms 4.1}
1477      * of <cite>The Java Virtual Machine Specification</cite>.
1478      *
1479      * @return the {@code int} representing the modifiers for this class
1480      * @see     java.lang.reflect.Modifier
1481      * @see #accessFlags()
1482      * @see <a
1483      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1484      * programming language and JVM modeling in core reflection</a>
1485      * @since 1.1
1486      * @jls 8.1.1 Class Modifiers
1487      * @jls 9.1.1. Interface Modifiers
1488      * @jvms 4.1 The {@code ClassFile} Structure
1489      */
1490     @IntrinsicCandidate
1491     public native int getModifiers();
1492 
1493    /**
1494      * {@return an unmodifiable set of the {@linkplain AccessFlag access
1495      * flags} for this class, possibly empty}
1496      *
1497      * <p> If the underlying class is an array class:
1498      * <ul>
1499      * <li> its {@code PUBLIC}, {@code PRIVATE} and {@code PROTECTED}
1500      *      access flags are the same as those of its component type
1501      * <li> its {@code ABSTRACT} and {@code FINAL} flags are present
1502      * <li> its {@code INTERFACE} flag is absent, even when the
1503      *      component type is an interface
1504      * </ul>
1505      * If this {@code Class} object represents a primitive type or
1506      * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
1507      * {@code FINAL}.
1508      * For {@code Class} objects representing void, primitive types, and
1509      * arrays, access flags are absent other than as specified above.
1510      *
1511      * @see #getModifiers()
1512      * @jvms 4.1 The ClassFile Structure
1513      * @jvms 4.7.6 The InnerClasses Attribute
1514      * @since 20
1515      */
1516     public Set<AccessFlag> accessFlags() {
1517         // Location.CLASS allows SUPER and AccessFlag.MODULE which
1518         // INNER_CLASS forbids. INNER_CLASS allows PRIVATE, PROTECTED,
1519         // and STATIC, which are not allowed on Location.CLASS.
1520         // Use getClassAccessFlagsRaw to expose SUPER status.
1521         var location = (isMemberClass() || isLocalClass() ||
1522                         isAnonymousClass() || isArray()) ?
1523             AccessFlag.Location.INNER_CLASS :
1524             AccessFlag.Location.CLASS;
1525         return AccessFlag.maskToAccessFlags((location == AccessFlag.Location.CLASS) ?
1526                                             getClassAccessFlagsRaw() & (~0x800) :
1527                                             getModifiers() & (~0x800), // suppress unspecified bit
1528                                             location);
1529     }
1530 
1531    /**
1532      * Gets the signers of this class.
1533      *
1534      * @return  the signers of this class, or null if there are no signers.  In
1535      *          particular, this method returns null if this {@code Class} object represents
1536      *          a primitive type or void.
1537      * @since   1.1
1538      */
1539     public native Object[] getSigners();
1540 

1541     /**
1542      * Set the signers of this class.
1543      */
1544     native void setSigners(Object[] signers);
1545 

1546     /**
1547      * If this {@code Class} object represents a local or anonymous
1548      * class within a method, returns a {@link
1549      * java.lang.reflect.Method Method} object representing the
1550      * immediately enclosing method of the underlying class. Returns
1551      * {@code null} otherwise.
1552      *
1553      * In particular, this method returns {@code null} if the underlying
1554      * class is a local or anonymous class immediately enclosed by a class or
1555      * interface declaration, instance initializer or static initializer.
1556      *
1557      * @return the immediately enclosing method of the underlying class, if
1558      *     that class is a local or anonymous class; otherwise {@code null}.
1559      *
1560      * @throws SecurityException
1561      *         If a security manager, <i>s</i>, is present and any of the
1562      *         following conditions is met:
1563      *
1564      *         <ul>
1565      *

1666                 // the immediately enclosing method or constructor's
1667                 // descriptor (null iff name is).
1668                 String descriptor = (String)enclosingInfo[2];
1669                 assert((name != null && descriptor != null) || name == descriptor);
1670             } catch (ClassCastException cce) {
1671                 throw new InternalError("Invalid type in enclosing method information", cce);
1672             }
1673         }
1674 
1675         EnclosingMethodInfo(Object[] enclosingInfo) {
1676             validate(enclosingInfo);
1677             this.enclosingClass = (Class<?>)enclosingInfo[0];
1678             this.name = (String)enclosingInfo[1];
1679             this.descriptor = (String)enclosingInfo[2];
1680         }
1681 
1682         boolean isPartial() {
1683             return enclosingClass == null || name == null || descriptor == null;
1684         }
1685 
1686         boolean isObjectConstructor() { return !isPartial() && "<init>".equals(name); }
1687 
1688         boolean isValueFactoryMethod() { return !isPartial() && "<vnew>".equals(name); }
1689 
1690         boolean isMethod() { return !isPartial() && !isObjectConstructor()
1691                                         && !isValueFactoryMethod()
1692                                         && !"<clinit>".equals(name); }
1693 
1694         Class<?> getEnclosingClass() { return enclosingClass; }
1695 
1696         String getName() { return name; }
1697 
1698         String getDescriptor() { return descriptor; }
1699 
1700     }
1701 
1702     private static Class<?> toClass(Type o) {
1703         if (o instanceof GenericArrayType)
1704             return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
1705                                      0)
1706                 .getClass();
1707         return (Class<?>)o;
1708      }
1709 
1710     /**
1711      * If this {@code Class} object represents a local or anonymous
1712      * class within a constructor, returns a {@link

1731      *         s.checkPermission} method with
1732      *         {@code RuntimePermission("accessDeclaredMembers")}
1733      *         denies access to the constructors within the enclosing class
1734      *
1735      *         <li> the caller's class loader is not the same as or an
1736      *         ancestor of the class loader for the enclosing class and
1737      *         invocation of {@link SecurityManager#checkPackageAccess
1738      *         s.checkPackageAccess()} denies access to the package
1739      *         of the enclosing class
1740      *
1741      *         </ul>
1742      * @since 1.5
1743      */
1744     @CallerSensitive
1745     public Constructor<?> getEnclosingConstructor() throws SecurityException {
1746         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1747 
1748         if (enclosingInfo == null)
1749             return null;
1750         else {
1751             if (!enclosingInfo.isObjectConstructor() && !enclosingInfo.isValueFactoryMethod())
1752                 return null;
1753 
1754             ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
1755                                                                         getFactory());
1756             Type []    parameterTypes   = typeInfo.getParameterTypes();
1757             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1758 
1759             // Convert Types to Classes; returned types *should*
1760             // be class objects since the methodDescriptor's used
1761             // don't have generics information
1762             for(int i = 0; i < parameterClasses.length; i++)
1763                 parameterClasses[i] = toClass(parameterTypes[i]);
1764 
1765             // Perform access check
1766             final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1767             @SuppressWarnings("removal")
1768             SecurityManager sm = System.getSecurityManager();
1769             if (sm != null) {
1770                 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED,
1771                                                      Reflection.getCallerClass(), true);

1911             simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1912         }
1913         return simpleName;
1914     }
1915 
1916     /**
1917      * Return an informative string for the name of this class or interface.
1918      *
1919      * @return an informative string for the name of this class or interface
1920      * @since 1.8
1921      */
1922     public String getTypeName() {
1923         if (isArray()) {
1924             try {
1925                 Class<?> cl = this;
1926                 int dimensions = 0;
1927                 do {
1928                     dimensions++;
1929                     cl = cl.getComponentType();
1930                 } while (cl.isArray());
1931                 return cl.getTypeName().concat("[]".repeat(dimensions));
1932             } catch (Throwable e) { /*FALLTHRU*/ }
1933         }
1934         if (isPrimitiveClass()) {
1935             // TODO: null-default
1936             return isPrimaryType() ? getName().concat(".ref") : getName();
1937         } else {
1938             return getName();
1939         }
1940     }
1941 
1942     /**
1943      * Returns the canonical name of the underlying class as
1944      * defined by <cite>The Java Language Specification</cite>.
1945      * Returns {@code null} if the underlying class does not have a canonical
1946      * name. Classes without canonical names include:
1947      * <ul>
1948      * <li>a {@linkplain #isLocalClass() local class}
1949      * <li>a {@linkplain #isAnonymousClass() anonymous class}
1950      * <li>a {@linkplain #isHidden() hidden class}
1951      * <li>an array whose component type does not have a canonical name</li>
1952      * </ul>
1953      *
1954      * The canonical name for a primitive class is the keyword for the
1955      * corresponding primitive type ({@code byte}, {@code short},
1956      * {@code char}, {@code int}, and so on).
1957      *
1958      * <p>An array type has a canonical name if and only if its
1959      * component type has a canonical name. When an array type has a

3833                                               /* includeStatic */ false));
3834         }
3835 
3836         return res;
3837     }
3838 
3839     // Returns a "root" Constructor object. This Constructor object must NOT
3840     // be propagated to the outside world, but must instead be copied
3841     // via ReflectionFactory.copyConstructor.
3842     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3843                                         int which) throws NoSuchMethodException
3844     {
3845         ReflectionFactory fact = getReflectionFactory();
3846         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3847         for (Constructor<T> constructor : constructors) {
3848             if (arrayContentsEq(parameterTypes,
3849                                 fact.getExecutableSharedParameterTypes(constructor))) {
3850                 return constructor;
3851             }
3852         }
3853         throw new NoSuchMethodException(methodToString(isValue() ? "<vnew>" : "<init>", parameterTypes));
3854     }
3855 
3856     //
3857     // Other helpers and base implementation
3858     //
3859 
3860     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3861         if (a1 == null) {
3862             return a2 == null || a2.length == 0;
3863         }
3864 
3865         if (a2 == null) {
3866             return a1.length == 0;
3867         }
3868 
3869         if (a1.length != a2.length) {
3870             return false;
3871         }
3872 
3873         for (int i = 0; i < a1.length; i++) {

4138         }
4139         return directory;
4140     }
4141     private transient volatile Map<String, T> enumConstantDirectory;
4142 
4143     /**
4144      * Casts an object to the class or interface represented
4145      * by this {@code Class} object.
4146      *
4147      * @param obj the object to be cast
4148      * @return the object after casting, or null if obj is null
4149      *
4150      * @throws ClassCastException if the object is not
4151      * null and is not assignable to the type T.
4152      *
4153      * @since 1.5
4154      */
4155     @SuppressWarnings("unchecked")
4156     @IntrinsicCandidate
4157     public T cast(Object obj) {
4158         if (isPrimitiveValueType() && obj == null)
4159             throw new NullPointerException(getName() + " is a primitive value type");
4160 
4161         if (obj != null && !isInstance(obj))
4162             throw new ClassCastException(cannotCastMsg(obj));
4163         return (T) obj;
4164     }
4165 
4166     private String cannotCastMsg(Object obj) {
4167         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
4168     }
4169 
4170     /**
4171      * Casts this {@code Class} object to represent a subclass of the class
4172      * represented by the specified class object.  Checks that the cast
4173      * is valid, and throws a {@code ClassCastException} if it is not.  If
4174      * this method succeeds, it always returns a reference to this {@code Class} object.
4175      *
4176      * <p>This method is useful when a client needs to "narrow" the type of
4177      * a {@code Class} object to pass it to an API that restricts the
4178      * {@code Class} objects that it is willing to accept.  A cast would
4179      * generate a compile-time warning, as the correctness of the cast
4180      * could not be checked at runtime (because generic types are implemented

4436      *
4437      * <p> If this {@code Class} object represents an interface, the return
4438      * value is an array containing objects representing the uses of interface
4439      * types to specify interfaces directly extended by the interface. The
4440      * order of the objects in the array corresponds to the order of the
4441      * interface types used in the 'extends' clause of the declaration of this
4442      * {@code Class} object.
4443      *
4444      * <p> If this {@code Class} object represents a class or interface whose
4445      * declaration does not explicitly indicate any annotated superinterfaces,
4446      * the return value is an array of length 0.
4447      *
4448      * <p> If this {@code Class} object represents either the {@code Object}
4449      * class, an array type, a primitive type, or void, the return value is an
4450      * array of length 0.
4451      *
4452      * @return an array representing the superinterfaces
4453      * @since 1.8
4454      */
4455     public AnnotatedType[] getAnnotatedInterfaces() {
4456         return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
4457     }
4458 
4459     private native Class<?> getNestHost0();
4460 
4461     /**
4462      * Returns the nest host of the <a href=#nest>nest</a> to which the class
4463      * or interface represented by this {@code Class} object belongs.
4464      * Every class and interface belongs to exactly one nest.
4465      *
4466      * If the nest host of this class or interface has previously
4467      * been determined, then this method returns the nest host.
4468      * If the nest host of this class or interface has
4469      * not previously been determined, then this method determines the nest
4470      * host using the algorithm of JVMS 5.4.4, and returns it.
4471      *
4472      * Often, a class or interface belongs to a nest consisting only of itself,
4473      * in which case this method returns {@code this} to indicate that the class
4474      * or interface is the nest host.
4475      *
4476      * <p>If this {@code Class} object represents a primitive type, an array type,

4651      * {@code void}, then the result is a field descriptor string which
4652      * is a one-letter code corresponding to a primitive type or {@code void}
4653      * ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}).
4654      *
4655      * @apiNote
4656      * This is not a strict inverse of {@link #forName};
4657      * distinct classes which share a common name but have different class loaders
4658      * will have identical descriptor strings.
4659      *
4660      * @return the descriptor string for this {@code Class} object
4661      * @jvms 4.3.2 Field Descriptors
4662      * @since 12
4663      */
4664     @Override
4665     public String descriptorString() {
4666         if (isPrimitive())
4667             return Wrapper.forPrimitiveType(this).basicTypeString();
4668 
4669         if (isArray()) {
4670             return "[" + componentType.descriptorString();
4671         }
4672         char typeDesc = isPrimitiveValueType() ? 'Q' : 'L';
4673         if (isHidden()) {
4674             String name = getName();
4675             int index = name.indexOf('/');
4676             return new StringBuilder(name.length() + 2)
4677                     .append(typeDesc)
4678                     .append(name.substring(0, index).replace('.', '/'))
4679                     .append('.')
4680                     .append(name, index + 1, name.length())
4681                     .append(';')
4682                     .toString();
4683         } else {
4684             String name = getName().replace('.', '/');
4685             return new StringBuilder(name.length() + 2)
4686                     .append(typeDesc)
4687                     .append(name)
4688                     .append(';')
4689                     .toString();
4690         }
4691     }
4692 
4693     /**
4694      * Returns the component type of this {@code Class}, if it describes
4695      * an array type, or {@code null} otherwise.
4696      *
4697      * @implSpec
4698      * Equivalent to {@link Class#getComponentType()}.
4699      *
4700      * @return a {@code Class} describing the component type, or {@code null}
4701      * if this {@code Class} does not describe an array type
4702      * @since 12
4703      */
4704     @Override
4705     public Class<?> componentType() {
4706         return isArray() ? componentType : null;
< prev index next >