< prev index next >

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

Print this page

  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 import java.lang.annotation.Annotation;
  29 import java.lang.constant.ClassDesc;
  30 import java.lang.constant.ConstantDescs;
  31 import java.lang.invoke.TypeDescriptor;
  32 import java.lang.invoke.MethodHandles;
  33 import java.lang.module.ModuleReader;
  34 import java.lang.ref.SoftReference;
  35 import java.io.IOException;
  36 import java.io.InputStream;
  37 import java.io.ObjectStreamField;
  38 import java.lang.reflect.AnnotatedElement;
  39 import java.lang.reflect.AnnotatedType;
  40 import java.lang.reflect.AccessFlag;
  41 import java.lang.reflect.Array;

  42 import java.lang.reflect.Constructor;
  43 import java.lang.reflect.Executable;
  44 import java.lang.reflect.Field;
  45 import java.lang.reflect.GenericArrayType;
  46 import java.lang.reflect.GenericDeclaration;
  47 import java.lang.reflect.InvocationTargetException;
  48 import java.lang.reflect.Member;
  49 import java.lang.reflect.Method;
  50 import java.lang.reflect.Modifier;
  51 import java.lang.reflect.Proxy;
  52 import java.lang.reflect.RecordComponent;
  53 import java.lang.reflect.Type;
  54 import java.lang.reflect.TypeVariable;
  55 import java.lang.constant.Constable;
  56 import java.net.URL;
  57 import java.security.AccessController;
  58 import java.security.PrivilegedAction;
  59 import java.util.ArrayList;
  60 import java.util.Arrays;
  61 import java.util.Collection;

  64 import java.util.LinkedHashMap;
  65 import java.util.LinkedHashSet;
  66 import java.util.List;
  67 import java.util.Map;
  68 import java.util.Objects;
  69 import java.util.Optional;
  70 import java.util.Set;
  71 import java.util.stream.Collectors;
  72 
  73 import jdk.internal.javac.PreviewFeature;
  74 import jdk.internal.loader.BootLoader;
  75 import jdk.internal.loader.BuiltinClassLoader;
  76 import jdk.internal.misc.PreviewFeatures;
  77 import jdk.internal.misc.Unsafe;
  78 import jdk.internal.module.Resources;
  79 import jdk.internal.reflect.CallerSensitive;
  80 import jdk.internal.reflect.CallerSensitiveAdapter;
  81 import jdk.internal.reflect.ConstantPool;
  82 import jdk.internal.reflect.Reflection;
  83 import jdk.internal.reflect.ReflectionFactory;

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

 212  * {@linkplain #getTypeName type name} return results
 213  * equal to {@code "HelloWorld"}. The {@linkplain #getSimpleName
 214  * simple name} of such an unnamed class is the empty string and the
 215  * {@linkplain #getCanonicalName canonical name} is {@code null}.
 216  *
 217  * @param <T> the type of the class modeled by this {@code Class}
 218  * object.  For example, the type of {@code String.class} is {@code
 219  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
 220  * unknown.
 221  *
 222  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
 223  * @since   1.0
 224  * @jls 15.8.2 Class Literals
 225  */
 226 public final class Class<T> implements java.io.Serializable,
 227                               GenericDeclaration,
 228                               Type,
 229                               AnnotatedElement,
 230                               TypeDescriptor.OfField<Class<?>>,
 231                               Constable {
 232     private static final int ANNOTATION= 0x00002000;
 233     private static final int ENUM      = 0x00004000;
 234     private static final int SYNTHETIC = 0x00001000;
 235 
 236     private static native void registerNatives();
 237     static {
 238         registerNatives();
 239     }
 240 
 241     /*
 242      * Private constructor. Only the Java Virtual Machine creates Class objects.
 243      * This constructor is not used and prevents the default constructor being
 244      * generated.
 245      */
 246     private Class(ClassLoader loader, Class<?> arrayComponentType) {
 247         // Initialize final field for classLoader.  The initialization value of non-null
 248         // prevents future JIT optimizations from assuming this final field is null.
 249         classLoader = loader;
 250         componentType = arrayComponentType;
 251     }
 252 
 253     /**
 254      * Converts the object to a string. The string representation is the
 255      * string "class" or "interface", followed by a space, and then by the
 256      * name of the class in the format returned by {@code getName}.
 257      * If this {@code Class} object represents a primitive type,
 258      * this method returns the name of the primitive type.  If
 259      * this {@code Class} object represents void this method returns
 260      * "void". If this {@code Class} object represents an array type,
 261      * this method returns "class " followed by {@code getName}.
 262      *
 263      * @return a string representation of this {@code Class} object.
 264      */
 265     public String toString() {
 266         String kind = isInterface() ? "interface " : isPrimitive() ? "" : "class ";
 267         return kind.concat(getName());














 268     }
 269 
 270     /**
 271      * Returns a string describing this {@code Class}, including
 272      * information about modifiers and type parameters.
 273      *
 274      * The string is formatted as a list of type modifiers, if any,
 275      * followed by the kind of type (empty string for primitive types
 276      * and {@code class}, {@code enum}, {@code interface},
 277      * {@code @interface}, or {@code record} as appropriate), followed
 278      * by the type's name, followed by an angle-bracketed
 279      * comma-separated list of the type's type parameters, if any,
 280      * including informative bounds on the type parameters, if any.
 281      *
 282      * A space is used to separate modifiers from one another and to
 283      * separate any modifiers from the kind of type. The modifiers
 284      * occur in canonical order. If there are no type parameters, the
 285      * type parameter list is elided.
 286      *
 287      * For an array type, the string starts with the type name,

 300      *
 301      * @since 1.8
 302      */
 303     public String toGenericString() {
 304         if (isPrimitive()) {
 305             return toString();
 306         } else {
 307             StringBuilder sb = new StringBuilder();
 308             Class<?> component = this;
 309             int arrayDepth = 0;
 310 
 311             if (isArray()) {
 312                 do {
 313                     arrayDepth++;
 314                     component = component.getComponentType();
 315                 } while (component.isArray());
 316                 sb.append(component.getName());
 317             } else {
 318                 // Class modifiers are a superset of interface modifiers
 319                 int modifiers = getModifiers() & Modifier.classModifiers();


 320                 if (modifiers != 0) {
 321                     sb.append(Modifier.toString(modifiers));
 322                     sb.append(' ');
 323                 }
 324 
 325                 if (isAnnotation()) {
 326                     sb.append('@');
 327                 }



 328                 if (isInterface()) { // Note: all annotation interfaces are interfaces
 329                     sb.append("interface");
 330                 } else {
 331                     if (isEnum())
 332                         sb.append("enum");
 333                     else if (isRecord())
 334                         sb.append("record");
 335                     else
 336                         sb.append("class");
 337                 }
 338                 sb.append(' ');
 339                 sb.append(getName());
 340             }
 341 
 342             TypeVariable<?>[] typeparms = component.getTypeParameters();
 343             if (typeparms.length > 0) {
 344                 sb.append(Arrays.stream(typeparms)
 345                           .map(Class::typeVarBounds)
 346                           .collect(Collectors.joining(",", "<", ">")));
 347             }

 522             throws ClassNotFoundException
 523     {
 524         @SuppressWarnings("removal")
 525         SecurityManager sm = System.getSecurityManager();
 526         if (sm != null) {
 527             // Reflective call to get caller class is only needed if a security manager
 528             // is present.  Avoid the overhead of making this call otherwise.
 529             if (loader == null) {
 530                 ClassLoader ccl = ClassLoader.getClassLoader(caller);
 531                 if (ccl != null) {
 532                     sm.checkPermission(
 533                             SecurityConstants.GET_CLASSLOADER_PERMISSION);
 534                 }
 535             }
 536         }
 537         return forName0(name, initialize, loader, caller);
 538     }
 539 
 540     /** Called after security check for system loader access checks have been made. */
 541     private static native Class<?> forName0(String name, boolean initialize,
 542                                             ClassLoader loader,
 543                                             Class<?> caller)
 544         throws ClassNotFoundException;
 545 
 546 
 547     /**
 548      * Returns the {@code Class} with the given {@linkplain ClassLoader##binary-name
 549      * binary name} in the given module.
 550      *
 551      * <p> This method attempts to locate and load the class or interface.
 552      * It does not link the class, and does not run the class initializer.
 553      * If the class is not found, this method returns {@code null}. </p>
 554      *
 555      * <p> If the class loader of the given module defines other modules and
 556      * the given name is a class defined in a different module, this method
 557      * returns {@code null} after the class is loaded. </p>
 558      *
 559      * <p> This method does not check whether the requested class is
 560      * accessible to its caller. </p>
 561      *
 562      * @apiNote
 563      * This method does not support loading of array types, unlike

 614         SecurityManager sm = System.getSecurityManager();
 615         if (sm != null) {
 616             if (caller != null && caller.getModule() != module) {
 617                 // if caller is null, Class.forName is the last java frame on the stack.
 618                 // java.base has all permissions
 619                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 620             }
 621             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
 622             cl = AccessController.doPrivileged(pa);
 623         } else {
 624             cl = module.getClassLoader();
 625         }
 626 
 627         if (cl != null) {
 628             return cl.loadClass(module, name);
 629         } else {
 630             return BootLoader.loadClass(module, name);
 631         }
 632     }
 633 










































































































































 634     /**
 635      * {@return the {@code Class} object associated with the
 636      * {@linkplain #isPrimitive() primitive type} of the given name}
 637      * If the argument is not the name of a primitive type, {@code
 638      * null} is returned.
 639      *
 640      * @param primitiveName the name of the primitive type to find
 641      *
 642      * @throws NullPointerException if the argument is {@code null}
 643      *
 644      * @jls 4.2 Primitive Types and Values
 645      * @jls 15.8.2 Class Literals
 646      * @since 22
 647      */
 648     public static Class<?> forPrimitiveName(String primitiveName) {
 649         return switch(primitiveName) {
 650         // Integral types
 651         case "int"     -> int.class;
 652         case "long"    -> long.class;
 653         case "short"   -> short.class;

1370      * If this class does not represent an array class, then this method returns
1371      * {@code null}.
1372      */
1373     private Class<?> elementType() {
1374         if (!isArray()) return null;
1375 
1376         Class<?> c = this;
1377         while (c.isArray()) {
1378             c = c.getComponentType();
1379         }
1380         return c;
1381     }
1382 
1383     /**
1384      * Returns the Java language modifiers for this class or interface, encoded
1385      * in an integer. The modifiers consist of the Java Virtual Machine's
1386      * constants for {@code public}, {@code protected},
1387      * {@code private}, {@code final}, {@code static},
1388      * {@code abstract} and {@code interface}; they should be decoded
1389      * using the methods of class {@code Modifier}.


1390      *
1391      * <p> If the underlying class is an array class:
1392      * <ul>
1393      * <li> its {@code public}, {@code private} and {@code protected}
1394      *      modifiers are the same as those of its component type
1395      * <li> its {@code abstract} and {@code final} modifiers are always
1396      *      {@code true}
1397      * <li> its interface modifier is always {@code false}, even when
1398      *      the component type is an interface
1399      * </ul>
1400      * If this {@code Class} object represents a primitive type or
1401      * void, its {@code public}, {@code abstract}, and {@code final}
1402      * modifiers are always {@code true}.
1403      * For {@code Class} objects representing void, primitive types, and
1404      * arrays, the values of other modifiers are {@code false} other
1405      * than as specified above.
1406      *
1407      * <p> The modifier encodings are defined in section {@jvms 4.1}
1408      * of <cite>The Java Virtual Machine Specification</cite>.
1409      *
1410      * @return the {@code int} representing the modifiers for this class
1411      * @see     java.lang.reflect.Modifier
1412      * @see #accessFlags()
1413      * @see <a
1414      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1415      * programming language and JVM modeling in core reflection</a>
1416      * @since 1.1
1417      * @jls 8.1.1 Class Modifiers
1418      * @jls 9.1.1. Interface Modifiers
1419      * @jvms 4.1 The {@code ClassFile} Structure
1420      */
1421     @IntrinsicCandidate
1422     public native int getModifiers();
1423 
1424     /**
1425      * {@return an unmodifiable set of the {@linkplain AccessFlag access
1426      * flags} for this class, possibly empty}

1427      *
1428      * <p> If the underlying class is an array class:
1429      * <ul>
1430      * <li> its {@code PUBLIC}, {@code PRIVATE} and {@code PROTECTED}
1431      *      access flags are the same as those of its component type
1432      * <li> its {@code ABSTRACT} and {@code FINAL} flags are present
1433      * <li> its {@code INTERFACE} flag is absent, even when the
1434      *      component type is an interface
1435      * </ul>
1436      * If this {@code Class} object represents a primitive type or
1437      * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
1438      * {@code FINAL}.
1439      * For {@code Class} objects representing void, primitive types, and
1440      * arrays, access flags are absent other than as specified above.
1441      *
1442      * @see #getModifiers()
1443      * @jvms 4.1 The ClassFile Structure
1444      * @jvms 4.7.6 The InnerClasses Attribute
1445      * @since 20
1446      */
1447     public Set<AccessFlag> accessFlags() {
1448         // Location.CLASS allows SUPER and AccessFlag.MODULE which
1449         // INNER_CLASS forbids. INNER_CLASS allows PRIVATE, PROTECTED,
1450         // and STATIC, which are not allowed on Location.CLASS.
1451         // Use getClassAccessFlagsRaw to expose SUPER status.
1452         var location = (isMemberClass() || isLocalClass() ||
1453                         isAnonymousClass() || isArray()) ?
1454             AccessFlag.Location.INNER_CLASS :
1455             AccessFlag.Location.CLASS;
1456         return AccessFlag.maskToAccessFlags((location == AccessFlag.Location.CLASS) ?
1457                                             getClassAccessFlagsRaw() :
1458                                             getModifiers(),
1459                                             location);




1460     }
1461 
1462     /**
1463      * Gets the signers of this class.
1464      *
1465      * @return  the signers of this class, or null if there are no signers.  In
1466      *          particular, this method returns null if this {@code Class} object represents
1467      *          a primitive type or void.
1468      * @since   1.1
1469      */
1470     public native Object[] getSigners();
1471 
1472 
1473     /**
1474      * Set the signers of this class.
1475      */
1476     native void setSigners(Object[] signers);
1477 
1478 
1479     /**
1480      * If this {@code Class} object represents a local or anonymous
1481      * class within a method, returns a {@link
1482      * java.lang.reflect.Method Method} object representing the
1483      * immediately enclosing method of the underlying class. Returns
1484      * {@code null} otherwise.
1485      *
1486      * In particular, this method returns {@code null} if the underlying
1487      * class is a local or anonymous class immediately enclosed by a class or
1488      * interface declaration, instance initializer or static initializer.
1489      *
1490      * @return the immediately enclosing method of the underlying class, if
1491      *     that class is a local or anonymous class; otherwise {@code null}.
1492      *
1493      * @throws SecurityException
1494      *         If a security manager, <i>s</i>, is present and any of the
1495      *         following conditions is met:
1496      *
1497      *         <ul>
1498      *

1599                 // the immediately enclosing method or constructor's
1600                 // descriptor (null iff name is).
1601                 String descriptor = (String)enclosingInfo[2];
1602                 assert((name != null && descriptor != null) || name == descriptor);
1603             } catch (ClassCastException cce) {
1604                 throw new InternalError("Invalid type in enclosing method information", cce);
1605             }
1606         }
1607 
1608         EnclosingMethodInfo(Object[] enclosingInfo) {
1609             validate(enclosingInfo);
1610             this.enclosingClass = (Class<?>)enclosingInfo[0];
1611             this.name = (String)enclosingInfo[1];
1612             this.descriptor = (String)enclosingInfo[2];
1613         }
1614 
1615         boolean isPartial() {
1616             return enclosingClass == null || name == null || descriptor == null;
1617         }
1618 
1619         boolean isConstructor() { return !isPartial() && ConstantDescs.INIT_NAME.equals(name); }
1620 
1621         boolean isMethod() { return !isPartial() && !isConstructor() && !ConstantDescs.CLASS_INIT_NAME.equals(name); }




1622 
1623         Class<?> getEnclosingClass() { return enclosingClass; }
1624 
1625         String getName() { return name; }
1626 
1627         String getDescriptor() { return descriptor; }
1628 
1629     }
1630 
1631     private static Class<?> toClass(Type o) {
1632         if (o instanceof GenericArrayType gat)
1633             return toClass(gat.getGenericComponentType()).arrayType();
1634         return (Class<?>)o;
1635      }
1636 
1637     /**
1638      * If this {@code Class} object represents a local or anonymous
1639      * class within a constructor, returns a {@link
1640      * java.lang.reflect.Constructor Constructor} object representing
1641      * the immediately enclosing constructor of the underlying

1658      *         s.checkPermission} method with
1659      *         {@code RuntimePermission("accessDeclaredMembers")}
1660      *         denies access to the constructors within the enclosing class
1661      *
1662      *         <li> the caller's class loader is not the same as or an
1663      *         ancestor of the class loader for the enclosing class and
1664      *         invocation of {@link SecurityManager#checkPackageAccess
1665      *         s.checkPackageAccess()} denies access to the package
1666      *         of the enclosing class
1667      *
1668      *         </ul>
1669      * @since 1.5
1670      */
1671     @CallerSensitive
1672     public Constructor<?> getEnclosingConstructor() throws SecurityException {
1673         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1674 
1675         if (enclosingInfo == null)
1676             return null;
1677         else {
1678             if (!enclosingInfo.isConstructor())
1679                 return null;
1680 
1681             ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
1682                                                                         getFactory());
1683             Type []    parameterTypes   = typeInfo.getParameterTypes();
1684             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1685 
1686             // Convert Types to Classes; returned types *should*
1687             // be class objects since the methodDescriptor's used
1688             // don't have generics information
1689             for(int i = 0; i < parameterClasses.length; i++)
1690                 parameterClasses[i] = toClass(parameterTypes[i]);
1691 
1692             // Perform access check
1693             final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1694             @SuppressWarnings("removal")
1695             SecurityManager sm = System.getSecurityManager();
1696             if (sm != null) {
1697                 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED,
1698                                                      Reflection.getCallerClass(), true);

1841             simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1842         }
1843         return simpleName;
1844     }
1845 
1846     /**
1847      * Return an informative string for the name of this class or interface.
1848      *
1849      * @return an informative string for the name of this class or interface
1850      * @since 1.8
1851      */
1852     public String getTypeName() {
1853         if (isArray()) {
1854             try {
1855                 Class<?> cl = this;
1856                 int dimensions = 0;
1857                 do {
1858                     dimensions++;
1859                     cl = cl.getComponentType();
1860                 } while (cl.isArray());
1861                 return cl.getName().concat("[]".repeat(dimensions));
1862             } catch (Throwable e) { /*FALLTHRU*/ }
1863         }
1864         return getName();





1865     }
1866 
1867     /**
1868      * Returns the canonical name of the underlying class as
1869      * defined by <cite>The Java Language Specification</cite>.
1870      * Returns {@code null} if the underlying class does not have a canonical
1871      * name. Classes without canonical names include:
1872      * <ul>
1873      * <li>a {@linkplain #isLocalClass() local class}
1874      * <li>a {@linkplain #isAnonymousClass() anonymous class}
1875      * <li>an {@linkplain #isUnnamedClass() unnamed class}
1876      * <li>a {@linkplain #isHidden() hidden class}
1877      * <li>an array whose component type does not have a canonical name</li>
1878      * </ul>
1879      *
1880      * The canonical name for a primitive class is the keyword for the
1881      * corresponding primitive type ({@code byte}, {@code short},
1882      * {@code char}, {@code int}, and so on).
1883      *
1884      * <p>An array type has a canonical name if and only if its

3784                                               /* includeStatic */ false));
3785         }
3786 
3787         return res;
3788     }
3789 
3790     // Returns a "root" Constructor object. This Constructor object must NOT
3791     // be propagated to the outside world, but must instead be copied
3792     // via ReflectionFactory.copyConstructor.
3793     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3794                                         int which) throws NoSuchMethodException
3795     {
3796         ReflectionFactory fact = getReflectionFactory();
3797         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3798         for (Constructor<T> constructor : constructors) {
3799             if (arrayContentsEq(parameterTypes,
3800                                 fact.getExecutableSharedParameterTypes(constructor))) {
3801                 return constructor;
3802             }
3803         }
3804         throw new NoSuchMethodException(methodToString("<init>", parameterTypes));
3805     }
3806 
3807     //
3808     // Other helpers and base implementation
3809     //
3810 
3811     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3812         if (a1 == null) {
3813             return a2 == null || a2.length == 0;
3814         }
3815 
3816         if (a2 == null) {
3817             return a1.length == 0;
3818         }
3819 
3820         if (a1.length != a2.length) {
3821             return false;
3822         }
3823 
3824         for (int i = 0; i < a1.length; i++) {

4089         }
4090         return directory;
4091     }
4092     private transient volatile Map<String, T> enumConstantDirectory;
4093 
4094     /**
4095      * Casts an object to the class or interface represented
4096      * by this {@code Class} object.
4097      *
4098      * @param obj the object to be cast
4099      * @return the object after casting, or null if obj is null
4100      *
4101      * @throws ClassCastException if the object is not
4102      * null and is not assignable to the type T.
4103      *
4104      * @since 1.5
4105      */
4106     @SuppressWarnings("unchecked")
4107     @IntrinsicCandidate
4108     public T cast(Object obj) {



4109         if (obj != null && !isInstance(obj))
4110             throw new ClassCastException(cannotCastMsg(obj));
4111         return (T) obj;
4112     }
4113 
4114     private String cannotCastMsg(Object obj) {
4115         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
4116     }
4117 
4118     /**
4119      * Casts this {@code Class} object to represent a subclass of the class
4120      * represented by the specified class object.  Checks that the cast
4121      * is valid, and throws a {@code ClassCastException} if it is not.  If
4122      * this method succeeds, it always returns a reference to this {@code Class} object.
4123      *
4124      * <p>This method is useful when a client needs to "narrow" the type of
4125      * a {@code Class} object to pass it to an API that restricts the
4126      * {@code Class} objects that it is willing to accept.  A cast would
4127      * generate a compile-time warning, as the correctness of the cast
4128      * could not be checked at runtime (because generic types are implemented

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

4594      * interface, then this array class cannot be described nominally.
4595      * The result string is not a type descriptor.
4596      * </ul>
4597      *
4598      * <p> If this {@code Class} object represents a primitive type or
4599      * {@code void}, then the result is a field descriptor string which
4600      * is a one-letter code corresponding to a primitive type or {@code void}
4601      * ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}).
4602      *
4603      * @return the descriptor string for this {@code Class} object
4604      * @jvms 4.3.2 Field Descriptors
4605      * @since 12
4606      */
4607     @Override
4608     public String descriptorString() {
4609         if (isPrimitive())
4610             return Wrapper.forPrimitiveType(this).basicTypeString();
4611 
4612         if (isArray()) {
4613             return "[" + componentType.descriptorString();
4614         } else if (isHidden()) {


4615             String name = getName();
4616             int index = name.indexOf('/');
4617             return new StringBuilder(name.length() + 2)
4618                     .append('L')
4619                     .append(name.substring(0, index).replace('.', '/'))
4620                     .append('.')
4621                     .append(name, index + 1, name.length())
4622                     .append(';')
4623                     .toString();
4624         } else {
4625             String name = getName().replace('.', '/');
4626             return new StringBuilder(name.length() + 2)
4627                     .append('L')
4628                     .append(name)
4629                     .append(';')
4630                     .toString();
4631         }
4632     }
4633 
4634     /**
4635      * Returns the component type of this {@code Class}, if it describes
4636      * an array type, or {@code null} otherwise.
4637      *
4638      * @implSpec
4639      * Equivalent to {@link Class#getComponentType()}.
4640      *
4641      * @return a {@code Class} describing the component type, or {@code null}
4642      * if this {@code Class} does not describe an array type
4643      * @since 12
4644      */
4645     @Override
4646     public Class<?> componentType() {
4647         return isArray() ? componentType : null;

4785      * @since 17
4786      */
4787     public boolean isSealed() {
4788         if (isArray() || isPrimitive()) {
4789             return false;
4790         }
4791         return getPermittedSubclasses() != null;
4792     }
4793 
4794     private native Class<?>[] getPermittedSubclasses0();
4795 
4796     /*
4797      * Return the class's major and minor class file version packed into an int.
4798      * The high order 16 bits contain the class's minor version.  The low order
4799      * 16 bits contain the class's major version.
4800      *
4801      * If the class is an array type then the class file version of its element
4802      * type is returned.  If the class is a primitive type then the latest class
4803      * file major version is returned and zero is returned for the minor version.
4804      */
4805     private int getClassFileVersion() {

4806         Class<?> c = isArray() ? elementType() : this;
4807         return c.getClassFileVersion0();
4808     }
4809 
4810     private native int getClassFileVersion0();
4811 
4812     /*
4813      * Return the access flags as they were in the class's bytecode, including
4814      * the original setting of ACC_SUPER.
4815      *
4816      * If the class is an array type then the access flags of the element type is
4817      * returned.  If the class is a primitive then ACC_ABSTRACT | ACC_FINAL | ACC_PUBLIC.
4818      */
4819     private int getClassAccessFlagsRaw() {
4820         Class<?> c = isArray() ? elementType() : this;
4821         return c.getClassAccessFlagsRaw0();
4822     }
4823 
4824     private native int getClassAccessFlagsRaw0();
4825 }

  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 import java.lang.annotation.Annotation;
  29 import java.lang.constant.ClassDesc;
  30 import java.lang.constant.ConstantDescs;
  31 import java.lang.invoke.TypeDescriptor;
  32 import java.lang.invoke.MethodHandles;
  33 import java.lang.module.ModuleReader;
  34 import java.lang.ref.SoftReference;
  35 import java.io.IOException;
  36 import java.io.InputStream;
  37 import java.io.ObjectStreamField;
  38 import java.lang.reflect.AnnotatedElement;
  39 import java.lang.reflect.AnnotatedType;
  40 import java.lang.reflect.AccessFlag;
  41 import java.lang.reflect.Array;
  42 import java.lang.reflect.ClassFileFormatVersion;
  43 import java.lang.reflect.Constructor;
  44 import java.lang.reflect.Executable;
  45 import java.lang.reflect.Field;
  46 import java.lang.reflect.GenericArrayType;
  47 import java.lang.reflect.GenericDeclaration;
  48 import java.lang.reflect.InvocationTargetException;
  49 import java.lang.reflect.Member;
  50 import java.lang.reflect.Method;
  51 import java.lang.reflect.Modifier;
  52 import java.lang.reflect.Proxy;
  53 import java.lang.reflect.RecordComponent;
  54 import java.lang.reflect.Type;
  55 import java.lang.reflect.TypeVariable;
  56 import java.lang.constant.Constable;
  57 import java.net.URL;
  58 import java.security.AccessController;
  59 import java.security.PrivilegedAction;
  60 import java.util.ArrayList;
  61 import java.util.Arrays;
  62 import java.util.Collection;

  65 import java.util.LinkedHashMap;
  66 import java.util.LinkedHashSet;
  67 import java.util.List;
  68 import java.util.Map;
  69 import java.util.Objects;
  70 import java.util.Optional;
  71 import java.util.Set;
  72 import java.util.stream.Collectors;
  73 
  74 import jdk.internal.javac.PreviewFeature;
  75 import jdk.internal.loader.BootLoader;
  76 import jdk.internal.loader.BuiltinClassLoader;
  77 import jdk.internal.misc.PreviewFeatures;
  78 import jdk.internal.misc.Unsafe;
  79 import jdk.internal.module.Resources;
  80 import jdk.internal.reflect.CallerSensitive;
  81 import jdk.internal.reflect.CallerSensitiveAdapter;
  82 import jdk.internal.reflect.ConstantPool;
  83 import jdk.internal.reflect.Reflection;
  84 import jdk.internal.reflect.ReflectionFactory;
  85 import jdk.internal.value.PrimitiveClass;
  86 import jdk.internal.vm.annotation.ForceInline;
  87 import jdk.internal.vm.annotation.IntrinsicCandidate;
  88 
  89 import sun.invoke.util.Wrapper;
  90 import sun.reflect.generics.factory.CoreReflectionFactory;
  91 import sun.reflect.generics.factory.GenericsFactory;
  92 import sun.reflect.generics.repository.ClassRepository;
  93 import sun.reflect.generics.repository.MethodRepository;
  94 import sun.reflect.generics.repository.ConstructorRepository;
  95 import sun.reflect.generics.scope.ClassScope;
  96 import sun.security.util.SecurityConstants;
  97 import sun.reflect.annotation.*;
  98 import sun.reflect.misc.ReflectUtil;
  99 
 100 /**
 101  * Instances of the class {@code Class} represent classes and
 102  * interfaces in a running Java application. An enum class and a record
 103  * class are kinds of class; an annotation interface is a kind of
 104  * interface. Every array also belongs to a class that is reflected as
 105  * a {@code Class} object that is shared by all arrays with the same

 214  * {@linkplain #getTypeName type name} return results
 215  * equal to {@code "HelloWorld"}. The {@linkplain #getSimpleName
 216  * simple name} of such an unnamed class is the empty string and the
 217  * {@linkplain #getCanonicalName canonical name} is {@code null}.
 218  *
 219  * @param <T> the type of the class modeled by this {@code Class}
 220  * object.  For example, the type of {@code String.class} is {@code
 221  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
 222  * unknown.
 223  *
 224  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
 225  * @since   1.0
 226  * @jls 15.8.2 Class Literals
 227  */
 228 public final class Class<T> implements java.io.Serializable,
 229                               GenericDeclaration,
 230                               Type,
 231                               AnnotatedElement,
 232                               TypeDescriptor.OfField<Class<?>>,
 233                               Constable {
 234     private static final int ANNOTATION = 0x00002000;
 235     private static final int ENUM       = 0x00004000;
 236     private static final int SYNTHETIC  = 0x00001000;
 237 
 238     private static native void registerNatives();
 239     static {
 240         registerNatives();
 241     }
 242 
 243     /*
 244      * Private constructor. Only the Java Virtual Machine creates Class objects.
 245      * This constructor is not used and prevents the default constructor being
 246      * generated.
 247      */
 248     private Class(ClassLoader loader, Class<?> arrayComponentType) {
 249         // Initialize final field for classLoader.  The initialization value of non-null
 250         // prevents future JIT optimizations from assuming this final field is null.
 251         classLoader = loader;
 252         componentType = arrayComponentType;
 253     }
 254 
 255     /**
 256      * Converts the object to a string. The string representation is the
 257      * string "class" or "interface", followed by a space, and then by the
 258      * name of the class in the format returned by {@code getName}.
 259      * If this {@code Class} object represents a primitive type,
 260      * this method returns the name of the primitive type.  If
 261      * this {@code Class} object represents void this method returns
 262      * "void". If this {@code Class} object represents an array type,
 263      * this method returns "class " followed by {@code getName}.
 264      *
 265      * @return a string representation of this {@code Class} object.
 266      */
 267     public String toString() {
 268         String s = getName();
 269         if (isPrimitive()) {
 270             return s;
 271         }
 272         // Avoid invokedynamic based String concat, might be not available
 273         // Prepend type of class
 274         s = (isInterface() ? "interface " : "class ").concat(s);
 275         if (isValue()) {
 276             // prepend value class type
 277             s = (isPrimitiveClass() ? "primitive " : "value ").concat(s);
 278             if (isPrimitiveClass() && isPrimaryType()) {
 279                 // Append .ref
 280                 s = s.concat(".ref");
 281             }
 282         }
 283         return s;
 284     }
 285 
 286     /**
 287      * Returns a string describing this {@code Class}, including
 288      * information about modifiers and type parameters.
 289      *
 290      * The string is formatted as a list of type modifiers, if any,
 291      * followed by the kind of type (empty string for primitive types
 292      * and {@code class}, {@code enum}, {@code interface},
 293      * {@code @interface}, or {@code record} as appropriate), followed
 294      * by the type's name, followed by an angle-bracketed
 295      * comma-separated list of the type's type parameters, if any,
 296      * including informative bounds on the type parameters, if any.
 297      *
 298      * A space is used to separate modifiers from one another and to
 299      * separate any modifiers from the kind of type. The modifiers
 300      * occur in canonical order. If there are no type parameters, the
 301      * type parameter list is elided.
 302      *
 303      * For an array type, the string starts with the type name,

 316      *
 317      * @since 1.8
 318      */
 319     public String toGenericString() {
 320         if (isPrimitive()) {
 321             return toString();
 322         } else {
 323             StringBuilder sb = new StringBuilder();
 324             Class<?> component = this;
 325             int arrayDepth = 0;
 326 
 327             if (isArray()) {
 328                 do {
 329                     arrayDepth++;
 330                     component = component.getComponentType();
 331                 } while (component.isArray());
 332                 sb.append(component.getName());
 333             } else {
 334                 // Class modifiers are a superset of interface modifiers
 335                 int modifiers = getModifiers() & Modifier.classModifiers();
 336                 // Modifier.toString() below mis-interprets SYNCHRONIZED, STRICT, and VOLATILE bits
 337                 modifiers &= ~(Modifier.SYNCHRONIZED | Modifier.STRICT | Modifier.VOLATILE);
 338                 if (modifiers != 0) {
 339                     sb.append(Modifier.toString(modifiers));
 340                     sb.append(' ');
 341                 }
 342 
 343                 if (isAnnotation()) {
 344                     sb.append('@');
 345                 }
 346                 if (isValue()) {
 347                     sb.append(isPrimitiveClass() ? "primitive " : "value ");
 348                 }
 349                 if (isInterface()) { // Note: all annotation interfaces are interfaces
 350                     sb.append("interface");
 351                 } else {
 352                     if (isEnum())
 353                         sb.append("enum");
 354                     else if (isRecord())
 355                         sb.append("record");
 356                     else
 357                         sb.append("class");
 358                 }
 359                 sb.append(' ');
 360                 sb.append(getName());
 361             }
 362 
 363             TypeVariable<?>[] typeparms = component.getTypeParameters();
 364             if (typeparms.length > 0) {
 365                 sb.append(Arrays.stream(typeparms)
 366                           .map(Class::typeVarBounds)
 367                           .collect(Collectors.joining(",", "<", ">")));
 368             }

 543             throws ClassNotFoundException
 544     {
 545         @SuppressWarnings("removal")
 546         SecurityManager sm = System.getSecurityManager();
 547         if (sm != null) {
 548             // Reflective call to get caller class is only needed if a security manager
 549             // is present.  Avoid the overhead of making this call otherwise.
 550             if (loader == null) {
 551                 ClassLoader ccl = ClassLoader.getClassLoader(caller);
 552                 if (ccl != null) {
 553                     sm.checkPermission(
 554                             SecurityConstants.GET_CLASSLOADER_PERMISSION);
 555                 }
 556             }
 557         }
 558         return forName0(name, initialize, loader, caller);
 559     }
 560 
 561     /** Called after security check for system loader access checks have been made. */
 562     private static native Class<?> forName0(String name, boolean initialize,
 563                                     ClassLoader loader,
 564                                     Class<?> caller)
 565         throws ClassNotFoundException;
 566 
 567 
 568     /**
 569      * Returns the {@code Class} with the given {@linkplain ClassLoader##binary-name
 570      * binary name} in the given module.
 571      *
 572      * <p> This method attempts to locate and load the class or interface.
 573      * It does not link the class, and does not run the class initializer.
 574      * If the class is not found, this method returns {@code null}. </p>
 575      *
 576      * <p> If the class loader of the given module defines other modules and
 577      * the given name is a class defined in a different module, this method
 578      * returns {@code null} after the class is loaded. </p>
 579      *
 580      * <p> This method does not check whether the requested class is
 581      * accessible to its caller. </p>
 582      *
 583      * @apiNote
 584      * This method does not support loading of array types, unlike

 635         SecurityManager sm = System.getSecurityManager();
 636         if (sm != null) {
 637             if (caller != null && caller.getModule() != module) {
 638                 // if caller is null, Class.forName is the last java frame on the stack.
 639                 // java.base has all permissions
 640                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 641             }
 642             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
 643             cl = AccessController.doPrivileged(pa);
 644         } else {
 645             cl = module.getClassLoader();
 646         }
 647 
 648         if (cl != null) {
 649             return cl.loadClass(module, name);
 650         } else {
 651             return BootLoader.loadClass(module, name);
 652         }
 653     }
 654 
 655     // set by VM if this class is an exotic type such as primitive class
 656     // otherwise, these two fields are null
 657     private transient Class<T> primaryType;
 658     private transient Class<T> secondaryType;
 659 
 660     /**
 661      * Returns {@code true} if this class is a primitive class.
 662      * <p>
 663      * Each primitive class has a {@linkplain #isPrimaryType() primary type}
 664      * representing the <em>primitive reference type</em> and a
 665      * {@linkplain #isPrimitiveValueType() secondary type} representing
 666      * the <em>primitive value type</em>.  The primitive reference type
 667      * and primitive value type can be obtained by calling the
 668      * {@link #asPrimaryType()} and {@link #asValueType} method
 669      * of a primitive class respectively.
 670      * <p>
 671      * A primitive class is a {@linkplain #isValue() value class}.
 672      *
 673      * @return {@code true} if this class is a primitive class, otherwise {@code false}
 674      * @see #isValue()
 675      * @see #asPrimaryType()
 676      * @see #asValueType()
 677      * @since Valhalla
 678      */
 679     /* package */ boolean isPrimitiveClass() {
 680         return (this.getModifiers() & PrimitiveClass.PRIMITIVE_CLASS) != 0;
 681     }
 682 
 683     /**
 684      * {@return {@code true} if this {@code Class} object represents an identity
 685      * class or interface; otherwise {@code false}}
 686      *
 687      * If this {@code Class} object represents an array type, then this method
 688      * returns {@code true}.
 689      * If this {@code Class} object represents a primitive type, or {@code void},
 690      * then this method returns {@code false}.
 691      *
 692      * @since Valhalla
 693      */
 694     @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS)
 695     public native boolean isIdentity();
 696 
 697     /**
 698      * {@return {@code true} if this {@code Class} object represents a value
 699      * class or interface; otherwise {@code false}}
 700      *
 701      * If this {@code Class} object represents an array type, a primitive type, or
 702      * {@code void}, then this method returns {@code false}.
 703      *
 704      * @since Valhalla
 705      */
 706     @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS)
 707     public boolean isValue() {
 708         return (this.getModifiers() & Modifier.VALUE) != 0;
 709     }
 710 
 711     /**
 712      * Returns a {@code Class} object representing the primary type
 713      * of this class or interface.
 714      * <p>
 715      * If this {@code Class} object represents a primitive type or an array type,
 716      * then this method returns this class.
 717      * <p>
 718      * If this {@code Class} object represents a {@linkplain #isPrimitiveClass()
 719      * primitive class}, then this method returns the <em>primitive reference type</em>
 720      * type of this primitive class.
 721      * <p>
 722      * Otherwise, this {@code Class} object represents a non-primitive class or interface
 723      * and this method returns this class.
 724      *
 725      * @return the {@code Class} representing the primary type of
 726      *         this class or interface
 727      * @since Valhalla
 728      */
 729     @IntrinsicCandidate
 730     /* package */ Class<?> asPrimaryType() {
 731         return isPrimitiveClass() ? primaryType : this;
 732     }
 733 
 734     /**
 735      * Returns a {@code Class} object representing the <em>primitive value type</em>
 736      * of this class if this class is a {@linkplain #isPrimitiveClass() primitive class}.
 737      *
 738      * @apiNote Alternatively, this method returns null if this class is not
 739      *          a primitive class rather than throwing UOE.
 740      *
 741      * @return the {@code Class} representing the {@linkplain #isPrimitiveValueType()
 742      * primitive value type} of this class if this class is a primitive class
 743      * @throws UnsupportedOperationException if this class or interface
 744      *         is not a primitive class
 745      * @since Valhalla
 746      */
 747     @IntrinsicCandidate
 748     /* package */ Class<?> asValueType() {
 749         if (isPrimitiveClass())
 750             return secondaryType;
 751 
 752         throw new UnsupportedOperationException(this.getName().concat(" is not a primitive class"));
 753     }
 754 
 755     /**
 756      * Returns {@code true} if this {@code Class} object represents the primary type
 757      * of this class or interface.
 758      * <p>
 759      * If this {@code Class} object represents a primitive type or an array type,
 760      * then this method returns {@code true}.
 761      * <p>
 762      * If this {@code Class} object represents a {@linkplain #isPrimitiveClass()
 763      * primitive}, then this method returns {@code true} if this {@code Class}
 764      * object represents a primitive reference type, or returns {@code false}
 765      * if this {@code Class} object represents a primitive value type.
 766      * <p>
 767      * If this {@code Class} object represents a non-primitive class or interface,
 768      * then this method returns {@code true}.
 769      *
 770      * @return {@code true} if this {@code Class} object represents
 771      * the primary type of this class or interface
 772      * @since Valhalla
 773      */
 774     /* package */ boolean isPrimaryType() {
 775         if (isPrimitiveClass()) {
 776             return this == primaryType;
 777         }
 778         return true;
 779     }
 780 
 781     /**
 782      * Returns {@code true} if this {@code Class} object represents
 783      * a {@linkplain #isPrimitiveClass() primitive} value type.
 784      *
 785      * @return {@code true} if this {@code Class} object represents
 786      * the value type of a primitive class
 787      * @since Valhalla
 788      */
 789     /* package */ boolean isPrimitiveValueType() {
 790         return isPrimitiveClass() && this == secondaryType;
 791     }
 792 
 793     /**
 794      * {@return the {@code Class} object associated with the
 795      * {@linkplain #isPrimitive() primitive type} of the given name}
 796      * If the argument is not the name of a primitive type, {@code
 797      * null} is returned.
 798      *
 799      * @param primitiveName the name of the primitive type to find
 800      *
 801      * @throws NullPointerException if the argument is {@code null}
 802      *
 803      * @jls 4.2 Primitive Types and Values
 804      * @jls 15.8.2 Class Literals
 805      * @since 22
 806      */
 807     public static Class<?> forPrimitiveName(String primitiveName) {
 808         return switch(primitiveName) {
 809         // Integral types
 810         case "int"     -> int.class;
 811         case "long"    -> long.class;
 812         case "short"   -> short.class;

1529      * If this class does not represent an array class, then this method returns
1530      * {@code null}.
1531      */
1532     private Class<?> elementType() {
1533         if (!isArray()) return null;
1534 
1535         Class<?> c = this;
1536         while (c.isArray()) {
1537             c = c.getComponentType();
1538         }
1539         return c;
1540     }
1541 
1542     /**
1543      * Returns the Java language modifiers for this class or interface, encoded
1544      * in an integer. The modifiers consist of the Java Virtual Machine's
1545      * constants for {@code public}, {@code protected},
1546      * {@code private}, {@code final}, {@code static},
1547      * {@code abstract} and {@code interface}; they should be decoded
1548      * using the methods of class {@code Modifier}.
1549      * The modifiers also include the Java Virtual Machine's constants for
1550      * {@code identity class} and {@code value class}.
1551      *
1552      * <p> If the underlying class is an array class:
1553      * <ul>
1554      * <li> its {@code public}, {@code private} and {@code protected}
1555      *      modifiers are the same as those of its component type
1556      * <li> its {@code abstract} and {@code final} modifiers are always
1557      *      {@code true}
1558      * <li> its interface modifier is always {@code false}, even when
1559      *      the component type is an interface
1560      * </ul>
1561      * If this {@code Class} object represents a primitive type or
1562      * void, its {@code public}, {@code abstract}, and {@code final}
1563      * modifiers are always {@code true}.
1564      * For {@code Class} objects representing void, primitive types, and
1565      * arrays, the values of other modifiers are {@code false} other
1566      * than as specified above.
1567      *
1568      * <p> The modifier encodings are defined in section {@jvms 4.1}
1569      * of <cite>The Java Virtual Machine Specification</cite>.
1570      *
1571      * @return the {@code int} representing the modifiers for this class
1572      * @see     java.lang.reflect.Modifier
1573      * @see #accessFlags()
1574      * @see <a
1575      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1576      * programming language and JVM modeling in core reflection</a>
1577      * @since 1.1
1578      * @jls 8.1.1 Class Modifiers
1579      * @jls 9.1.1. Interface Modifiers
1580      * @jvms 4.1 The {@code ClassFile} Structure
1581      */
1582     @IntrinsicCandidate
1583     public native int getModifiers();
1584 
1585    /**
1586      * {@return an unmodifiable set of the {@linkplain AccessFlag access
1587      * flags} for this class, possibly empty}
1588      * The {@code AccessFlags} may depend on the class file format version of the class.
1589      *
1590      * <p> If the underlying class is an array class:
1591      * <ul>
1592      * <li> its {@code PUBLIC}, {@code PRIVATE} and {@code PROTECTED}
1593      *      access flags are the same as those of its component type
1594      * <li> its {@code ABSTRACT} and {@code FINAL} flags are present
1595      * <li> its {@code INTERFACE} flag is absent, even when the
1596      *      component type is an interface
1597      * </ul>
1598      * If this {@code Class} object represents a primitive type or
1599      * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
1600      * {@code FINAL}.
1601      * For {@code Class} objects representing void, primitive types, and
1602      * arrays, access flags are absent other than as specified above.
1603      *
1604      * @see #getModifiers()
1605      * @jvms 4.1 The ClassFile Structure
1606      * @jvms 4.7.6 The InnerClasses Attribute
1607      * @since 20
1608      */
1609     public Set<AccessFlag> accessFlags() {
1610         // Location.CLASS allows SUPER and AccessFlag.MODULE which
1611         // INNER_CLASS forbids. INNER_CLASS allows PRIVATE, PROTECTED,
1612         // and STATIC, which are not allowed on Location.CLASS.
1613         // Use getClassAccessFlagsRaw to expose SUPER status.
1614         var location = (isMemberClass() || isLocalClass() ||
1615                         isAnonymousClass() || isArray()) ?
1616             AccessFlag.Location.INNER_CLASS :
1617             AccessFlag.Location.CLASS;
1618         int accessFlags = (location == AccessFlag.Location.CLASS) ?
1619                 getClassAccessFlagsRaw() : getModifiers();
1620         var cffv = ClassFileFormatVersion.fromMajor(getClassFileVersion() & 0xffff);
1621         if (cffv.compareTo(ClassFileFormatVersion.latest()) >= 0) {
1622             // Ignore unspecified (0x800) access flag for current version
1623             accessFlags &= ~0x0800;
1624         }
1625         return AccessFlag.maskToAccessFlags(accessFlags, location, cffv);
1626     }
1627 
1628    /**
1629      * Gets the signers of this class.
1630      *
1631      * @return  the signers of this class, or null if there are no signers.  In
1632      *          particular, this method returns null if this {@code Class} object represents
1633      *          a primitive type or void.
1634      * @since   1.1
1635      */
1636     public native Object[] getSigners();
1637 

1638     /**
1639      * Set the signers of this class.
1640      */
1641     native void setSigners(Object[] signers);
1642 

1643     /**
1644      * If this {@code Class} object represents a local or anonymous
1645      * class within a method, returns a {@link
1646      * java.lang.reflect.Method Method} object representing the
1647      * immediately enclosing method of the underlying class. Returns
1648      * {@code null} otherwise.
1649      *
1650      * In particular, this method returns {@code null} if the underlying
1651      * class is a local or anonymous class immediately enclosed by a class or
1652      * interface declaration, instance initializer or static initializer.
1653      *
1654      * @return the immediately enclosing method of the underlying class, if
1655      *     that class is a local or anonymous class; otherwise {@code null}.
1656      *
1657      * @throws SecurityException
1658      *         If a security manager, <i>s</i>, is present and any of the
1659      *         following conditions is met:
1660      *
1661      *         <ul>
1662      *

1763                 // the immediately enclosing method or constructor's
1764                 // descriptor (null iff name is).
1765                 String descriptor = (String)enclosingInfo[2];
1766                 assert((name != null && descriptor != null) || name == descriptor);
1767             } catch (ClassCastException cce) {
1768                 throw new InternalError("Invalid type in enclosing method information", cce);
1769             }
1770         }
1771 
1772         EnclosingMethodInfo(Object[] enclosingInfo) {
1773             validate(enclosingInfo);
1774             this.enclosingClass = (Class<?>)enclosingInfo[0];
1775             this.name = (String)enclosingInfo[1];
1776             this.descriptor = (String)enclosingInfo[2];
1777         }
1778 
1779         boolean isPartial() {
1780             return enclosingClass == null || name == null || descriptor == null;
1781         }
1782 
1783         boolean isObjectConstructor() { return !isPartial() && ConstantDescs.INIT_NAME.equals(name); }
1784 
1785         boolean isValueFactoryMethod() { return !isPartial() && ConstantDescs.VNEW_NAME.equals(name); }
1786 
1787         boolean isMethod() { return !isPartial() && !isObjectConstructor()
1788                                         && !isValueFactoryMethod()
1789                                         && !ConstantDescs.CLASS_INIT_NAME.equals(name); }
1790 
1791         Class<?> getEnclosingClass() { return enclosingClass; }
1792 
1793         String getName() { return name; }
1794 
1795         String getDescriptor() { return descriptor; }
1796 
1797     }
1798 
1799     private static Class<?> toClass(Type o) {
1800         if (o instanceof GenericArrayType gat)
1801             return toClass(gat.getGenericComponentType()).arrayType();
1802         return (Class<?>)o;
1803      }
1804 
1805     /**
1806      * If this {@code Class} object represents a local or anonymous
1807      * class within a constructor, returns a {@link
1808      * java.lang.reflect.Constructor Constructor} object representing
1809      * the immediately enclosing constructor of the underlying

1826      *         s.checkPermission} method with
1827      *         {@code RuntimePermission("accessDeclaredMembers")}
1828      *         denies access to the constructors within the enclosing class
1829      *
1830      *         <li> the caller's class loader is not the same as or an
1831      *         ancestor of the class loader for the enclosing class and
1832      *         invocation of {@link SecurityManager#checkPackageAccess
1833      *         s.checkPackageAccess()} denies access to the package
1834      *         of the enclosing class
1835      *
1836      *         </ul>
1837      * @since 1.5
1838      */
1839     @CallerSensitive
1840     public Constructor<?> getEnclosingConstructor() throws SecurityException {
1841         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1842 
1843         if (enclosingInfo == null)
1844             return null;
1845         else {
1846             if (!enclosingInfo.isObjectConstructor() && !enclosingInfo.isValueFactoryMethod())
1847                 return null;
1848 
1849             ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
1850                                                                         getFactory());
1851             Type []    parameterTypes   = typeInfo.getParameterTypes();
1852             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1853 
1854             // Convert Types to Classes; returned types *should*
1855             // be class objects since the methodDescriptor's used
1856             // don't have generics information
1857             for(int i = 0; i < parameterClasses.length; i++)
1858                 parameterClasses[i] = toClass(parameterTypes[i]);
1859 
1860             // Perform access check
1861             final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1862             @SuppressWarnings("removal")
1863             SecurityManager sm = System.getSecurityManager();
1864             if (sm != null) {
1865                 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED,
1866                                                      Reflection.getCallerClass(), true);

2009             simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
2010         }
2011         return simpleName;
2012     }
2013 
2014     /**
2015      * Return an informative string for the name of this class or interface.
2016      *
2017      * @return an informative string for the name of this class or interface
2018      * @since 1.8
2019      */
2020     public String getTypeName() {
2021         if (isArray()) {
2022             try {
2023                 Class<?> cl = this;
2024                 int dimensions = 0;
2025                 do {
2026                     dimensions++;
2027                     cl = cl.getComponentType();
2028                 } while (cl.isArray());
2029                 return cl.getTypeName().concat("[]".repeat(dimensions));
2030             } catch (Throwable e) { /*FALLTHRU*/ }
2031         }
2032         if (isPrimitiveClass()) {
2033             // TODO: null-default
2034             return isPrimaryType() ? getName().concat(".ref") : getName();
2035         } else {
2036             return getName();
2037         }
2038     }
2039 
2040     /**
2041      * Returns the canonical name of the underlying class as
2042      * defined by <cite>The Java Language Specification</cite>.
2043      * Returns {@code null} if the underlying class does not have a canonical
2044      * name. Classes without canonical names include:
2045      * <ul>
2046      * <li>a {@linkplain #isLocalClass() local class}
2047      * <li>a {@linkplain #isAnonymousClass() anonymous class}
2048      * <li>an {@linkplain #isUnnamedClass() unnamed class}
2049      * <li>a {@linkplain #isHidden() hidden class}
2050      * <li>an array whose component type does not have a canonical name</li>
2051      * </ul>
2052      *
2053      * The canonical name for a primitive class is the keyword for the
2054      * corresponding primitive type ({@code byte}, {@code short},
2055      * {@code char}, {@code int}, and so on).
2056      *
2057      * <p>An array type has a canonical name if and only if its

3957                                               /* includeStatic */ false));
3958         }
3959 
3960         return res;
3961     }
3962 
3963     // Returns a "root" Constructor object. This Constructor object must NOT
3964     // be propagated to the outside world, but must instead be copied
3965     // via ReflectionFactory.copyConstructor.
3966     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3967                                         int which) throws NoSuchMethodException
3968     {
3969         ReflectionFactory fact = getReflectionFactory();
3970         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3971         for (Constructor<T> constructor : constructors) {
3972             if (arrayContentsEq(parameterTypes,
3973                                 fact.getExecutableSharedParameterTypes(constructor))) {
3974                 return constructor;
3975             }
3976         }
3977         throw new NoSuchMethodException(methodToString(isValue() ? "<vnew>" : "<init>", parameterTypes));
3978     }
3979 
3980     //
3981     // Other helpers and base implementation
3982     //
3983 
3984     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3985         if (a1 == null) {
3986             return a2 == null || a2.length == 0;
3987         }
3988 
3989         if (a2 == null) {
3990             return a1.length == 0;
3991         }
3992 
3993         if (a1.length != a2.length) {
3994             return false;
3995         }
3996 
3997         for (int i = 0; i < a1.length; i++) {

4262         }
4263         return directory;
4264     }
4265     private transient volatile Map<String, T> enumConstantDirectory;
4266 
4267     /**
4268      * Casts an object to the class or interface represented
4269      * by this {@code Class} object.
4270      *
4271      * @param obj the object to be cast
4272      * @return the object after casting, or null if obj is null
4273      *
4274      * @throws ClassCastException if the object is not
4275      * null and is not assignable to the type T.
4276      *
4277      * @since 1.5
4278      */
4279     @SuppressWarnings("unchecked")
4280     @IntrinsicCandidate
4281     public T cast(Object obj) {
4282         if (isPrimitiveValueType() && obj == null)
4283             throw new NullPointerException(getName() + " is a primitive value type");
4284 
4285         if (obj != null && !isInstance(obj))
4286             throw new ClassCastException(cannotCastMsg(obj));
4287         return (T) obj;
4288     }
4289 
4290     private String cannotCastMsg(Object obj) {
4291         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
4292     }
4293 
4294     /**
4295      * Casts this {@code Class} object to represent a subclass of the class
4296      * represented by the specified class object.  Checks that the cast
4297      * is valid, and throws a {@code ClassCastException} if it is not.  If
4298      * this method succeeds, it always returns a reference to this {@code Class} object.
4299      *
4300      * <p>This method is useful when a client needs to "narrow" the type of
4301      * a {@code Class} object to pass it to an API that restricts the
4302      * {@code Class} objects that it is willing to accept.  A cast would
4303      * generate a compile-time warning, as the correctness of the cast
4304      * could not be checked at runtime (because generic types are implemented

4560      *
4561      * <p> If this {@code Class} object represents an interface, the return
4562      * value is an array containing objects representing the uses of interface
4563      * types to specify interfaces directly extended by the interface. The
4564      * order of the objects in the array corresponds to the order of the
4565      * interface types used in the 'extends' clause of the declaration of this
4566      * {@code Class} object.
4567      *
4568      * <p> If this {@code Class} object represents a class or interface whose
4569      * declaration does not explicitly indicate any annotated superinterfaces,
4570      * the return value is an array of length 0.
4571      *
4572      * <p> If this {@code Class} object represents either the {@code Object}
4573      * class, an array type, a primitive type, or void, the return value is an
4574      * array of length 0.
4575      *
4576      * @return an array representing the superinterfaces
4577      * @since 1.8
4578      */
4579     public AnnotatedType[] getAnnotatedInterfaces() {
4580         return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
4581     }
4582 
4583     private native Class<?> getNestHost0();
4584 
4585     /**
4586      * Returns the nest host of the <a href=#nest>nest</a> to which the class
4587      * or interface represented by this {@code Class} object belongs.
4588      * Every class and interface belongs to exactly one nest.
4589      *
4590      * If the nest host of this class or interface has previously
4591      * been determined, then this method returns the nest host.
4592      * If the nest host of this class or interface has
4593      * not previously been determined, then this method determines the nest
4594      * host using the algorithm of JVMS 5.4.4, and returns it.
4595      *
4596      * Often, a class or interface belongs to a nest consisting only of itself,
4597      * in which case this method returns {@code this} to indicate that the class
4598      * or interface is the nest host.
4599      *
4600      * <p>If this {@code Class} object represents a primitive type, an array type,

4770      * interface, then this array class cannot be described nominally.
4771      * The result string is not a type descriptor.
4772      * </ul>
4773      *
4774      * <p> If this {@code Class} object represents a primitive type or
4775      * {@code void}, then the result is a field descriptor string which
4776      * is a one-letter code corresponding to a primitive type or {@code void}
4777      * ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}).
4778      *
4779      * @return the descriptor string for this {@code Class} object
4780      * @jvms 4.3.2 Field Descriptors
4781      * @since 12
4782      */
4783     @Override
4784     public String descriptorString() {
4785         if (isPrimitive())
4786             return Wrapper.forPrimitiveType(this).basicTypeString();
4787 
4788         if (isArray()) {
4789             return "[" + componentType.descriptorString();
4790         }
4791         char typeDesc = isPrimitiveValueType() ? 'Q' : 'L';
4792         if (isHidden()) {
4793             String name = getName();
4794             int index = name.indexOf('/');
4795             return new StringBuilder(name.length() + 2)
4796                     .append(typeDesc)
4797                     .append(name.substring(0, index).replace('.', '/'))
4798                     .append('.')
4799                     .append(name, index + 1, name.length())
4800                     .append(';')
4801                     .toString();
4802         } else {
4803             String name = getName().replace('.', '/');
4804             return new StringBuilder(name.length() + 2)
4805                     .append(typeDesc)
4806                     .append(name)
4807                     .append(';')
4808                     .toString();
4809         }
4810     }
4811 
4812     /**
4813      * Returns the component type of this {@code Class}, if it describes
4814      * an array type, or {@code null} otherwise.
4815      *
4816      * @implSpec
4817      * Equivalent to {@link Class#getComponentType()}.
4818      *
4819      * @return a {@code Class} describing the component type, or {@code null}
4820      * if this {@code Class} does not describe an array type
4821      * @since 12
4822      */
4823     @Override
4824     public Class<?> componentType() {
4825         return isArray() ? componentType : null;

4963      * @since 17
4964      */
4965     public boolean isSealed() {
4966         if (isArray() || isPrimitive()) {
4967             return false;
4968         }
4969         return getPermittedSubclasses() != null;
4970     }
4971 
4972     private native Class<?>[] getPermittedSubclasses0();
4973 
4974     /*
4975      * Return the class's major and minor class file version packed into an int.
4976      * The high order 16 bits contain the class's minor version.  The low order
4977      * 16 bits contain the class's major version.
4978      *
4979      * If the class is an array type then the class file version of its element
4980      * type is returned.  If the class is a primitive type then the latest class
4981      * file major version is returned and zero is returned for the minor version.
4982      */
4983     /* package-private */
4984     int getClassFileVersion() {
4985         Class<?> c = isArray() ? elementType() : this;
4986         return c.getClassFileVersion0();
4987     }
4988 
4989     private native int getClassFileVersion0();
4990 
4991     /*
4992      * Return the access flags as they were in the class's bytecode, including
4993      * the original setting of ACC_SUPER.
4994      *
4995      * If the class is an array type then the access flags of the element type is
4996      * returned.  If the class is a primitive then ACC_ABSTRACT | ACC_FINAL | ACC_PUBLIC.
4997      */
4998     private int getClassAccessFlagsRaw() {
4999         Class<?> c = isArray() ? elementType() : this;
5000         return c.getClassAccessFlagsRaw0();
5001     }
5002 
5003     private native int getClassAccessFlagsRaw0();
5004 }
< prev index next >