1 /*
   2  * Copyright (c) 1994, 2022, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  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.invoke.TypeDescriptor;
  31 import java.lang.invoke.MethodHandles;
  32 import java.lang.module.ModuleReader;
  33 import java.lang.ref.SoftReference;
  34 import java.io.IOException;
  35 import java.io.InputStream;
  36 import java.io.ObjectStreamField;
  37 import java.lang.reflect.AnnotatedElement;
  38 import java.lang.reflect.AnnotatedType;
  39 import java.lang.reflect.Array;
  40 import java.lang.reflect.Constructor;
  41 import java.lang.reflect.Executable;
  42 import java.lang.reflect.Field;
  43 import java.lang.reflect.GenericArrayType;
  44 import java.lang.reflect.GenericDeclaration;
  45 import java.lang.reflect.InvocationTargetException;
  46 import java.lang.reflect.Member;
  47 import java.lang.reflect.Method;
  48 import java.lang.reflect.Modifier;
  49 import java.lang.reflect.Proxy;
  50 import java.lang.reflect.RecordComponent;
  51 import java.lang.reflect.Type;
  52 import java.lang.reflect.TypeVariable;
  53 import java.lang.constant.Constable;
  54 import java.net.URL;
  55 import java.security.AccessController;
  56 import java.security.PrivilegedAction;
  57 import java.util.ArrayList;
  58 import java.util.Arrays;
  59 import java.util.Collection;
  60 import java.util.HashMap;
  61 import java.util.HashSet;
  62 import java.util.LinkedHashMap;
  63 import java.util.LinkedHashSet;
  64 import java.util.List;
  65 import java.util.Map;
  66 import java.util.Objects;
  67 import java.util.Optional;
  68 import java.util.Set;
  69 import java.util.stream.Collectors;
  70 
  71 import jdk.internal.loader.BootLoader;
  72 import jdk.internal.loader.BuiltinClassLoader;
  73 import jdk.internal.misc.Unsafe;
  74 import jdk.internal.module.Resources;
  75 import jdk.internal.reflect.CallerSensitive;
  76 import jdk.internal.reflect.CallerSensitiveAdapter;
  77 import jdk.internal.reflect.ConstantPool;
  78 import jdk.internal.reflect.Reflection;
  79 import jdk.internal.reflect.ReflectionFactory;
  80 import jdk.internal.vm.annotation.ForceInline;
  81 import jdk.internal.vm.annotation.IntrinsicCandidate;
  82 import sun.invoke.util.Wrapper;
  83 import sun.reflect.generics.factory.CoreReflectionFactory;
  84 import sun.reflect.generics.factory.GenericsFactory;
  85 import sun.reflect.generics.repository.ClassRepository;
  86 import sun.reflect.generics.repository.MethodRepository;
  87 import sun.reflect.generics.repository.ConstructorRepository;
  88 import sun.reflect.generics.scope.ClassScope;
  89 import sun.security.util.SecurityConstants;
  90 import sun.reflect.annotation.*;
  91 import sun.reflect.misc.ReflectUtil;
  92 
  93 /**
  94  * Instances of the class {@code Class} represent classes and
  95  * interfaces in a running Java application. An enum class and a record
  96  * class are kinds of class; an annotation interface is a kind of
  97  * interface. Every array also belongs to a class that is reflected as
  98  * a {@code Class} object that is shared by all arrays with the same
  99  * element type and number of dimensions.  The primitive Java types
 100  * ({@code boolean}, {@code byte}, {@code char}, {@code short}, {@code
 101  * int}, {@code long}, {@code float}, and {@code double}), and the
 102  * keyword {@code void} are also represented as {@code Class} objects.
 103  *
 104  * <p> {@code Class} has no public constructor. Instead a {@code Class}
 105  * object is constructed automatically by the Java Virtual Machine when
 106  * a class is derived from the bytes of a {@code class} file through
 107  * the invocation of one of the following methods:
 108  * <ul>
 109  * <li> {@link ClassLoader#defineClass(String, byte[], int, int) ClassLoader::defineClass}
 110  * <li> {@link java.lang.invoke.MethodHandles.Lookup#defineClass(byte[])
 111  *      java.lang.invoke.MethodHandles.Lookup::defineClass}
 112  * <li> {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
 113  *      java.lang.invoke.MethodHandles.Lookup::defineHiddenClass}
 114  * </ul>
 115  *
 116  * <p> The methods of class {@code Class} expose many characteristics of a
 117  * class or interface. Most characteristics are derived from the {@code class}
 118  * file that the class loader passed to the Java Virtual Machine or
 119  * from the {@code class} file passed to {@code Lookup::defineClass}
 120  * or {@code Lookup::defineHiddenClass}.
 121  * A few characteristics are determined by the class loading environment
 122  * at run time, such as the module returned by {@link #getModule() getModule()}.
 123  *
 124  * <p> The following example uses a {@code Class} object to print the
 125  * class name of an object:
 126  *
 127  * <blockquote><pre>
 128  *     void printClassName(Object obj) {
 129  *         System.out.println("The class of " + obj +
 130  *                            " is " + obj.getClass().getName());
 131  *     }
 132  * </pre></blockquote>
 133  *
 134  * It is also possible to get the {@code Class} object for a named
 135  * class or interface (or for {@code void}) using a <i>class literal</i>.
 136  * For example:
 137  *
 138  * <blockquote>
 139  *     {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
 140  * </blockquote>
 141  *
 142  * <p> Some methods of class {@code Class} expose whether the declaration of
 143  * a class or interface in Java source code was <em>enclosed</em> within
 144  * another declaration. Other methods describe how a class or interface
 145  * is situated in a <em>nest</em>. A <a id="nest">nest</a> is a set of
 146  * classes and interfaces, in the same run-time package, that
 147  * allow mutual access to their {@code private} members.
 148  * The classes and interfaces are known as <em>nestmates</em>.
 149  * One nestmate acts as the
 150  * <em>nest host</em>, and enumerates the other nestmates which
 151  * belong to the nest; each of them in turn records it as the nest host.
 152  * The classes and interfaces which belong to a nest, including its host, are
 153  * determined when
 154  * {@code class} files are generated, for example, a Java compiler
 155  * will typically record a top-level class as the host of a nest where the
 156  * other members are the classes and interfaces whose declarations are
 157  * enclosed within the top-level class declaration.
 158  *
 159  * <p> A class or interface created by the invocation of
 160  * {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
 161  * Lookup::defineHiddenClass} is a {@linkplain Class#isHidden() <em>hidden</em>}
 162  * class or interface.
 163  * All kinds of class, including enum classes and record classes, may be
 164  * hidden classes; all kinds of interface, including annotation interfaces,
 165  * may be hidden interfaces.
 166  *
 167  * The {@linkplain #getName() name of a hidden class or interface} is
 168  * not a <a href="ClassLoader.html#binary-name">binary name</a>,
 169  * which means the following:
 170  * <ul>
 171  * <li>A hidden class or interface cannot be referenced by the constant pools
 172  *     of other classes and interfaces.
 173  * <li>A hidden class or interface cannot be described in
 174  *     {@linkplain java.lang.constant.ConstantDesc <em>nominal form</em>} by
 175  *     {@link #describeConstable() Class::describeConstable},
 176  *     {@link ClassDesc#of(String) ClassDesc::of}, or
 177  *     {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor}.
 178  * <li>A hidden class or interface cannot be discovered by {@link #forName Class::forName}
 179  *     or {@link ClassLoader#loadClass(String, boolean) ClassLoader::loadClass}.
 180  * </ul>
 181  *
 182  * A hidden class or interface is never an array class, but may be
 183  * the element type of an array. In all other respects, the fact that
 184  * a class or interface is hidden has no bearing on the characteristics
 185  * exposed by the methods of class {@code Class}.
 186  *
 187  * @param <T> the type of the class modeled by this {@code Class}
 188  * object.  For example, the type of {@code String.class} is {@code
 189  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
 190  * unknown.
 191  *
 192  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
 193  * @since   1.0
 194  * @jls 15.8.2 Class Literals
 195  */
 196 public final class Class<T> implements java.io.Serializable,
 197                               GenericDeclaration,
 198                               Type,
 199                               AnnotatedElement,
 200                               TypeDescriptor.OfField<Class<?>>,
 201                               Constable {
 202     private static final int ANNOTATION= 0x00002000;
 203     private static final int ENUM      = 0x00004000;
 204     private static final int SYNTHETIC = 0x00001000;
 205 
 206     private static native void registerNatives();
 207     static {
 208         registerNatives();
 209     }
 210 
 211     /*
 212      * Private constructor. Only the Java Virtual Machine creates Class objects.
 213      * This constructor is not used and prevents the default constructor being
 214      * generated.
 215      */
 216     private Class(ClassLoader loader, Class<?> arrayComponentType) {
 217         // Initialize final field for classLoader.  The initialization value of non-null
 218         // prevents future JIT optimizations from assuming this final field is null.
 219         classLoader = loader;
 220         componentType = arrayComponentType;
 221     }
 222 
 223     /**
 224      * Converts the object to a string. The string representation is the
 225      * string "class" or "interface", followed by a space, and then by the
 226      * name of the class in the format returned by {@code getName}.
 227      * If this {@code Class} object represents a primitive type,
 228      * this method returns the name of the primitive type.  If
 229      * this {@code Class} object represents void this method returns
 230      * "void". If this {@code Class} object represents an array type,
 231      * this method returns "class " followed by {@code getName}.
 232      *
 233      * @return a string representation of this {@code Class} object.
 234      */
 235     public String toString() {
 236         String kind = isInterface() ? "interface " : isPrimitive() ? "" : "class ";
 237         return kind.concat(getName());
 238     }
 239 
 240     /**
 241      * Returns a string describing this {@code Class}, including
 242      * information about modifiers and type parameters.
 243      *
 244      * The string is formatted as a list of type modifiers, if any,
 245      * followed by the kind of type (empty string for primitive types
 246      * and {@code class}, {@code enum}, {@code interface},
 247      * {@code @interface}, or {@code record} as appropriate), followed
 248      * by the type's name, followed by an angle-bracketed
 249      * comma-separated list of the type's type parameters, if any,
 250      * including informative bounds on the type parameters, if any.
 251      *
 252      * A space is used to separate modifiers from one another and to
 253      * separate any modifiers from the kind of type. The modifiers
 254      * occur in canonical order. If there are no type parameters, the
 255      * type parameter list is elided.
 256      *
 257      * For an array type, the string starts with the type name,
 258      * followed by an angle-bracketed comma-separated list of the
 259      * type's type parameters, if any, followed by a sequence of
 260      * {@code []} characters, one set of brackets per dimension of
 261      * the array.
 262      *
 263      * <p>Note that since information about the runtime representation
 264      * of a type is being generated, modifiers not present on the
 265      * originating source code or illegal on the originating source
 266      * code may be present.
 267      *
 268      * @return a string describing this {@code Class}, including
 269      * information about modifiers and type parameters
 270      *
 271      * @since 1.8
 272      */
 273     public String toGenericString() {
 274         if (isPrimitive()) {
 275             return toString();
 276         } else {
 277             StringBuilder sb = new StringBuilder();
 278             Class<?> component = this;
 279             int arrayDepth = 0;
 280 
 281             if (isArray()) {
 282                 do {
 283                     arrayDepth++;
 284                     component = component.getComponentType();
 285                 } while (component.isArray());
 286                 sb.append(component.getName());
 287             } else {
 288                 // Class modifiers are a superset of interface modifiers
 289                 int modifiers = getModifiers() & Modifier.classModifiers();
 290                 if (modifiers != 0) {
 291                     sb.append(Modifier.toString(modifiers));
 292                     sb.append(' ');
 293                 }
 294 
 295                 if (isAnnotation()) {
 296                     sb.append('@');
 297                 }
 298                 if (isInterface()) { // Note: all annotation interfaces are interfaces
 299                     sb.append("interface");
 300                 } else {
 301                     if (isEnum())
 302                         sb.append("enum");
 303                     else if (isRecord())
 304                         sb.append("record");
 305                     else
 306                         sb.append("class");
 307                 }
 308                 sb.append(' ');
 309                 sb.append(getName());
 310             }
 311 
 312             TypeVariable<?>[] typeparms = component.getTypeParameters();
 313             if (typeparms.length > 0) {
 314                 sb.append(Arrays.stream(typeparms)
 315                           .map(Class::typeVarBounds)
 316                           .collect(Collectors.joining(",", "<", ">")));
 317             }
 318 
 319             if (arrayDepth > 0) sb.append("[]".repeat(arrayDepth));
 320 
 321             return sb.toString();
 322         }
 323     }
 324 
 325     static String typeVarBounds(TypeVariable<?> typeVar) {
 326         Type[] bounds = typeVar.getBounds();
 327         if (bounds.length == 1 && bounds[0].equals(Object.class)) {
 328             return typeVar.getName();
 329         } else {
 330             return typeVar.getName() + " extends " +
 331                 Arrays.stream(bounds)
 332                 .map(Type::getTypeName)
 333                 .collect(Collectors.joining(" & "));
 334         }
 335     }
 336 
 337     /**
 338      * Returns the {@code Class} object associated with the class or
 339      * interface with the given string name.  Invoking this method is
 340      * equivalent to:
 341      *
 342      * <blockquote>
 343      *  {@code Class.forName(className, true, currentLoader)}
 344      * </blockquote>
 345      *
 346      * where {@code currentLoader} denotes the defining class loader of
 347      * the current class.
 348      *
 349      * <p> For example, the following code fragment returns the
 350      * runtime {@code Class} descriptor for the class named
 351      * {@code java.lang.Thread}:
 352      *
 353      * <blockquote>
 354      *   {@code Class t = Class.forName("java.lang.Thread")}
 355      * </blockquote>
 356      * <p>
 357      * A call to {@code forName("X")} causes the class named
 358      * {@code X} to be initialized.
 359      *
 360      * @param      className   the fully qualified name of the desired class.
 361      * @return     the {@code Class} object for the class with the
 362      *             specified name.
 363      * @throws    LinkageError if the linkage fails
 364      * @throws    ExceptionInInitializerError if the initialization provoked
 365      *            by this method fails
 366      * @throws    ClassNotFoundException if the class cannot be located
 367      *
 368      * @jls 12.2 Loading of Classes and Interfaces
 369      * @jls 12.3 Linking of Classes and Interfaces
 370      * @jls 12.4 Initialization of Classes and Interfaces
 371      */
 372     @CallerSensitive
 373     public static Class<?> forName(String className)
 374                 throws ClassNotFoundException {
 375         Class<?> caller = Reflection.getCallerClass();
 376         return forName(className, caller);
 377     }
 378 
 379     // Caller-sensitive adapter method for reflective invocation
 380     @CallerSensitiveAdapter
 381     private static Class<?> forName(String className, Class<?> caller)
 382             throws ClassNotFoundException {
 383         return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
 384     }
 385 
 386     /**
 387      * Returns the {@code Class} object associated with the class or
 388      * interface with the given string name, using the given class loader.
 389      * Given the fully qualified name for a class or interface (in the same
 390      * format returned by {@code getName}) this method attempts to
 391      * locate and load the class or interface.  The specified class
 392      * loader is used to load the class or interface.  If the parameter
 393      * {@code loader} is null, the class is loaded through the bootstrap
 394      * class loader.  The class is initialized only if the
 395      * {@code initialize} parameter is {@code true} and if it has
 396      * not been initialized earlier.
 397      *
 398      * <p> If {@code name} denotes a primitive type or void, an attempt
 399      * will be made to locate a user-defined class in the unnamed package whose
 400      * name is {@code name}. Therefore, this method cannot be used to
 401      * obtain any of the {@code Class} objects representing primitive
 402      * types or void.
 403      *
 404      * <p> If {@code name} denotes an array class, the component type of
 405      * the array class is loaded but not initialized.
 406      *
 407      * <p> For example, in an instance method the expression:
 408      *
 409      * <blockquote>
 410      *  {@code Class.forName("Foo")}
 411      * </blockquote>
 412      *
 413      * is equivalent to:
 414      *
 415      * <blockquote>
 416      *  {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
 417      * </blockquote>
 418      *
 419      * Note that this method throws errors related to loading, linking
 420      * or initializing as specified in Sections {@jls 12.2}, {@jls
 421      * 12.3}, and {@jls 12.4} of <cite>The Java Language
 422      * Specification</cite>.
 423      * Note that this method does not check whether the requested class
 424      * is accessible to its caller.
 425      *
 426      * @param name       fully qualified name of the desired class
 427 
 428      * @param initialize if {@code true} the class will be initialized
 429      *                   (which implies linking). See Section {@jls
 430      *                   12.4} of <cite>The Java Language
 431      *                   Specification</cite>.
 432      * @param loader     class loader from which the class must be loaded
 433      * @return           class object representing the desired class
 434      *
 435      * @throws    LinkageError if the linkage fails
 436      * @throws    ExceptionInInitializerError if the initialization provoked
 437      *            by this method fails
 438      * @throws    ClassNotFoundException if the class cannot be located by
 439      *            the specified class loader
 440      * @throws    SecurityException
 441      *            if a security manager is present, and the {@code loader} is
 442      *            {@code null}, and the caller's class loader is not
 443      *            {@code null}, and the caller does not have the
 444      *            {@link RuntimePermission}{@code ("getClassLoader")}
 445      *
 446      * @see       java.lang.Class#forName(String)
 447      * @see       java.lang.ClassLoader
 448      *
 449      * @jls 12.2 Loading of Classes and Interfaces
 450      * @jls 12.3 Linking of Classes and Interfaces
 451      * @jls 12.4 Initialization of Classes and Interfaces
 452      * @since     1.2
 453      */
 454     @CallerSensitive
 455     public static Class<?> forName(String name, boolean initialize,
 456                                    ClassLoader loader)
 457         throws ClassNotFoundException
 458     {
 459         Class<?> caller = null;
 460         @SuppressWarnings("removal")
 461         SecurityManager sm = System.getSecurityManager();
 462         if (sm != null) {
 463             // Reflective call to get caller class is only needed if a security manager
 464             // is present.  Avoid the overhead of making this call otherwise.
 465             caller = Reflection.getCallerClass();
 466         }
 467         return forName(name, initialize, loader, caller);
 468     }
 469 
 470     // Caller-sensitive adapter method for reflective invocation
 471     @CallerSensitiveAdapter
 472     private static Class<?> forName(String name, boolean initialize, ClassLoader loader, Class<?> caller)
 473             throws ClassNotFoundException
 474     {
 475         @SuppressWarnings("removal")
 476         SecurityManager sm = System.getSecurityManager();
 477         if (sm != null) {
 478             // Reflective call to get caller class is only needed if a security manager
 479             // is present.  Avoid the overhead of making this call otherwise.
 480             if (loader == null) {
 481                 ClassLoader ccl = ClassLoader.getClassLoader(caller);
 482                 if (ccl != null) {
 483                     sm.checkPermission(
 484                             SecurityConstants.GET_CLASSLOADER_PERMISSION);
 485                 }
 486             }
 487         }
 488         return forName0(name, initialize, loader, caller);
 489     }
 490 
 491     /** Called after security check for system loader access checks have been made. */
 492     private static native Class<?> forName0(String name, boolean initialize,
 493                                             ClassLoader loader,
 494                                             Class<?> caller)
 495         throws ClassNotFoundException;
 496 
 497 
 498     /**
 499      * Returns the {@code Class} with the given <a href="ClassLoader.html#binary-name">
 500      * binary name</a> in the given module.
 501      *
 502      * <p> This method attempts to locate and load the class or interface.
 503      * It does not link the class, and does not run the class initializer.
 504      * If the class is not found, this method returns {@code null}. </p>
 505      *
 506      * <p> If the class loader of the given module defines other modules and
 507      * the given name is a class defined in a different module, this method
 508      * returns {@code null} after the class is loaded. </p>
 509      *
 510      * <p> This method does not check whether the requested class is
 511      * accessible to its caller. </p>
 512      *
 513      * @apiNote
 514      * This method returns {@code null} on failure rather than
 515      * throwing a {@link ClassNotFoundException}, as is done by
 516      * the {@link #forName(String, boolean, ClassLoader)} method.
 517      * The security check is a stack-based permission check if the caller
 518      * loads a class in another module.
 519      *
 520      * @param  module   A module
 521      * @param  name     The <a href="ClassLoader.html#binary-name">binary name</a>
 522      *                  of the class
 523      * @return {@code Class} object of the given name defined in the given module;
 524      *         {@code null} if not found.
 525      *
 526      * @throws NullPointerException if the given module or name is {@code null}
 527      *
 528      * @throws LinkageError if the linkage fails
 529      *
 530      * @throws SecurityException
 531      *         <ul>
 532      *         <li> if the caller is not the specified module and
 533      *         {@code RuntimePermission("getClassLoader")} permission is denied; or</li>
 534      *         <li> access to the module content is denied. For example,
 535      *         permission check will be performed when a class loader calls
 536      *         {@link ModuleReader#open(String)} to read the bytes of a class file
 537      *         in a module.</li>
 538      *         </ul>
 539      *
 540      * @jls 12.2 Loading of Classes and Interfaces
 541      * @jls 12.3 Linking of Classes and Interfaces
 542      * @since 9
 543      */
 544     @SuppressWarnings("removal")
 545     @CallerSensitive
 546     public static Class<?> forName(Module module, String name) {
 547         Class<?> caller = null;
 548         SecurityManager sm = System.getSecurityManager();
 549         if (sm != null) {
 550             caller = Reflection.getCallerClass();
 551         }
 552         return forName(module, name, caller);
 553     }
 554 
 555     // Caller-sensitive adapter method for reflective invocation
 556     @SuppressWarnings("removal")
 557     @CallerSensitiveAdapter
 558     private static Class<?> forName(Module module, String name, Class<?> caller) {
 559         Objects.requireNonNull(module);
 560         Objects.requireNonNull(name);
 561 
 562         ClassLoader cl;
 563         SecurityManager sm = System.getSecurityManager();
 564         if (sm != null) {
 565             if (caller != null && caller.getModule() != module) {
 566                 // if caller is null, Class.forName is the last java frame on the stack.
 567                 // java.base has all permissions
 568                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 569             }
 570             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
 571             cl = AccessController.doPrivileged(pa);
 572         } else {
 573             cl = module.getClassLoader();
 574         }
 575 
 576         if (cl != null) {
 577             return cl.loadClass(module, name);
 578         } else {
 579             return BootLoader.loadClass(module, name);
 580         }
 581     }
 582 
 583     /**
 584      * Creates a new instance of the class represented by this {@code Class}
 585      * object.  The class is instantiated as if by a {@code new}
 586      * expression with an empty argument list.  The class is initialized if it
 587      * has not already been initialized.
 588      *
 589      * @deprecated This method propagates any exception thrown by the
 590      * nullary constructor, including a checked exception.  Use of
 591      * this method effectively bypasses the compile-time exception
 592      * checking that would otherwise be performed by the compiler.
 593      * The {@link
 594      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
 595      * Constructor.newInstance} method avoids this problem by wrapping
 596      * any exception thrown by the constructor in a (checked) {@link
 597      * java.lang.reflect.InvocationTargetException}.
 598      *
 599      * <p>The call
 600      *
 601      * <pre>{@code
 602      * clazz.newInstance()
 603      * }</pre>
 604      *
 605      * can be replaced by
 606      *
 607      * <pre>{@code
 608      * clazz.getDeclaredConstructor().newInstance()
 609      * }</pre>
 610      *
 611      * The latter sequence of calls is inferred to be able to throw
 612      * the additional exception types {@link
 613      * InvocationTargetException} and {@link
 614      * NoSuchMethodException}. Both of these exception types are
 615      * subclasses of {@link ReflectiveOperationException}.
 616      *
 617      * @return  a newly allocated instance of the class represented by this
 618      *          object.
 619      * @throws  IllegalAccessException  if the class or its nullary
 620      *          constructor is not accessible.
 621      * @throws  InstantiationException
 622      *          if this {@code Class} represents an abstract class,
 623      *          an interface, an array class, a primitive type, or void;
 624      *          or if the class has no nullary constructor;
 625      *          or if the instantiation fails for some other reason.
 626      * @throws  ExceptionInInitializerError if the initialization
 627      *          provoked by this method fails.
 628      * @throws  SecurityException
 629      *          If a security manager, <i>s</i>, is present and
 630      *          the caller's class loader is not the same as or an
 631      *          ancestor of the class loader for the current class and
 632      *          invocation of {@link SecurityManager#checkPackageAccess
 633      *          s.checkPackageAccess()} denies access to the package
 634      *          of this class.
 635      */
 636     @SuppressWarnings("removal")
 637     @CallerSensitive
 638     @Deprecated(since="9")
 639     public T newInstance()
 640         throws InstantiationException, IllegalAccessException
 641     {
 642         SecurityManager sm = System.getSecurityManager();
 643         if (sm != null) {
 644             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false);
 645         }
 646 
 647         // Constructor lookup
 648         Constructor<T> tmpConstructor = cachedConstructor;
 649         if (tmpConstructor == null) {
 650             if (this == Class.class) {
 651                 throw new IllegalAccessException(
 652                     "Can not call newInstance() on the Class for java.lang.Class"
 653                 );
 654             }
 655             try {
 656                 Class<?>[] empty = {};
 657                 final Constructor<T> c = getReflectionFactory().copyConstructor(
 658                     getConstructor0(empty, Member.DECLARED));
 659                 // Disable accessibility checks on the constructor
 660                 // access check is done with the true caller
 661                 java.security.AccessController.doPrivileged(
 662                     new java.security.PrivilegedAction<>() {
 663                         public Void run() {
 664                                 c.setAccessible(true);
 665                                 return null;
 666                             }
 667                         });
 668                 cachedConstructor = tmpConstructor = c;
 669             } catch (NoSuchMethodException e) {
 670                 throw (InstantiationException)
 671                     new InstantiationException(getName()).initCause(e);
 672             }
 673         }
 674 
 675         try {
 676             Class<?> caller = Reflection.getCallerClass();
 677             return getReflectionFactory().newInstance(tmpConstructor, null, caller);
 678         } catch (InvocationTargetException e) {
 679             Unsafe.getUnsafe().throwException(e.getTargetException());
 680             // Not reached
 681             return null;
 682         }
 683     }
 684 
 685     private transient volatile Constructor<T> cachedConstructor;
 686 
 687     /**
 688      * Determines if the specified {@code Object} is assignment-compatible
 689      * with the object represented by this {@code Class}.  This method is
 690      * the dynamic equivalent of the Java language {@code instanceof}
 691      * operator. The method returns {@code true} if the specified
 692      * {@code Object} argument is non-null and can be cast to the
 693      * reference type represented by this {@code Class} object without
 694      * raising a {@code ClassCastException.} It returns {@code false}
 695      * otherwise.
 696      *
 697      * <p> Specifically, if this {@code Class} object represents a
 698      * declared class, this method returns {@code true} if the specified
 699      * {@code Object} argument is an instance of the represented class (or
 700      * of any of its subclasses); it returns {@code false} otherwise. If
 701      * this {@code Class} object represents an array class, this method
 702      * returns {@code true} if the specified {@code Object} argument
 703      * can be converted to an object of the array class by an identity
 704      * conversion or by a widening reference conversion; it returns
 705      * {@code false} otherwise. If this {@code Class} object
 706      * represents an interface, this method returns {@code true} if the
 707      * class or any superclass of the specified {@code Object} argument
 708      * implements this interface; it returns {@code false} otherwise. If
 709      * this {@code Class} object represents a primitive type, this method
 710      * returns {@code false}.
 711      *
 712      * @param   obj the object to check
 713      * @return  true if {@code obj} is an instance of this class
 714      *
 715      * @since 1.1
 716      */
 717     @IntrinsicCandidate
 718     public native boolean isInstance(Object obj);
 719 
 720 
 721     /**
 722      * Determines if the class or interface represented by this
 723      * {@code Class} object is either the same as, or is a superclass or
 724      * superinterface of, the class or interface represented by the specified
 725      * {@code Class} parameter. It returns {@code true} if so;
 726      * otherwise it returns {@code false}. If this {@code Class}
 727      * object represents a primitive type, this method returns
 728      * {@code true} if the specified {@code Class} parameter is
 729      * exactly this {@code Class} object; otherwise it returns
 730      * {@code false}.
 731      *
 732      * <p> Specifically, this method tests whether the type represented by the
 733      * specified {@code Class} parameter can be converted to the type
 734      * represented by this {@code Class} object via an identity conversion
 735      * or via a widening reference conversion. See <cite>The Java Language
 736      * Specification</cite>, sections {@jls 5.1.1} and {@jls 5.1.4},
 737      * for details.
 738      *
 739      * @param     cls the {@code Class} object to be checked
 740      * @return    the {@code boolean} value indicating whether objects of the
 741      *            type {@code cls} can be assigned to objects of this class
 742      * @throws    NullPointerException if the specified Class parameter is
 743      *            null.
 744      * @since     1.1
 745      */
 746     @IntrinsicCandidate
 747     public native boolean isAssignableFrom(Class<?> cls);
 748 
 749 
 750     /**
 751      * Determines if this {@code Class} object represents an
 752      * interface type.
 753      *
 754      * @return  {@code true} if this {@code Class} object represents an interface;
 755      *          {@code false} otherwise.
 756      */
 757     @IntrinsicCandidate
 758     public native boolean isInterface();
 759 
 760 
 761     /**
 762      * Determines if this {@code Class} object represents an array class.
 763      *
 764      * @return  {@code true} if this {@code Class} object represents an array class;
 765      *          {@code false} otherwise.
 766      * @since   1.1
 767      */
 768     @IntrinsicCandidate
 769     public native boolean isArray();
 770 
 771 
 772     /**
 773      * Determines if the specified {@code Class} object represents a
 774      * primitive type.
 775      *
 776      * <p> There are nine predefined {@code Class} objects to represent
 777      * the eight primitive types and void.  These are created by the Java
 778      * Virtual Machine, and have the same names as the primitive types that
 779      * they represent, namely {@code boolean}, {@code byte},
 780      * {@code char}, {@code short}, {@code int},
 781      * {@code long}, {@code float}, and {@code double}.
 782      *
 783      * <p> These objects may only be accessed via the following public static
 784      * final variables, and are the only {@code Class} objects for which
 785      * this method returns {@code true}.
 786      *
 787      * @return true if and only if this class represents a primitive type
 788      *
 789      * @see     java.lang.Boolean#TYPE
 790      * @see     java.lang.Character#TYPE
 791      * @see     java.lang.Byte#TYPE
 792      * @see     java.lang.Short#TYPE
 793      * @see     java.lang.Integer#TYPE
 794      * @see     java.lang.Long#TYPE
 795      * @see     java.lang.Float#TYPE
 796      * @see     java.lang.Double#TYPE
 797      * @see     java.lang.Void#TYPE
 798      * @since 1.1
 799      */
 800     @IntrinsicCandidate
 801     public native boolean isPrimitive();
 802 
 803     /**
 804      * Returns true if this {@code Class} object represents an annotation
 805      * interface.  Note that if this method returns true, {@link #isInterface()}
 806      * would also return true, as all annotation interfaces are also interfaces.
 807      *
 808      * @return {@code true} if this {@code Class} object represents an annotation
 809      *      interface; {@code false} otherwise
 810      * @since 1.5
 811      */
 812     public boolean isAnnotation() {
 813         return (getModifiers() & ANNOTATION) != 0;
 814     }
 815 
 816     /**
 817      *{@return {@code true} if and only if this class has the synthetic modifier
 818      * bit set}
 819      *
 820      * @jls 13.1 The Form of a Binary
 821      * @jvms 4.1 The {@code ClassFile} Structure
 822      * @see <a
 823      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
 824      * programming language and JVM modeling in core reflection</a>
 825      * @since 1.5
 826      */
 827     public boolean isSynthetic() {
 828         return (getModifiers() & SYNTHETIC) != 0;
 829     }
 830 
 831     /**
 832      * Returns the  name of the entity (class, interface, array class,
 833      * primitive type, or void) represented by this {@code Class} object.
 834      *
 835      * <p> If this {@code Class} object represents a class or interface,
 836      * not an array class, then:
 837      * <ul>
 838      * <li> If the class or interface is not {@linkplain #isHidden() hidden},
 839      *      then the <a href="ClassLoader.html#binary-name">binary name</a>
 840      *      of the class or interface is returned.
 841      * <li> If the class or interface is hidden, then the result is a string
 842      *      of the form: {@code N + '/' + <suffix>}
 843      *      where {@code N} is the <a href="ClassLoader.html#binary-name">binary name</a>
 844      *      indicated by the {@code class} file passed to
 845      *      {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
 846      *      Lookup::defineHiddenClass}, and {@code <suffix>} is an unqualified name.
 847      * </ul>
 848      *
 849      * <p> If this {@code Class} object represents an array class, then
 850      * the result is a string consisting of one or more '{@code [}' characters
 851      * representing the depth of the array nesting, followed by the element
 852      * type as encoded using the following table:
 853      *
 854      * <blockquote><table class="striped">
 855      * <caption style="display:none">Element types and encodings</caption>
 856      * <thead>
 857      * <tr><th scope="col"> Element Type <th scope="col"> Encoding
 858      * </thead>
 859      * <tbody style="text-align:left">
 860      * <tr><th scope="row"> {@code boolean} <td style="text-align:center"> {@code Z}
 861      * <tr><th scope="row"> {@code byte}    <td style="text-align:center"> {@code B}
 862      * <tr><th scope="row"> {@code char}    <td style="text-align:center"> {@code C}
 863      * <tr><th scope="row"> class or interface with <a href="ClassLoader.html#binary-name">binary name</a> <i>N</i>
 864      *                                      <td style="text-align:center"> {@code L}<em>N</em>{@code ;}
 865      * <tr><th scope="row"> {@code double}  <td style="text-align:center"> {@code D}
 866      * <tr><th scope="row"> {@code float}   <td style="text-align:center"> {@code F}
 867      * <tr><th scope="row"> {@code int}     <td style="text-align:center"> {@code I}
 868      * <tr><th scope="row"> {@code long}    <td style="text-align:center"> {@code J}
 869      * <tr><th scope="row"> {@code short}   <td style="text-align:center"> {@code S}
 870      * </tbody>
 871      * </table></blockquote>
 872      *
 873      * <p> If this {@code Class} object represents a primitive type or {@code void},
 874      * then the result is a string with the same spelling as the Java language
 875      * keyword which corresponds to the primitive type or {@code void}.
 876      *
 877      * <p> Examples:
 878      * <blockquote><pre>
 879      * String.class.getName()
 880      *     returns "java.lang.String"
 881      * byte.class.getName()
 882      *     returns "byte"
 883      * (new Object[3]).getClass().getName()
 884      *     returns "[Ljava.lang.Object;"
 885      * (new int[3][4][5][6][7][8][9]).getClass().getName()
 886      *     returns "[[[[[[[I"
 887      * </pre></blockquote>
 888      *
 889      * @return  the name of the class, interface, or other entity
 890      *          represented by this {@code Class} object.
 891      * @jls 13.1 The Form of a Binary
 892      */
 893     public String getName() {
 894         String name = this.name;
 895         return name != null ? name : initClassName();
 896     }
 897 
 898     // Cache the name to reduce the number of calls into the VM.
 899     // This field would be set by VM itself during initClassName call.
 900     private transient String name;
 901     private native String initClassName();
 902 
 903     /**
 904      * Returns the class loader for the class.  Some implementations may use
 905      * null to represent the bootstrap class loader. This method will return
 906      * null in such implementations if this class was loaded by the bootstrap
 907      * class loader.
 908      *
 909      * <p>If this {@code Class} object
 910      * represents a primitive type or void, null is returned.
 911      *
 912      * @return  the class loader that loaded the class or interface
 913      *          represented by this {@code Class} object.
 914      * @throws  SecurityException
 915      *          if a security manager is present, and the caller's class loader
 916      *          is not {@code null} and is not the same as or an ancestor of the
 917      *          class loader for the class whose class loader is requested,
 918      *          and the caller does not have the
 919      *          {@link RuntimePermission}{@code ("getClassLoader")}
 920      * @see java.lang.ClassLoader
 921      * @see SecurityManager#checkPermission
 922      * @see java.lang.RuntimePermission
 923      */
 924     @CallerSensitive
 925     @ForceInline // to ensure Reflection.getCallerClass optimization
 926     public ClassLoader getClassLoader() {
 927         ClassLoader cl = classLoader;
 928         if (cl == null)
 929             return null;
 930         @SuppressWarnings("removal")
 931         SecurityManager sm = System.getSecurityManager();
 932         if (sm != null) {
 933             ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass());
 934         }
 935         return cl;
 936     }
 937 
 938     // Package-private to allow ClassLoader access
 939     ClassLoader getClassLoader0() { return classLoader; }
 940 
 941     /**
 942      * Returns the module that this class or interface is a member of.
 943      *
 944      * If this class represents an array type then this method returns the
 945      * {@code Module} for the element type. If this class represents a
 946      * primitive type or void, then the {@code Module} object for the
 947      * {@code java.base} module is returned.
 948      *
 949      * If this class is in an unnamed module then the {@linkplain
 950      * ClassLoader#getUnnamedModule() unnamed} {@code Module} of the class
 951      * loader for this class is returned.
 952      *
 953      * @return the module that this class or interface is a member of
 954      *
 955      * @since 9
 956      */
 957     public Module getModule() {
 958         return module;
 959     }
 960 
 961     // set by VM
 962     private transient Module module;
 963 
 964     // Initialized in JVM not by private constructor
 965     // This field is filtered from reflection access, i.e. getDeclaredField
 966     // will throw NoSuchFieldException
 967     private final ClassLoader classLoader;
 968 
 969     // Set by VM
 970     private transient Object classData;
 971 
 972     // package-private
 973     Object getClassData() {
 974         return classData;
 975     }
 976 
 977     /**
 978      * Returns an array of {@code TypeVariable} objects that represent the
 979      * type variables declared by the generic declaration represented by this
 980      * {@code GenericDeclaration} object, in declaration order.  Returns an
 981      * array of length 0 if the underlying generic declaration declares no type
 982      * variables.
 983      *
 984      * @return an array of {@code TypeVariable} objects that represent
 985      *     the type variables declared by this generic declaration
 986      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
 987      *     signature of this generic declaration does not conform to
 988      *     the format specified in section {@jvms 4.7.9} of
 989      *     <cite>The Java Virtual Machine Specification</cite>
 990      * @since 1.5
 991      */
 992     @SuppressWarnings("unchecked")
 993     public TypeVariable<Class<T>>[] getTypeParameters() {
 994         ClassRepository info = getGenericInfo();
 995         if (info != null)
 996             return (TypeVariable<Class<T>>[])info.getTypeParameters();
 997         else
 998             return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];
 999     }
1000 
1001 
1002     /**
1003      * Returns the {@code Class} representing the direct superclass of the
1004      * entity (class, interface, primitive type or void) represented by
1005      * this {@code Class}.  If this {@code Class} represents either the
1006      * {@code Object} class, an interface, a primitive type, or void, then
1007      * null is returned.  If this {@code Class} object represents an array class
1008      * then the {@code Class} object representing the {@code Object} class is
1009      * returned.
1010      *
1011      * @return the direct superclass of the class represented by this {@code Class} object
1012      */
1013     @IntrinsicCandidate
1014     public native Class<? super T> getSuperclass();
1015 
1016 
1017     /**
1018      * Returns the {@code Type} representing the direct superclass of
1019      * the entity (class, interface, primitive type or void) represented by
1020      * this {@code Class} object.
1021      *
1022      * <p>If the superclass is a parameterized type, the {@code Type}
1023      * object returned must accurately reflect the actual type
1024      * arguments used in the source code. The parameterized type
1025      * representing the superclass is created if it had not been
1026      * created before. See the declaration of {@link
1027      * java.lang.reflect.ParameterizedType ParameterizedType} for the
1028      * semantics of the creation process for parameterized types.  If
1029      * this {@code Class} object represents either the {@code Object}
1030      * class, an interface, a primitive type, or void, then null is
1031      * returned.  If this {@code Class} object represents an array class
1032      * then the {@code Class} object representing the {@code Object} class is
1033      * returned.
1034      *
1035      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
1036      *     class signature does not conform to the format specified in
1037      *     section {@jvms 4.7.9} of <cite>The Java Virtual
1038      *     Machine Specification</cite>
1039      * @throws TypeNotPresentException if the generic superclass
1040      *     refers to a non-existent type declaration
1041      * @throws java.lang.reflect.MalformedParameterizedTypeException if the
1042      *     generic superclass refers to a parameterized type that cannot be
1043      *     instantiated  for any reason
1044      * @return the direct superclass of the class represented by this {@code Class} object
1045      * @since 1.5
1046      */
1047     public Type getGenericSuperclass() {
1048         ClassRepository info = getGenericInfo();
1049         if (info == null) {
1050             return getSuperclass();
1051         }
1052 
1053         // Historical irregularity:
1054         // Generic signature marks interfaces with superclass = Object
1055         // but this API returns null for interfaces
1056         if (isInterface()) {
1057             return null;
1058         }
1059 
1060         return info.getSuperclass();
1061     }
1062 
1063     /**
1064      * Gets the package of this class.
1065      *
1066      * <p>If this class represents an array type, a primitive type or void,
1067      * this method returns {@code null}.
1068      *
1069      * @return the package of this class.
1070      * @revised 9
1071      */
1072     public Package getPackage() {
1073         if (isPrimitive() || isArray()) {
1074             return null;
1075         }
1076         ClassLoader cl = classLoader;
1077         return cl != null ? cl.definePackage(this)
1078                           : BootLoader.definePackage(this);
1079     }
1080 
1081     /**
1082      * Returns the fully qualified package name.
1083      *
1084      * <p> If this class is a top level class, then this method returns the fully
1085      * qualified name of the package that the class is a member of, or the
1086      * empty string if the class is in an unnamed package.
1087      *
1088      * <p> If this class is a member class, then this method is equivalent to
1089      * invoking {@code getPackageName()} on the {@linkplain #getEnclosingClass
1090      * enclosing class}.
1091      *
1092      * <p> If this class is a {@linkplain #isLocalClass local class} or an {@linkplain
1093      * #isAnonymousClass() anonymous class}, then this method is equivalent to
1094      * invoking {@code getPackageName()} on the {@linkplain #getDeclaringClass
1095      * declaring class} of the {@linkplain #getEnclosingMethod enclosing method} or
1096      * {@linkplain #getEnclosingConstructor enclosing constructor}.
1097      *
1098      * <p> If this class represents an array type then this method returns the
1099      * package name of the element type. If this class represents a primitive
1100      * type or void then the package name "{@code java.lang}" is returned.
1101      *
1102      * @return the fully qualified package name
1103      *
1104      * @since 9
1105      * @jls 6.7 Fully Qualified Names
1106      */
1107     public String getPackageName() {
1108         String pn = this.packageName;
1109         if (pn == null) {
1110             Class<?> c = isArray() ? elementType() : this;
1111             if (c.isPrimitive()) {
1112                 pn = "java.lang";
1113             } else {
1114                 String cn = c.getName();
1115                 int dot = cn.lastIndexOf('.');
1116                 pn = (dot != -1) ? cn.substring(0, dot).intern() : "";
1117             }
1118             this.packageName = pn;
1119         }
1120         return pn;
1121     }
1122 
1123     // cached package name
1124     private transient String packageName;
1125 
1126     /**
1127      * Returns the interfaces directly implemented by the class or interface
1128      * represented by this {@code Class} object.
1129      *
1130      * <p>If this {@code Class} object represents a class, the return value is an array
1131      * containing objects representing all interfaces directly implemented by
1132      * the class.  The order of the interface objects in the array corresponds
1133      * to the order of the interface names in the {@code implements} clause of
1134      * the declaration of the class represented by this {@code Class} object.  For example,
1135      * given the declaration:
1136      * <blockquote>
1137      * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
1138      * </blockquote>
1139      * suppose the value of {@code s} is an instance of
1140      * {@code Shimmer}; the value of the expression:
1141      * <blockquote>
1142      * {@code s.getClass().getInterfaces()[0]}
1143      * </blockquote>
1144      * is the {@code Class} object that represents interface
1145      * {@code FloorWax}; and the value of:
1146      * <blockquote>
1147      * {@code s.getClass().getInterfaces()[1]}
1148      * </blockquote>
1149      * is the {@code Class} object that represents interface
1150      * {@code DessertTopping}.
1151      *
1152      * <p>If this {@code Class} object represents an interface, the array contains objects
1153      * representing all interfaces directly extended by the interface.  The
1154      * order of the interface objects in the array corresponds to the order of
1155      * the interface names in the {@code extends} clause of the declaration of
1156      * the interface represented by this {@code Class} object.
1157      *
1158      * <p>If this {@code Class} object represents a class or interface that implements no
1159      * interfaces, the method returns an array of length 0.
1160      *
1161      * <p>If this {@code Class} object represents a primitive type or void, the method
1162      * returns an array of length 0.
1163      *
1164      * <p>If this {@code Class} object represents an array type, the
1165      * interfaces {@code Cloneable} and {@code java.io.Serializable} are
1166      * returned in that order.
1167      *
1168      * @return an array of interfaces directly implemented by this class
1169      */
1170     public Class<?>[] getInterfaces() {
1171         // defensively copy before handing over to user code
1172         return getInterfaces(true);
1173     }
1174 
1175     private Class<?>[] getInterfaces(boolean cloneArray) {
1176         ReflectionData<T> rd = reflectionData();
1177         if (rd == null) {
1178             // no cloning required
1179             return getInterfaces0();
1180         } else {
1181             Class<?>[] interfaces = rd.interfaces;
1182             if (interfaces == null) {
1183                 interfaces = getInterfaces0();
1184                 rd.interfaces = interfaces;
1185             }
1186             // defensively copy if requested
1187             return cloneArray ? interfaces.clone() : interfaces;
1188         }
1189     }
1190 
1191     private native Class<?>[] getInterfaces0();
1192 
1193     /**
1194      * Returns the {@code Type}s representing the interfaces
1195      * directly implemented by the class or interface represented by
1196      * this {@code Class} object.
1197      *
1198      * <p>If a superinterface is a parameterized type, the
1199      * {@code Type} object returned for it must accurately reflect
1200      * the actual type arguments used in the source code. The
1201      * parameterized type representing each superinterface is created
1202      * if it had not been created before. See the declaration of
1203      * {@link java.lang.reflect.ParameterizedType ParameterizedType}
1204      * for the semantics of the creation process for parameterized
1205      * types.
1206      *
1207      * <p>If this {@code Class} object represents a class, the return value is an array
1208      * containing objects representing all interfaces directly implemented by
1209      * the class.  The order of the interface objects in the array corresponds
1210      * to the order of the interface names in the {@code implements} clause of
1211      * the declaration of the class represented by this {@code Class} object.
1212      *
1213      * <p>If this {@code Class} object represents an interface, the array contains objects
1214      * representing all interfaces directly extended by the interface.  The
1215      * order of the interface objects in the array corresponds to the order of
1216      * the interface names in the {@code extends} clause of the declaration of
1217      * the interface represented by this {@code Class} object.
1218      *
1219      * <p>If this {@code Class} object represents a class or interface that implements no
1220      * interfaces, the method returns an array of length 0.
1221      *
1222      * <p>If this {@code Class} object represents a primitive type or void, the method
1223      * returns an array of length 0.
1224      *
1225      * <p>If this {@code Class} object represents an array type, the
1226      * interfaces {@code Cloneable} and {@code java.io.Serializable} are
1227      * returned in that order.
1228      *
1229      * @throws java.lang.reflect.GenericSignatureFormatError
1230      *     if the generic class signature does not conform to the
1231      *     format specified in section {@jvms 4.7.9} of <cite>The
1232      *     Java Virtual Machine Specification</cite>
1233      * @throws TypeNotPresentException if any of the generic
1234      *     superinterfaces refers to a non-existent type declaration
1235      * @throws java.lang.reflect.MalformedParameterizedTypeException
1236      *     if any of the generic superinterfaces refer to a parameterized
1237      *     type that cannot be instantiated for any reason
1238      * @return an array of interfaces directly implemented by this class
1239      * @since 1.5
1240      */
1241     public Type[] getGenericInterfaces() {
1242         ClassRepository info = getGenericInfo();
1243         return (info == null) ?  getInterfaces() : info.getSuperInterfaces();
1244     }
1245 
1246 
1247     /**
1248      * Returns the {@code Class} representing the component type of an
1249      * array.  If this class does not represent an array class this method
1250      * returns null.
1251      *
1252      * @return the {@code Class} representing the component type of this
1253      * class if this class is an array
1254      * @see     java.lang.reflect.Array
1255      * @since 1.1
1256      */
1257     public Class<?> getComponentType() {
1258         // Only return for array types. Storage may be reused for Class for instance types.
1259         if (isArray()) {
1260             return componentType;
1261         } else {
1262             return null;
1263         }
1264     }
1265 
1266     private final Class<?> componentType;
1267 
1268     /*
1269      * Returns the {@code Class} representing the element type of an array class.
1270      * If this class does not represent an array class, then this method returns
1271      * {@code null}.
1272      */
1273     private Class<?> elementType() {
1274         if (!isArray()) return null;
1275 
1276         Class<?> c = this;
1277         while (c.isArray()) {
1278             c = c.getComponentType();
1279         }
1280         return c;
1281     }
1282 
1283     /**
1284      * Returns the Java language modifiers for this class or interface, encoded
1285      * in an integer. The modifiers consist of the Java Virtual Machine's
1286      * constants for {@code public}, {@code protected},
1287      * {@code private}, {@code final}, {@code static},
1288      * {@code abstract} and {@code interface}; they should be decoded
1289      * using the methods of class {@code Modifier}.
1290      *
1291      * <p> If the underlying class is an array class, then its
1292      * {@code public}, {@code private} and {@code protected}
1293      * modifiers are the same as those of its component type.  If this
1294      * {@code Class} object represents a primitive type or void, its
1295      * {@code public} modifier is always {@code true}, and its
1296      * {@code protected} and {@code private} modifiers are always
1297      * {@code false}. If this {@code Class} object represents an array class, a
1298      * primitive type or void, then its {@code final} modifier is always
1299      * {@code true} and its interface modifier is always
1300      * {@code false}. The values of its other modifiers are not determined
1301      * by this specification.
1302      *
1303      * <p> The modifier encodings are defined in section {@jvms 4.1}
1304      * of <cite>The Java Virtual Machine Specification</cite>.
1305      *
1306      * @return the {@code int} representing the modifiers for this class
1307      * @see     java.lang.reflect.Modifier
1308      * @see <a
1309      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1310      * programming language and JVM modeling in core reflection</a>
1311      * @since 1.1
1312      * @jls 8.1.1 Class Modifiers
1313      * @jls 9.1.1. Interface Modifiers
1314      */
1315     @IntrinsicCandidate
1316     public native int getModifiers();
1317 
1318 
1319     /**
1320      * Gets the signers of this class.
1321      *
1322      * @return  the signers of this class, or null if there are no signers.  In
1323      *          particular, this method returns null if this {@code Class} object represents
1324      *          a primitive type or void.
1325      * @since   1.1
1326      */
1327     public native Object[] getSigners();
1328 
1329 
1330     /**
1331      * Set the signers of this class.
1332      */
1333     native void setSigners(Object[] signers);
1334 
1335 
1336     /**
1337      * If this {@code Class} object represents a local or anonymous
1338      * class within a method, returns a {@link
1339      * java.lang.reflect.Method Method} object representing the
1340      * immediately enclosing method of the underlying class. Returns
1341      * {@code null} otherwise.
1342      *
1343      * In particular, this method returns {@code null} if the underlying
1344      * class is a local or anonymous class immediately enclosed by a class or
1345      * interface declaration, instance initializer or static initializer.
1346      *
1347      * @return the immediately enclosing method of the underlying class, if
1348      *     that class is a local or anonymous class; otherwise {@code null}.
1349      *
1350      * @throws SecurityException
1351      *         If a security manager, <i>s</i>, is present and any of the
1352      *         following conditions is met:
1353      *
1354      *         <ul>
1355      *
1356      *         <li> the caller's class loader is not the same as the
1357      *         class loader of the enclosing class and invocation of
1358      *         {@link SecurityManager#checkPermission
1359      *         s.checkPermission} method with
1360      *         {@code RuntimePermission("accessDeclaredMembers")}
1361      *         denies access to the methods within the enclosing class
1362      *
1363      *         <li> the caller's class loader is not the same as or an
1364      *         ancestor of the class loader for the enclosing class and
1365      *         invocation of {@link SecurityManager#checkPackageAccess
1366      *         s.checkPackageAccess()} denies access to the package
1367      *         of the enclosing class
1368      *
1369      *         </ul>
1370      * @since 1.5
1371      */
1372     @CallerSensitive
1373     public Method getEnclosingMethod() throws SecurityException {
1374         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1375 
1376         if (enclosingInfo == null)
1377             return null;
1378         else {
1379             if (!enclosingInfo.isMethod())
1380                 return null;
1381 
1382             MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
1383                                                               getFactory());
1384             Class<?>   returnType       = toClass(typeInfo.getReturnType());
1385             Type []    parameterTypes   = typeInfo.getParameterTypes();
1386             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1387 
1388             // Convert Types to Classes; returned types *should*
1389             // be class objects since the methodDescriptor's used
1390             // don't have generics information
1391             for(int i = 0; i < parameterClasses.length; i++)
1392                 parameterClasses[i] = toClass(parameterTypes[i]);
1393 
1394             // Perform access check
1395             final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1396             @SuppressWarnings("removal")
1397             SecurityManager sm = System.getSecurityManager();
1398             if (sm != null) {
1399                 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED,
1400                                                      Reflection.getCallerClass(), true);
1401             }
1402             Method[] candidates = enclosingCandidate.privateGetDeclaredMethods(false);
1403 
1404             /*
1405              * Loop over all declared methods; match method name,
1406              * number of and type of parameters, *and* return
1407              * type.  Matching return type is also necessary
1408              * because of covariant returns, etc.
1409              */
1410             ReflectionFactory fact = getReflectionFactory();
1411             for (Method m : candidates) {
1412                 if (m.getName().equals(enclosingInfo.getName()) &&
1413                     arrayContentsEq(parameterClasses,
1414                                     fact.getExecutableSharedParameterTypes(m))) {
1415                     // finally, check return type
1416                     if (m.getReturnType().equals(returnType)) {
1417                         return fact.copyMethod(m);
1418                     }
1419                 }
1420             }
1421 
1422             throw new InternalError("Enclosing method not found");
1423         }
1424     }
1425 
1426     private native Object[] getEnclosingMethod0();
1427 
1428     private EnclosingMethodInfo getEnclosingMethodInfo() {
1429         Object[] enclosingInfo = getEnclosingMethod0();
1430         if (enclosingInfo == null)
1431             return null;
1432         else {
1433             return new EnclosingMethodInfo(enclosingInfo);
1434         }
1435     }
1436 
1437     private static final class EnclosingMethodInfo {
1438         private final Class<?> enclosingClass;
1439         private final String name;
1440         private final String descriptor;
1441 
1442         static void validate(Object[] enclosingInfo) {
1443             if (enclosingInfo.length != 3)
1444                 throw new InternalError("Malformed enclosing method information");
1445             try {
1446                 // The array is expected to have three elements:
1447 
1448                 // the immediately enclosing class
1449                 Class<?> enclosingClass = (Class<?>)enclosingInfo[0];
1450                 assert(enclosingClass != null);
1451 
1452                 // the immediately enclosing method or constructor's
1453                 // name (can be null).
1454                 String name = (String)enclosingInfo[1];
1455 
1456                 // the immediately enclosing method or constructor's
1457                 // descriptor (null iff name is).
1458                 String descriptor = (String)enclosingInfo[2];
1459                 assert((name != null && descriptor != null) || name == descriptor);
1460             } catch (ClassCastException cce) {
1461                 throw new InternalError("Invalid type in enclosing method information", cce);
1462             }
1463         }
1464 
1465         EnclosingMethodInfo(Object[] enclosingInfo) {
1466             validate(enclosingInfo);
1467             this.enclosingClass = (Class<?>)enclosingInfo[0];
1468             this.name = (String)enclosingInfo[1];
1469             this.descriptor = (String)enclosingInfo[2];
1470         }
1471 
1472         boolean isPartial() {
1473             return enclosingClass == null || name == null || descriptor == null;
1474         }
1475 
1476         boolean isConstructor() { return !isPartial() && "<init>".equals(name); }
1477 
1478         boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }
1479 
1480         Class<?> getEnclosingClass() { return enclosingClass; }
1481 
1482         String getName() { return name; }
1483 
1484         String getDescriptor() { return descriptor; }
1485 
1486     }
1487 
1488     private static Class<?> toClass(Type o) {
1489         if (o instanceof GenericArrayType)
1490             return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
1491                                      0)
1492                 .getClass();
1493         return (Class<?>)o;
1494      }
1495 
1496     /**
1497      * If this {@code Class} object represents a local or anonymous
1498      * class within a constructor, returns a {@link
1499      * java.lang.reflect.Constructor Constructor} object representing
1500      * the immediately enclosing constructor of the underlying
1501      * class. Returns {@code null} otherwise.  In particular, this
1502      * method returns {@code null} if the underlying class is a local
1503      * or anonymous class immediately enclosed by a class or
1504      * interface declaration, instance initializer or static initializer.
1505      *
1506      * @return the immediately enclosing constructor of the underlying class, if
1507      *     that class is a local or anonymous class; otherwise {@code null}.
1508      * @throws SecurityException
1509      *         If a security manager, <i>s</i>, is present and any of the
1510      *         following conditions is met:
1511      *
1512      *         <ul>
1513      *
1514      *         <li> the caller's class loader is not the same as the
1515      *         class loader of the enclosing class and invocation of
1516      *         {@link SecurityManager#checkPermission
1517      *         s.checkPermission} method with
1518      *         {@code RuntimePermission("accessDeclaredMembers")}
1519      *         denies access to the constructors within the enclosing class
1520      *
1521      *         <li> the caller's class loader is not the same as or an
1522      *         ancestor of the class loader for the enclosing class and
1523      *         invocation of {@link SecurityManager#checkPackageAccess
1524      *         s.checkPackageAccess()} denies access to the package
1525      *         of the enclosing class
1526      *
1527      *         </ul>
1528      * @since 1.5
1529      */
1530     @CallerSensitive
1531     public Constructor<?> getEnclosingConstructor() throws SecurityException {
1532         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1533 
1534         if (enclosingInfo == null)
1535             return null;
1536         else {
1537             if (!enclosingInfo.isConstructor())
1538                 return null;
1539 
1540             ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
1541                                                                         getFactory());
1542             Type []    parameterTypes   = typeInfo.getParameterTypes();
1543             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1544 
1545             // Convert Types to Classes; returned types *should*
1546             // be class objects since the methodDescriptor's used
1547             // don't have generics information
1548             for(int i = 0; i < parameterClasses.length; i++)
1549                 parameterClasses[i] = toClass(parameterTypes[i]);
1550 
1551             // Perform access check
1552             final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1553             @SuppressWarnings("removal")
1554             SecurityManager sm = System.getSecurityManager();
1555             if (sm != null) {
1556                 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED,
1557                                                      Reflection.getCallerClass(), true);
1558             }
1559 
1560             Constructor<?>[] candidates = enclosingCandidate
1561                     .privateGetDeclaredConstructors(false);
1562             /*
1563              * Loop over all declared constructors; match number
1564              * of and type of parameters.
1565              */
1566             ReflectionFactory fact = getReflectionFactory();
1567             for (Constructor<?> c : candidates) {
1568                 if (arrayContentsEq(parameterClasses,
1569                                     fact.getExecutableSharedParameterTypes(c))) {
1570                     return fact.copyConstructor(c);
1571                 }
1572             }
1573 
1574             throw new InternalError("Enclosing constructor not found");
1575         }
1576     }
1577 
1578 
1579     /**
1580      * If the class or interface represented by this {@code Class} object
1581      * is a member of another class, returns the {@code Class} object
1582      * representing the class in which it was declared.  This method returns
1583      * null if this class or interface is not a member of any other class.  If
1584      * this {@code Class} object represents an array class, a primitive
1585      * type, or void, then this method returns null.
1586      *
1587      * @return the declaring class for this class
1588      * @throws SecurityException
1589      *         If a security manager, <i>s</i>, is present and the caller's
1590      *         class loader is not the same as or an ancestor of the class
1591      *         loader for the declaring class and invocation of {@link
1592      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
1593      *         denies access to the package of the declaring class
1594      * @since 1.1
1595      */
1596     @CallerSensitive
1597     public Class<?> getDeclaringClass() throws SecurityException {
1598         final Class<?> candidate = getDeclaringClass0();
1599 
1600         if (candidate != null) {
1601             @SuppressWarnings("removal")
1602             SecurityManager sm = System.getSecurityManager();
1603             if (sm != null) {
1604                 candidate.checkPackageAccess(sm,
1605                     ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
1606             }
1607         }
1608         return candidate;
1609     }
1610 
1611     private native Class<?> getDeclaringClass0();
1612 
1613 
1614     /**
1615      * Returns the immediately enclosing class of the underlying
1616      * class.  If the underlying class is a top level class this
1617      * method returns {@code null}.
1618      * @return the immediately enclosing class of the underlying class
1619      * @throws     SecurityException
1620      *             If a security manager, <i>s</i>, is present and the caller's
1621      *             class loader is not the same as or an ancestor of the class
1622      *             loader for the enclosing class and invocation of {@link
1623      *             SecurityManager#checkPackageAccess s.checkPackageAccess()}
1624      *             denies access to the package of the enclosing class
1625      * @since 1.5
1626      */
1627     @CallerSensitive
1628     public Class<?> getEnclosingClass() throws SecurityException {
1629         // There are five kinds of classes (or interfaces):
1630         // a) Top level classes
1631         // b) Nested classes (static member classes)
1632         // c) Inner classes (non-static member classes)
1633         // d) Local classes (named classes declared within a method)
1634         // e) Anonymous classes
1635 
1636 
1637         // JVM Spec 4.7.7: A class must have an EnclosingMethod
1638         // attribute if and only if it is a local class or an
1639         // anonymous class.
1640         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1641         Class<?> enclosingCandidate;
1642 
1643         if (enclosingInfo == null) {
1644             // This is a top level or a nested class or an inner class (a, b, or c)
1645             enclosingCandidate = getDeclaringClass0();
1646         } else {
1647             Class<?> enclosingClass = enclosingInfo.getEnclosingClass();
1648             // This is a local class or an anonymous class (d or e)
1649             if (enclosingClass == this || enclosingClass == null)
1650                 throw new InternalError("Malformed enclosing method information");
1651             else
1652                 enclosingCandidate = enclosingClass;
1653         }
1654 
1655         if (enclosingCandidate != null) {
1656             @SuppressWarnings("removal")
1657             SecurityManager sm = System.getSecurityManager();
1658             if (sm != null) {
1659                 enclosingCandidate.checkPackageAccess(sm,
1660                     ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
1661             }
1662         }
1663         return enclosingCandidate;
1664     }
1665 
1666     /**
1667      * Returns the simple name of the underlying class as given in the
1668      * source code. An empty string is returned if the underlying class is
1669      * {@linkplain #isAnonymousClass() anonymous}.
1670      * A {@linkplain #isSynthetic() synthetic class}, one not present
1671      * in source code, can have a non-empty name including special
1672      * characters, such as "{@code $}".
1673      *
1674      * <p>The simple name of an {@linkplain #isArray() array class} is the simple name of the
1675      * component type with "[]" appended.  In particular the simple
1676      * name of an array class whose component type is anonymous is "[]".
1677      *
1678      * @return the simple name of the underlying class
1679      * @since 1.5
1680      */
1681     public String getSimpleName() {
1682         ReflectionData<T> rd = reflectionData();
1683         String simpleName = rd.simpleName;
1684         if (simpleName == null) {
1685             rd.simpleName = simpleName = getSimpleName0();
1686         }
1687         return simpleName;
1688     }
1689 
1690     private String getSimpleName0() {
1691         if (isArray()) {
1692             return getComponentType().getSimpleName().concat("[]");
1693         }
1694         String simpleName = getSimpleBinaryName();
1695         if (simpleName == null) { // top level class
1696             simpleName = getName();
1697             simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1698         }
1699         return simpleName;
1700     }
1701 
1702     /**
1703      * Return an informative string for the name of this class or interface.
1704      *
1705      * @return an informative string for the name of this class or interface
1706      * @since 1.8
1707      */
1708     public String getTypeName() {
1709         if (isArray()) {
1710             try {
1711                 Class<?> cl = this;
1712                 int dimensions = 0;
1713                 do {
1714                     dimensions++;
1715                     cl = cl.getComponentType();
1716                 } while (cl.isArray());
1717                 return cl.getName().concat("[]".repeat(dimensions));
1718             } catch (Throwable e) { /*FALLTHRU*/ }
1719         }
1720         return getName();
1721     }
1722 
1723     /**
1724      * Returns the canonical name of the underlying class as
1725      * defined by <cite>The Java Language Specification</cite>.
1726      * Returns {@code null} if the underlying class does not have a canonical
1727      * name. Classes without canonical names include:
1728      * <ul>
1729      * <li>a {@linkplain #isLocalClass() local class}
1730      * <li>a {@linkplain #isAnonymousClass() anonymous class}
1731      * <li>a {@linkplain #isHidden() hidden class}
1732      * <li>an array whose component type does not have a canonical name</li>
1733      * </ul>
1734      *
1735      * The canonical name for a primitive class is the keyword for the
1736      * corresponding primitive type ({@code byte}, {@code short},
1737      * {@code char}, {@code int}, and so on).
1738      *
1739      * <p>An array type has a canonical name if and only if its
1740      * component type has a canonical name. When an array type has a
1741      * canonical name, it is equal to the canonical name of the
1742      * component type followed by "{@code []}".
1743      *
1744      * @return the canonical name of the underlying class if it exists, and
1745      * {@code null} otherwise.
1746      * @jls 6.7 Fully Qualified Names and Canonical Names
1747      * @since 1.5
1748      */
1749     public String getCanonicalName() {
1750         ReflectionData<T> rd = reflectionData();
1751         String canonicalName = rd.canonicalName;
1752         if (canonicalName == null) {
1753             rd.canonicalName = canonicalName = getCanonicalName0();
1754         }
1755         return canonicalName == ReflectionData.NULL_SENTINEL? null : canonicalName;
1756     }
1757 
1758     private String getCanonicalName0() {
1759         if (isArray()) {
1760             String canonicalName = getComponentType().getCanonicalName();
1761             if (canonicalName != null)
1762                 return canonicalName.concat("[]");
1763             else
1764                 return ReflectionData.NULL_SENTINEL;
1765         }
1766         if (isHidden() || isLocalOrAnonymousClass())
1767             return ReflectionData.NULL_SENTINEL;
1768         Class<?> enclosingClass = getEnclosingClass();
1769         if (enclosingClass == null) { // top level class
1770             return getName();
1771         } else {
1772             String enclosingName = enclosingClass.getCanonicalName();
1773             if (enclosingName == null)
1774                 return ReflectionData.NULL_SENTINEL;
1775             String simpleName = getSimpleName();
1776             return new StringBuilder(enclosingName.length() + simpleName.length() + 1)
1777                     .append(enclosingName)
1778                     .append('.')
1779                     .append(simpleName)
1780                     .toString();
1781         }
1782     }
1783 
1784     /**
1785      * Returns {@code true} if and only if the underlying class
1786      * is an anonymous class.
1787      *
1788      * @apiNote
1789      * An anonymous class is not a {@linkplain #isHidden() hidden class}.
1790      *
1791      * @return {@code true} if and only if this class is an anonymous class.
1792      * @since 1.5
1793      * @jls 15.9.5 Anonymous Class Declarations
1794      */
1795     public boolean isAnonymousClass() {
1796         return !isArray() && isLocalOrAnonymousClass() &&
1797                 getSimpleBinaryName0() == null;
1798     }
1799 
1800     /**
1801      * Returns {@code true} if and only if the underlying class
1802      * is a local class.
1803      *
1804      * @return {@code true} if and only if this class is a local class.
1805      * @since 1.5
1806      * @jls 14.3 Local Class Declarations
1807      */
1808     public boolean isLocalClass() {
1809         return isLocalOrAnonymousClass() &&
1810                 (isArray() || getSimpleBinaryName0() != null);
1811     }
1812 
1813     /**
1814      * Returns {@code true} if and only if the underlying class
1815      * is a member class.
1816      *
1817      * @return {@code true} if and only if this class is a member class.
1818      * @since 1.5
1819      * @jls 8.5 Member Type Declarations
1820      */
1821     public boolean isMemberClass() {
1822         return !isLocalOrAnonymousClass() && getDeclaringClass0() != null;
1823     }
1824 
1825     /**
1826      * Returns the "simple binary name" of the underlying class, i.e.,
1827      * the binary name without the leading enclosing class name.
1828      * Returns {@code null} if the underlying class is a top level
1829      * class.
1830      */
1831     private String getSimpleBinaryName() {
1832         if (isTopLevelClass())
1833             return null;
1834         String name = getSimpleBinaryName0();
1835         if (name == null) // anonymous class
1836             return "";
1837         return name;
1838     }
1839 
1840     private native String getSimpleBinaryName0();
1841 
1842     /**
1843      * Returns {@code true} if this is a top level class.  Returns {@code false}
1844      * otherwise.
1845      */
1846     private boolean isTopLevelClass() {
1847         return !isLocalOrAnonymousClass() && getDeclaringClass0() == null;
1848     }
1849 
1850     /**
1851      * Returns {@code true} if this is a local class or an anonymous
1852      * class.  Returns {@code false} otherwise.
1853      */
1854     private boolean isLocalOrAnonymousClass() {
1855         // JVM Spec 4.7.7: A class must have an EnclosingMethod
1856         // attribute if and only if it is a local class or an
1857         // anonymous class.
1858         return hasEnclosingMethodInfo();
1859     }
1860 
1861     private boolean hasEnclosingMethodInfo() {
1862         Object[] enclosingInfo = getEnclosingMethod0();
1863         if (enclosingInfo != null) {
1864             EnclosingMethodInfo.validate(enclosingInfo);
1865             return true;
1866         }
1867         return false;
1868     }
1869 
1870     /**
1871      * Returns an array containing {@code Class} objects representing all
1872      * the public classes and interfaces that are members of the class
1873      * represented by this {@code Class} object.  This includes public
1874      * class and interface members inherited from superclasses and public class
1875      * and interface members declared by the class.  This method returns an
1876      * array of length 0 if this {@code Class} object has no public member
1877      * classes or interfaces.  This method also returns an array of length 0 if
1878      * this {@code Class} object represents a primitive type, an array
1879      * class, or void.
1880      *
1881      * @return the array of {@code Class} objects representing the public
1882      *         members of this class
1883      * @throws SecurityException
1884      *         If a security manager, <i>s</i>, is present and
1885      *         the caller's class loader is not the same as or an
1886      *         ancestor of the class loader for the current class and
1887      *         invocation of {@link SecurityManager#checkPackageAccess
1888      *         s.checkPackageAccess()} denies access to the package
1889      *         of this class.
1890      *
1891      * @since 1.1
1892      */
1893     @SuppressWarnings("removal")
1894     @CallerSensitive
1895     public Class<?>[] getClasses() {
1896         SecurityManager sm = System.getSecurityManager();
1897         if (sm != null) {
1898             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false);
1899         }
1900 
1901         // Privileged so this implementation can look at DECLARED classes,
1902         // something the caller might not have privilege to do.  The code here
1903         // is allowed to look at DECLARED classes because (1) it does not hand
1904         // out anything other than public members and (2) public member access
1905         // has already been ok'd by the SecurityManager.
1906 
1907         return java.security.AccessController.doPrivileged(
1908             new java.security.PrivilegedAction<>() {
1909                 public Class<?>[] run() {
1910                     List<Class<?>> list = new ArrayList<>();
1911                     Class<?> currentClass = Class.this;
1912                     while (currentClass != null) {
1913                         for (Class<?> m : currentClass.getDeclaredClasses()) {
1914                             if (Modifier.isPublic(m.getModifiers())) {
1915                                 list.add(m);
1916                             }
1917                         }
1918                         currentClass = currentClass.getSuperclass();
1919                     }
1920                     return list.toArray(new Class<?>[0]);
1921                 }
1922             });
1923     }
1924 
1925 
1926     /**
1927      * Returns an array containing {@code Field} objects reflecting all
1928      * the accessible public fields of the class or interface represented by
1929      * this {@code Class} object.
1930      *
1931      * <p> If this {@code Class} object represents a class or interface with
1932      * no accessible public fields, then this method returns an array of length
1933      * 0.
1934      *
1935      * <p> If this {@code Class} object represents a class, then this method
1936      * returns the public fields of the class and of all its superclasses and
1937      * superinterfaces.
1938      *
1939      * <p> If this {@code Class} object represents an interface, then this
1940      * method returns the fields of the interface and of all its
1941      * superinterfaces.
1942      *
1943      * <p> If this {@code Class} object represents an array type, a primitive
1944      * type, or void, then this method returns an array of length 0.
1945      *
1946      * <p> The elements in the returned array are not sorted and are not in any
1947      * particular order.
1948      *
1949      * @return the array of {@code Field} objects representing the
1950      *         public fields
1951      * @throws SecurityException
1952      *         If a security manager, <i>s</i>, is present and
1953      *         the caller's class loader is not the same as or an
1954      *         ancestor of the class loader for the current class and
1955      *         invocation of {@link SecurityManager#checkPackageAccess
1956      *         s.checkPackageAccess()} denies access to the package
1957      *         of this class.
1958      *
1959      * @since 1.1
1960      * @jls 8.2 Class Members
1961      * @jls 8.3 Field Declarations
1962      */
1963     @CallerSensitive
1964     public Field[] getFields() throws SecurityException {
1965         @SuppressWarnings("removal")
1966         SecurityManager sm = System.getSecurityManager();
1967         if (sm != null) {
1968             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
1969         }
1970         return copyFields(privateGetPublicFields());
1971     }
1972 
1973 
1974     /**
1975      * Returns an array containing {@code Method} objects reflecting all the
1976      * public methods of the class or interface represented by this {@code
1977      * Class} object, including those declared by the class or interface and
1978      * those inherited from superclasses and superinterfaces.
1979      *
1980      * <p> If this {@code Class} object represents an array type, then the
1981      * returned array has a {@code Method} object for each of the public
1982      * methods inherited by the array type from {@code Object}. It does not
1983      * contain a {@code Method} object for {@code clone()}.
1984      *
1985      * <p> If this {@code Class} object represents an interface then the
1986      * returned array does not contain any implicitly declared methods from
1987      * {@code Object}. Therefore, if no methods are explicitly declared in
1988      * this interface or any of its superinterfaces then the returned array
1989      * has length 0. (Note that a {@code Class} object which represents a class
1990      * always has public methods, inherited from {@code Object}.)
1991      *
1992      * <p> The returned array never contains methods with names "{@code <init>}"
1993      * or "{@code <clinit>}".
1994      *
1995      * <p> The elements in the returned array are not sorted and are not in any
1996      * particular order.
1997      *
1998      * <p> Generally, the result is computed as with the following 4 step algorithm.
1999      * Let C be the class or interface represented by this {@code Class} object:
2000      * <ol>
2001      * <li> A union of methods is composed of:
2002      *   <ol type="a">
2003      *   <li> C's declared public instance and static methods as returned by
2004      *        {@link #getDeclaredMethods()} and filtered to include only public
2005      *        methods.</li>
2006      *   <li> If C is a class other than {@code Object}, then include the result
2007      *        of invoking this algorithm recursively on the superclass of C.</li>
2008      *   <li> Include the results of invoking this algorithm recursively on all
2009      *        direct superinterfaces of C, but include only instance methods.</li>
2010      *   </ol></li>
2011      * <li> Union from step 1 is partitioned into subsets of methods with same
2012      *      signature (name, parameter types) and return type.</li>
2013      * <li> Within each such subset only the most specific methods are selected.
2014      *      Let method M be a method from a set of methods with same signature
2015      *      and return type. M is most specific if there is no such method
2016      *      N != M from the same set, such that N is more specific than M.
2017      *      N is more specific than M if:
2018      *   <ol type="a">
2019      *   <li> N is declared by a class and M is declared by an interface; or</li>
2020      *   <li> N and M are both declared by classes or both by interfaces and
2021      *        N's declaring type is the same as or a subtype of M's declaring type
2022      *        (clearly, if M's and N's declaring types are the same type, then
2023      *        M and N are the same method).</li>
2024      *   </ol></li>
2025      * <li> The result of this algorithm is the union of all selected methods from
2026      *      step 3.</li>
2027      * </ol>
2028      *
2029      * @apiNote There may be more than one method with a particular name
2030      * and parameter types in a class because while the Java language forbids a
2031      * class to declare multiple methods with the same signature but different
2032      * return types, the Java virtual machine does not.  This
2033      * increased flexibility in the virtual machine can be used to
2034      * implement various language features.  For example, covariant
2035      * returns can be implemented with {@linkplain
2036      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
2037      * method and the overriding method would have the same
2038      * signature but different return types.
2039      *
2040      * @return the array of {@code Method} objects representing the
2041      *         public methods of this class
2042      * @throws SecurityException
2043      *         If a security manager, <i>s</i>, is present and
2044      *         the caller's class loader is not the same as or an
2045      *         ancestor of the class loader for the current class and
2046      *         invocation of {@link SecurityManager#checkPackageAccess
2047      *         s.checkPackageAccess()} denies access to the package
2048      *         of this class.
2049      *
2050      * @jls 8.2 Class Members
2051      * @jls 8.4 Method Declarations
2052      * @since 1.1
2053      */
2054     @CallerSensitive
2055     public Method[] getMethods() throws SecurityException {
2056         @SuppressWarnings("removal")
2057         SecurityManager sm = System.getSecurityManager();
2058         if (sm != null) {
2059             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
2060         }
2061         return copyMethods(privateGetPublicMethods());
2062     }
2063 
2064 
2065     /**
2066      * Returns an array containing {@code Constructor} objects reflecting
2067      * all the public constructors of the class represented by this
2068      * {@code Class} object.  An array of length 0 is returned if the
2069      * class has no public constructors, or if the class is an array class, or
2070      * if the class reflects a primitive type or void.
2071      *
2072      * @apiNote
2073      * While this method returns an array of {@code
2074      * Constructor<T>} objects (that is an array of constructors from
2075      * this class), the return type of this method is {@code
2076      * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
2077      * might be expected.  This less informative return type is
2078      * necessary since after being returned from this method, the
2079      * array could be modified to hold {@code Constructor} objects for
2080      * different classes, which would violate the type guarantees of
2081      * {@code Constructor<T>[]}.
2082      *
2083      * @return the array of {@code Constructor} objects representing the
2084      *         public constructors of this class
2085      * @throws SecurityException
2086      *         If a security manager, <i>s</i>, is present and
2087      *         the caller's class loader is not the same as or an
2088      *         ancestor of the class loader for the current class and
2089      *         invocation of {@link SecurityManager#checkPackageAccess
2090      *         s.checkPackageAccess()} denies access to the package
2091      *         of this class.
2092      *
2093      * @see #getDeclaredConstructors()
2094      * @since 1.1
2095      */
2096     @CallerSensitive
2097     public Constructor<?>[] getConstructors() throws SecurityException {
2098         @SuppressWarnings("removal")
2099         SecurityManager sm = System.getSecurityManager();
2100         if (sm != null) {
2101             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
2102         }
2103         return copyConstructors(privateGetDeclaredConstructors(true));
2104     }
2105 
2106 
2107     /**
2108      * Returns a {@code Field} object that reflects the specified public member
2109      * field of the class or interface represented by this {@code Class}
2110      * object. The {@code name} parameter is a {@code String} specifying the
2111      * simple name of the desired field.
2112      *
2113      * <p> The field to be reflected is determined by the algorithm that
2114      * follows.  Let C be the class or interface represented by this {@code Class} object:
2115      *
2116      * <OL>
2117      * <LI> If C declares a public field with the name specified, that is the
2118      *      field to be reflected.</LI>
2119      * <LI> If no field was found in step 1 above, this algorithm is applied
2120      *      recursively to each direct superinterface of C. The direct
2121      *      superinterfaces are searched in the order they were declared.</LI>
2122      * <LI> If no field was found in steps 1 and 2 above, and C has a
2123      *      superclass S, then this algorithm is invoked recursively upon S.
2124      *      If C has no superclass, then a {@code NoSuchFieldException}
2125      *      is thrown.</LI>
2126      * </OL>
2127      *
2128      * <p> If this {@code Class} object represents an array type, then this
2129      * method does not find the {@code length} field of the array type.
2130      *
2131      * @param name the field name
2132      * @return the {@code Field} object of this class specified by
2133      *         {@code name}
2134      * @throws NoSuchFieldException if a field with the specified name is
2135      *         not found.
2136      * @throws NullPointerException if {@code name} is {@code null}
2137      * @throws SecurityException
2138      *         If a security manager, <i>s</i>, is present and
2139      *         the caller's class loader is not the same as or an
2140      *         ancestor of the class loader for the current class and
2141      *         invocation of {@link SecurityManager#checkPackageAccess
2142      *         s.checkPackageAccess()} denies access to the package
2143      *         of this class.
2144      *
2145      * @since 1.1
2146      * @jls 8.2 Class Members
2147      * @jls 8.3 Field Declarations
2148      */
2149     @CallerSensitive
2150     public Field getField(String name)
2151         throws NoSuchFieldException, SecurityException {
2152         Objects.requireNonNull(name);
2153         @SuppressWarnings("removal")
2154         SecurityManager sm = System.getSecurityManager();
2155         if (sm != null) {
2156             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
2157         }
2158         Field field = getField0(name);
2159         if (field == null) {
2160             throw new NoSuchFieldException(name);
2161         }
2162         return getReflectionFactory().copyField(field);
2163     }
2164 
2165 
2166     /**
2167      * Returns a {@code Method} object that reflects the specified public
2168      * member method of the class or interface represented by this
2169      * {@code Class} object. The {@code name} parameter is a
2170      * {@code String} specifying the simple name of the desired method. The
2171      * {@code parameterTypes} parameter is an array of {@code Class}
2172      * objects that identify the method's formal parameter types, in declared
2173      * order. If {@code parameterTypes} is {@code null}, it is
2174      * treated as if it were an empty array.
2175      *
2176      * <p> If this {@code Class} object represents an array type, then this
2177      * method finds any public method inherited by the array type from
2178      * {@code Object} except method {@code clone()}.
2179      *
2180      * <p> If this {@code Class} object represents an interface then this
2181      * method does not find any implicitly declared method from
2182      * {@code Object}. Therefore, if no methods are explicitly declared in
2183      * this interface or any of its superinterfaces, then this method does not
2184      * find any method.
2185      *
2186      * <p> This method does not find any method with name "{@code <init>}" or
2187      * "{@code <clinit>}".
2188      *
2189      * <p> Generally, the method to be reflected is determined by the 4 step
2190      * algorithm that follows.
2191      * Let C be the class or interface represented by this {@code Class} object:
2192      * <ol>
2193      * <li> A union of methods is composed of:
2194      *   <ol type="a">
2195      *   <li> C's declared public instance and static methods as returned by
2196      *        {@link #getDeclaredMethods()} and filtered to include only public
2197      *        methods that match given {@code name} and {@code parameterTypes}</li>
2198      *   <li> If C is a class other than {@code Object}, then include the result
2199      *        of invoking this algorithm recursively on the superclass of C.</li>
2200      *   <li> Include the results of invoking this algorithm recursively on all
2201      *        direct superinterfaces of C, but include only instance methods.</li>
2202      *   </ol></li>
2203      * <li> This union is partitioned into subsets of methods with same
2204      *      return type (the selection of methods from step 1 also guarantees that
2205      *      they have the same method name and parameter types).</li>
2206      * <li> Within each such subset only the most specific methods are selected.
2207      *      Let method M be a method from a set of methods with same VM
2208      *      signature (return type, name, parameter types).
2209      *      M is most specific if there is no such method N != M from the same
2210      *      set, such that N is more specific than M. N is more specific than M
2211      *      if:
2212      *   <ol type="a">
2213      *   <li> N is declared by a class and M is declared by an interface; or</li>
2214      *   <li> N and M are both declared by classes or both by interfaces and
2215      *        N's declaring type is the same as or a subtype of M's declaring type
2216      *        (clearly, if M's and N's declaring types are the same type, then
2217      *        M and N are the same method).</li>
2218      *   </ol></li>
2219      * <li> The result of this algorithm is chosen arbitrarily from the methods
2220      *      with most specific return type among all selected methods from step 3.
2221      *      Let R be a return type of a method M from the set of all selected methods
2222      *      from step 3. M is a method with most specific return type if there is
2223      *      no such method N != M from the same set, having return type S != R,
2224      *      such that S is a subtype of R as determined by
2225      *      R.class.{@link #isAssignableFrom}(S.class).
2226      * </ol>
2227      *
2228      * @apiNote There may be more than one method with matching name and
2229      * parameter types in a class because while the Java language forbids a
2230      * class to declare multiple methods with the same signature but different
2231      * return types, the Java virtual machine does not.  This
2232      * increased flexibility in the virtual machine can be used to
2233      * implement various language features.  For example, covariant
2234      * returns can be implemented with {@linkplain
2235      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
2236      * method and the overriding method would have the same
2237      * signature but different return types. This method would return the
2238      * overriding method as it would have a more specific return type.
2239      *
2240      * @param name the name of the method
2241      * @param parameterTypes the list of parameters
2242      * @return the {@code Method} object that matches the specified
2243      *         {@code name} and {@code parameterTypes}
2244      * @throws NoSuchMethodException if a matching method is not found
2245      *         or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
2246      * @throws NullPointerException if {@code name} is {@code null}
2247      * @throws SecurityException
2248      *         If a security manager, <i>s</i>, is present and
2249      *         the caller's class loader is not the same as or an
2250      *         ancestor of the class loader for the current class and
2251      *         invocation of {@link SecurityManager#checkPackageAccess
2252      *         s.checkPackageAccess()} denies access to the package
2253      *         of this class.
2254      *
2255      * @jls 8.2 Class Members
2256      * @jls 8.4 Method Declarations
2257      * @since 1.1
2258      */
2259     @CallerSensitive
2260     public Method getMethod(String name, Class<?>... parameterTypes)
2261         throws NoSuchMethodException, SecurityException {
2262         Objects.requireNonNull(name);
2263         @SuppressWarnings("removal")
2264         SecurityManager sm = System.getSecurityManager();
2265         if (sm != null) {
2266             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
2267         }
2268         Method method = getMethod0(name, parameterTypes);
2269         if (method == null) {
2270             throw new NoSuchMethodException(methodToString(name, parameterTypes));
2271         }
2272         return getReflectionFactory().copyMethod(method);
2273     }
2274 
2275     /**
2276      * Returns a {@code Constructor} object that reflects the specified
2277      * public constructor of the class represented by this {@code Class}
2278      * object. The {@code parameterTypes} parameter is an array of
2279      * {@code Class} objects that identify the constructor's formal
2280      * parameter types, in declared order.
2281      *
2282      * If this {@code Class} object represents an inner class
2283      * declared in a non-static context, the formal parameter types
2284      * include the explicit enclosing instance as the first parameter.
2285      *
2286      * <p> The constructor to reflect is the public constructor of the class
2287      * represented by this {@code Class} object whose formal parameter
2288      * types match those specified by {@code parameterTypes}.
2289      *
2290      * @param parameterTypes the parameter array
2291      * @return the {@code Constructor} object of the public constructor that
2292      *         matches the specified {@code parameterTypes}
2293      * @throws NoSuchMethodException if a matching constructor is not found,
2294      *         including when this {@code Class} object represents
2295      *         an interface, a primitive type, an array class, or void.
2296      * @throws SecurityException
2297      *         If a security manager, <i>s</i>, is present and
2298      *         the caller's class loader is not the same as or an
2299      *         ancestor of the class loader for the current class and
2300      *         invocation of {@link SecurityManager#checkPackageAccess
2301      *         s.checkPackageAccess()} denies access to the package
2302      *         of this class.
2303      *
2304      * @see #getDeclaredConstructor(Class<?>[])
2305      * @since 1.1
2306      */
2307     @CallerSensitive
2308     public Constructor<T> getConstructor(Class<?>... parameterTypes)
2309         throws NoSuchMethodException, SecurityException
2310     {
2311         @SuppressWarnings("removal")
2312         SecurityManager sm = System.getSecurityManager();
2313         if (sm != null) {
2314             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
2315         }
2316         return getReflectionFactory().copyConstructor(
2317             getConstructor0(parameterTypes, Member.PUBLIC));
2318     }
2319 
2320 
2321     /**
2322      * Returns an array of {@code Class} objects reflecting all the
2323      * classes and interfaces declared as members of the class represented by
2324      * this {@code Class} object. This includes public, protected, default
2325      * (package) access, and private classes and interfaces declared by the
2326      * class, but excludes inherited classes and interfaces.  This method
2327      * returns an array of length 0 if the class declares no classes or
2328      * interfaces as members, or if this {@code Class} object represents a
2329      * primitive type, an array class, or void.
2330      *
2331      * @return the array of {@code Class} objects representing all the
2332      *         declared members of this class
2333      * @throws SecurityException
2334      *         If a security manager, <i>s</i>, is present and any of the
2335      *         following conditions is met:
2336      *
2337      *         <ul>
2338      *
2339      *         <li> the caller's class loader is not the same as the
2340      *         class loader of this class and invocation of
2341      *         {@link SecurityManager#checkPermission
2342      *         s.checkPermission} method with
2343      *         {@code RuntimePermission("accessDeclaredMembers")}
2344      *         denies access to the declared classes within this class
2345      *
2346      *         <li> the caller's class loader is not the same as or an
2347      *         ancestor of the class loader for the current class and
2348      *         invocation of {@link SecurityManager#checkPackageAccess
2349      *         s.checkPackageAccess()} denies access to the package
2350      *         of this class
2351      *
2352      *         </ul>
2353      *
2354      * @since 1.1
2355      * @jls 8.5 Member Type Declarations
2356      */
2357     @CallerSensitive
2358     public Class<?>[] getDeclaredClasses() throws SecurityException {
2359         @SuppressWarnings("removal")
2360         SecurityManager sm = System.getSecurityManager();
2361         if (sm != null) {
2362             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), false);
2363         }
2364         return getDeclaredClasses0();
2365     }
2366 
2367 
2368     /**
2369      * Returns an array of {@code Field} objects reflecting all the fields
2370      * declared by the class or interface represented by this
2371      * {@code Class} object. This includes public, protected, default
2372      * (package) access, and private fields, but excludes inherited fields.
2373      *
2374      * <p> If this {@code Class} object represents a class or interface with no
2375      * declared fields, then this method returns an array of length 0.
2376      *
2377      * <p> If this {@code Class} object represents an array type, a primitive
2378      * type, or void, then this method returns an array of length 0.
2379      *
2380      * <p> The elements in the returned array are not sorted and are not in any
2381      * particular order.
2382      *
2383      * @return  the array of {@code Field} objects representing all the
2384      *          declared fields of this class
2385      * @throws  SecurityException
2386      *          If a security manager, <i>s</i>, is present and any of the
2387      *          following conditions is met:
2388      *
2389      *          <ul>
2390      *
2391      *          <li> the caller's class loader is not the same as the
2392      *          class loader of this class and invocation of
2393      *          {@link SecurityManager#checkPermission
2394      *          s.checkPermission} method with
2395      *          {@code RuntimePermission("accessDeclaredMembers")}
2396      *          denies access to the declared fields within this class
2397      *
2398      *          <li> the caller's class loader is not the same as or an
2399      *          ancestor of the class loader for the current class and
2400      *          invocation of {@link SecurityManager#checkPackageAccess
2401      *          s.checkPackageAccess()} denies access to the package
2402      *          of this class
2403      *
2404      *          </ul>
2405      *
2406      * @since 1.1
2407      * @jls 8.2 Class Members
2408      * @jls 8.3 Field Declarations
2409      */
2410     @CallerSensitive
2411     public Field[] getDeclaredFields() throws SecurityException {
2412         @SuppressWarnings("removal")
2413         SecurityManager sm = System.getSecurityManager();
2414         if (sm != null) {
2415             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2416         }
2417         return copyFields(privateGetDeclaredFields(false));
2418     }
2419 
2420     /**
2421      * Returns an array of {@code RecordComponent} objects representing all the
2422      * record components of this record class, or {@code null} if this class is
2423      * not a record class.
2424      *
2425      * <p> The components are returned in the same order that they are declared
2426      * in the record header. The array is empty if this record class has no
2427      * components. If the class is not a record class, that is {@link
2428      * #isRecord()} returns {@code false}, then this method returns {@code null}.
2429      * Conversely, if {@link #isRecord()} returns {@code true}, then this method
2430      * returns a non-null value.
2431      *
2432      * @apiNote
2433      * <p> The following method can be used to find the record canonical constructor:
2434      *
2435      * <pre>{@code
2436      * static <T extends Record> Constructor<T> getCanonicalConstructor(Class<T> cls)
2437      *     throws NoSuchMethodException {
2438      *   Class<?>[] paramTypes =
2439      *     Arrays.stream(cls.getRecordComponents())
2440      *           .map(RecordComponent::getType)
2441      *           .toArray(Class<?>[]::new);
2442      *   return cls.getDeclaredConstructor(paramTypes);
2443      * }}</pre>
2444      *
2445      * @return  An array of {@code RecordComponent} objects representing all the
2446      *          record components of this record class, or {@code null} if this
2447      *          class is not a record class
2448      * @throws  SecurityException
2449      *          If a security manager, <i>s</i>, is present and any of the
2450      *          following conditions is met:
2451      *
2452      *          <ul>
2453      *
2454      *          <li> the caller's class loader is not the same as the
2455      *          class loader of this class and invocation of
2456      *          {@link SecurityManager#checkPermission
2457      *          s.checkPermission} method with
2458      *          {@code RuntimePermission("accessDeclaredMembers")}
2459      *          denies access to the declared methods within this class
2460      *
2461      *          <li> the caller's class loader is not the same as or an
2462      *          ancestor of the class loader for the current class and
2463      *          invocation of {@link SecurityManager#checkPackageAccess
2464      *          s.checkPackageAccess()} denies access to the package
2465      *          of this class
2466      *
2467      *          </ul>
2468      *
2469      * @jls 8.10 Record Classes
2470      * @since 16
2471      */
2472     @CallerSensitive
2473     public RecordComponent[] getRecordComponents() {
2474         @SuppressWarnings("removal")
2475         SecurityManager sm = System.getSecurityManager();
2476         if (sm != null) {
2477             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2478         }
2479         if (!isRecord()) {
2480             return null;
2481         }
2482         return getRecordComponents0();
2483     }
2484 
2485     /**
2486      * Returns an array containing {@code Method} objects reflecting all the
2487      * declared methods of the class or interface represented by this {@code
2488      * Class} object, including public, protected, default (package)
2489      * access, and private methods, but excluding inherited methods.
2490      * The declared methods may include methods <em>not</em> in the
2491      * source of the class or interface, including {@linkplain
2492      * Method#isBridge bridge methods} and other {@linkplain
2493      * Executable#isSynthetic synthetic} methods added by compilers.
2494      *
2495      * <p> If this {@code Class} object represents a class or interface that
2496      * has multiple declared methods with the same name and parameter types,
2497      * but different return types, then the returned array has a {@code Method}
2498      * object for each such method.
2499      *
2500      * <p> If this {@code Class} object represents a class or interface that
2501      * has a class initialization method {@code <clinit>}, then the returned
2502      * array does <em>not</em> have a corresponding {@code Method} object.
2503      *
2504      * <p> If this {@code Class} object represents a class or interface with no
2505      * declared methods, then the returned array has length 0.
2506      *
2507      * <p> If this {@code Class} object represents an array type, a primitive
2508      * type, or void, then the returned array has length 0.
2509      *
2510      * <p> The elements in the returned array are not sorted and are not in any
2511      * particular order.
2512      *
2513      * @return  the array of {@code Method} objects representing all the
2514      *          declared methods of this class
2515      * @throws  SecurityException
2516      *          If a security manager, <i>s</i>, is present and any of the
2517      *          following conditions is met:
2518      *
2519      *          <ul>
2520      *
2521      *          <li> the caller's class loader is not the same as the
2522      *          class loader of this class and invocation of
2523      *          {@link SecurityManager#checkPermission
2524      *          s.checkPermission} method with
2525      *          {@code RuntimePermission("accessDeclaredMembers")}
2526      *          denies access to the declared methods within this class
2527      *
2528      *          <li> the caller's class loader is not the same as or an
2529      *          ancestor of the class loader for the current class and
2530      *          invocation of {@link SecurityManager#checkPackageAccess
2531      *          s.checkPackageAccess()} denies access to the package
2532      *          of this class
2533      *
2534      *          </ul>
2535      *
2536      * @jls 8.2 Class Members
2537      * @jls 8.4 Method Declarations
2538      * @see <a
2539      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
2540      * programming language and JVM modeling in core reflection</a>
2541      * @since 1.1
2542      */
2543     @CallerSensitive
2544     public Method[] getDeclaredMethods() throws SecurityException {
2545         @SuppressWarnings("removal")
2546         SecurityManager sm = System.getSecurityManager();
2547         if (sm != null) {
2548             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2549         }
2550         return copyMethods(privateGetDeclaredMethods(false));
2551     }
2552 
2553     /**
2554      * Returns an array of {@code Constructor} objects reflecting all the
2555      * constructors implicitly or explicitly declared by the class represented by this
2556      * {@code Class} object. These are public, protected, default
2557      * (package) access, and private constructors.  The elements in the array
2558      * returned are not sorted and are not in any particular order.  If the
2559      * class has a default constructor (JLS {@jls 8.8.9}), it is included in the returned array.
2560      * If a record class has a canonical constructor (JLS {@jls
2561      * 8.10.4.1}, {@jls 8.10.4.2}), it is included in the returned array.
2562      *
2563      * This method returns an array of length 0 if this {@code Class}
2564      * object represents an interface, a primitive type, an array class, or
2565      * void.
2566      *
2567      * @return  the array of {@code Constructor} objects representing all the
2568      *          declared constructors of this class
2569      * @throws  SecurityException
2570      *          If a security manager, <i>s</i>, is present and any of the
2571      *          following conditions is met:
2572      *
2573      *          <ul>
2574      *
2575      *          <li> the caller's class loader is not the same as the
2576      *          class loader of this class and invocation of
2577      *          {@link SecurityManager#checkPermission
2578      *          s.checkPermission} method with
2579      *          {@code RuntimePermission("accessDeclaredMembers")}
2580      *          denies access to the declared constructors within this class
2581      *
2582      *          <li> the caller's class loader is not the same as or an
2583      *          ancestor of the class loader for the current class and
2584      *          invocation of {@link SecurityManager#checkPackageAccess
2585      *          s.checkPackageAccess()} denies access to the package
2586      *          of this class
2587      *
2588      *          </ul>
2589      *
2590      * @since 1.1
2591      * @see #getConstructors()
2592      * @jls 8.8 Constructor Declarations
2593      */
2594     @CallerSensitive
2595     public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
2596         @SuppressWarnings("removal")
2597         SecurityManager sm = System.getSecurityManager();
2598         if (sm != null) {
2599             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2600         }
2601         return copyConstructors(privateGetDeclaredConstructors(false));
2602     }
2603 
2604 
2605     /**
2606      * Returns a {@code Field} object that reflects the specified declared
2607      * field of the class or interface represented by this {@code Class}
2608      * object. The {@code name} parameter is a {@code String} that specifies
2609      * the simple name of the desired field.
2610      *
2611      * <p> If this {@code Class} object represents an array type, then this
2612      * method does not find the {@code length} field of the array type.
2613      *
2614      * @param name the name of the field
2615      * @return  the {@code Field} object for the specified field in this
2616      *          class
2617      * @throws  NoSuchFieldException if a field with the specified name is
2618      *          not found.
2619      * @throws  NullPointerException if {@code name} is {@code null}
2620      * @throws  SecurityException
2621      *          If a security manager, <i>s</i>, is present and any of the
2622      *          following conditions is met:
2623      *
2624      *          <ul>
2625      *
2626      *          <li> the caller's class loader is not the same as the
2627      *          class loader of this class and invocation of
2628      *          {@link SecurityManager#checkPermission
2629      *          s.checkPermission} method with
2630      *          {@code RuntimePermission("accessDeclaredMembers")}
2631      *          denies access to the declared field
2632      *
2633      *          <li> the caller's class loader is not the same as or an
2634      *          ancestor of the class loader for the current class and
2635      *          invocation of {@link SecurityManager#checkPackageAccess
2636      *          s.checkPackageAccess()} denies access to the package
2637      *          of this class
2638      *
2639      *          </ul>
2640      *
2641      * @since 1.1
2642      * @jls 8.2 Class Members
2643      * @jls 8.3 Field Declarations
2644      */
2645     @CallerSensitive
2646     public Field getDeclaredField(String name)
2647         throws NoSuchFieldException, SecurityException {
2648         Objects.requireNonNull(name);
2649         @SuppressWarnings("removal")
2650         SecurityManager sm = System.getSecurityManager();
2651         if (sm != null) {
2652             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2653         }
2654         Field field = searchFields(privateGetDeclaredFields(false), name);
2655         if (field == null) {
2656             throw new NoSuchFieldException(name);
2657         }
2658         return getReflectionFactory().copyField(field);
2659     }
2660 
2661 
2662     /**
2663      * Returns a {@code Method} object that reflects the specified
2664      * declared method of the class or interface represented by this
2665      * {@code Class} object. The {@code name} parameter is a
2666      * {@code String} that specifies the simple name of the desired
2667      * method, and the {@code parameterTypes} parameter is an array of
2668      * {@code Class} objects that identify the method's formal parameter
2669      * types, in declared order.  If more than one method with the same
2670      * parameter types is declared in a class, and one of these methods has a
2671      * return type that is more specific than any of the others, that method is
2672      * returned; otherwise one of the methods is chosen arbitrarily.  If the
2673      * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
2674      * is raised.
2675      *
2676      * <p> If this {@code Class} object represents an array type, then this
2677      * method does not find the {@code clone()} method.
2678      *
2679      * @param name the name of the method
2680      * @param parameterTypes the parameter array
2681      * @return  the {@code Method} object for the method of this class
2682      *          matching the specified name and parameters
2683      * @throws  NoSuchMethodException if a matching method is not found.
2684      * @throws  NullPointerException if {@code name} is {@code null}
2685      * @throws  SecurityException
2686      *          If a security manager, <i>s</i>, is present and any of the
2687      *          following conditions is met:
2688      *
2689      *          <ul>
2690      *
2691      *          <li> the caller's class loader is not the same as the
2692      *          class loader of this class and invocation of
2693      *          {@link SecurityManager#checkPermission
2694      *          s.checkPermission} method with
2695      *          {@code RuntimePermission("accessDeclaredMembers")}
2696      *          denies access to the declared method
2697      *
2698      *          <li> the caller's class loader is not the same as or an
2699      *          ancestor of the class loader for the current class and
2700      *          invocation of {@link SecurityManager#checkPackageAccess
2701      *          s.checkPackageAccess()} denies access to the package
2702      *          of this class
2703      *
2704      *          </ul>
2705      *
2706      * @jls 8.2 Class Members
2707      * @jls 8.4 Method Declarations
2708      * @since 1.1
2709      */
2710     @CallerSensitive
2711     public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2712         throws NoSuchMethodException, SecurityException {
2713         Objects.requireNonNull(name);
2714         @SuppressWarnings("removal")
2715         SecurityManager sm = System.getSecurityManager();
2716         if (sm != null) {
2717             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2718         }
2719         Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
2720         if (method == null) {
2721             throw new NoSuchMethodException(methodToString(name, parameterTypes));
2722         }
2723         return getReflectionFactory().copyMethod(method);
2724     }
2725 
2726     /**
2727      * Returns the list of {@code Method} objects for the declared public
2728      * methods of this class or interface that have the specified method name
2729      * and parameter types.
2730      *
2731      * @param name the name of the method
2732      * @param parameterTypes the parameter array
2733      * @return the list of {@code Method} objects for the public methods of
2734      *         this class matching the specified name and parameters
2735      */
2736     List<Method> getDeclaredPublicMethods(String name, Class<?>... parameterTypes) {
2737         Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);
2738         ReflectionFactory factory = getReflectionFactory();
2739         List<Method> result = new ArrayList<>();
2740         for (Method method : methods) {
2741             if (method.getName().equals(name)
2742                 && Arrays.equals(
2743                     factory.getExecutableSharedParameterTypes(method),
2744                     parameterTypes)) {
2745                 result.add(factory.copyMethod(method));
2746             }
2747         }
2748         return result;
2749     }
2750 
2751     /**
2752      * Returns a {@code Constructor} object that reflects the specified
2753      * constructor of the class represented by this
2754      * {@code Class} object.  The {@code parameterTypes} parameter is
2755      * an array of {@code Class} objects that identify the constructor's
2756      * formal parameter types, in declared order.
2757      *
2758      * If this {@code Class} object represents an inner class
2759      * declared in a non-static context, the formal parameter types
2760      * include the explicit enclosing instance as the first parameter.
2761      *
2762      * @param parameterTypes the parameter array
2763      * @return  The {@code Constructor} object for the constructor with the
2764      *          specified parameter list
2765      * @throws  NoSuchMethodException if a matching constructor is not found,
2766      *          including when this {@code Class} object represents
2767      *          an interface, a primitive type, an array class, or void.
2768      * @throws  SecurityException
2769      *          If a security manager, <i>s</i>, is present and any of the
2770      *          following conditions is met:
2771      *
2772      *          <ul>
2773      *
2774      *          <li> the caller's class loader is not the same as the
2775      *          class loader of this class and invocation of
2776      *          {@link SecurityManager#checkPermission
2777      *          s.checkPermission} method with
2778      *          {@code RuntimePermission("accessDeclaredMembers")}
2779      *          denies access to the declared constructor
2780      *
2781      *          <li> the caller's class loader is not the same as or an
2782      *          ancestor of the class loader for the current class and
2783      *          invocation of {@link SecurityManager#checkPackageAccess
2784      *          s.checkPackageAccess()} denies access to the package
2785      *          of this class
2786      *
2787      *          </ul>
2788      *
2789      * @see #getConstructor(Class<?>[])
2790      * @since 1.1
2791      */
2792     @CallerSensitive
2793     public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
2794         throws NoSuchMethodException, SecurityException
2795     {
2796         @SuppressWarnings("removal")
2797         SecurityManager sm = System.getSecurityManager();
2798         if (sm != null) {
2799             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2800         }
2801 
2802         return getReflectionFactory().copyConstructor(
2803             getConstructor0(parameterTypes, Member.DECLARED));
2804     }
2805 
2806     /**
2807      * Finds a resource with a given name.
2808      *
2809      * <p> If this class is in a named {@link Module Module} then this method
2810      * will attempt to find the resource in the module. This is done by
2811      * delegating to the module's class loader {@link
2812      * ClassLoader#findResource(String,String) findResource(String,String)}
2813      * method, invoking it with the module name and the absolute name of the
2814      * resource. Resources in named modules are subject to the rules for
2815      * encapsulation specified in the {@code Module} {@link
2816      * Module#getResourceAsStream getResourceAsStream} method and so this
2817      * method returns {@code null} when the resource is a
2818      * non-"{@code .class}" resource in a package that is not open to the
2819      * caller's module.
2820      *
2821      * <p> Otherwise, if this class is not in a named module then the rules for
2822      * searching resources associated with a given class are implemented by the
2823      * defining {@linkplain ClassLoader class loader} of the class.  This method
2824      * delegates to this {@code Class} object's class loader.
2825      * If this {@code Class} object was loaded by the bootstrap class loader,
2826      * the method delegates to {@link ClassLoader#getSystemResourceAsStream}.
2827      *
2828      * <p> Before delegation, an absolute resource name is constructed from the
2829      * given resource name using this algorithm:
2830      *
2831      * <ul>
2832      *
2833      * <li> If the {@code name} begins with a {@code '/'}
2834      * (<code>'&#92;u002f'</code>), then the absolute name of the resource is the
2835      * portion of the {@code name} following the {@code '/'}.
2836      *
2837      * <li> Otherwise, the absolute name is of the following form:
2838      *
2839      * <blockquote>
2840      *   {@code modified_package_name/name}
2841      * </blockquote>
2842      *
2843      * <p> Where the {@code modified_package_name} is the package name of this
2844      * object with {@code '/'} substituted for {@code '.'}
2845      * (<code>'&#92;u002e'</code>).
2846      *
2847      * </ul>
2848      *
2849      * @param  name name of the desired resource
2850      * @return  A {@link java.io.InputStream} object; {@code null} if no
2851      *          resource with this name is found, the resource is in a package
2852      *          that is not {@linkplain Module#isOpen(String, Module) open} to at
2853      *          least the caller module, or access to the resource is denied
2854      *          by the security manager.
2855      * @throws  NullPointerException If {@code name} is {@code null}
2856      *
2857      * @see Module#getResourceAsStream(String)
2858      * @since  1.1
2859      * @revised 9
2860      */
2861     @CallerSensitive
2862     public InputStream getResourceAsStream(String name) {
2863         name = resolveName(name);
2864 
2865         Module thisModule = getModule();
2866         if (thisModule.isNamed()) {
2867             // check if resource can be located by caller
2868             if (Resources.canEncapsulate(name)
2869                 && !isOpenToCaller(name, Reflection.getCallerClass())) {
2870                 return null;
2871             }
2872 
2873             // resource not encapsulated or in package open to caller
2874             String mn = thisModule.getName();
2875             ClassLoader cl = classLoader;
2876             try {
2877 
2878                 // special-case built-in class loaders to avoid the
2879                 // need for a URL connection
2880                 if (cl == null) {
2881                     return BootLoader.findResourceAsStream(mn, name);
2882                 } else if (cl instanceof BuiltinClassLoader) {
2883                     return ((BuiltinClassLoader) cl).findResourceAsStream(mn, name);
2884                 } else {
2885                     URL url = cl.findResource(mn, name);
2886                     return (url != null) ? url.openStream() : null;
2887                 }
2888 
2889             } catch (IOException | SecurityException e) {
2890                 return null;
2891             }
2892         }
2893 
2894         // unnamed module
2895         ClassLoader cl = classLoader;
2896         if (cl == null) {
2897             return ClassLoader.getSystemResourceAsStream(name);
2898         } else {
2899             return cl.getResourceAsStream(name);
2900         }
2901     }
2902 
2903     /**
2904      * Finds a resource with a given name.
2905      *
2906      * <p> If this class is in a named {@link Module Module} then this method
2907      * will attempt to find the resource in the module. This is done by
2908      * delegating to the module's class loader {@link
2909      * ClassLoader#findResource(String,String) findResource(String,String)}
2910      * method, invoking it with the module name and the absolute name of the
2911      * resource. Resources in named modules are subject to the rules for
2912      * encapsulation specified in the {@code Module} {@link
2913      * Module#getResourceAsStream getResourceAsStream} method and so this
2914      * method returns {@code null} when the resource is a
2915      * non-"{@code .class}" resource in a package that is not open to the
2916      * caller's module.
2917      *
2918      * <p> Otherwise, if this class is not in a named module then the rules for
2919      * searching resources associated with a given class are implemented by the
2920      * defining {@linkplain ClassLoader class loader} of the class.  This method
2921      * delegates to this {@code Class} object's class loader.
2922      * If this {@code Class} object was loaded by the bootstrap class loader,
2923      * the method delegates to {@link ClassLoader#getSystemResource}.
2924      *
2925      * <p> Before delegation, an absolute resource name is constructed from the
2926      * given resource name using this algorithm:
2927      *
2928      * <ul>
2929      *
2930      * <li> If the {@code name} begins with a {@code '/'}
2931      * (<code>'&#92;u002f'</code>), then the absolute name of the resource is the
2932      * portion of the {@code name} following the {@code '/'}.
2933      *
2934      * <li> Otherwise, the absolute name is of the following form:
2935      *
2936      * <blockquote>
2937      *   {@code modified_package_name/name}
2938      * </blockquote>
2939      *
2940      * <p> Where the {@code modified_package_name} is the package name of this
2941      * object with {@code '/'} substituted for {@code '.'}
2942      * (<code>'&#92;u002e'</code>).
2943      *
2944      * </ul>
2945      *
2946      * @param  name name of the desired resource
2947      * @return A {@link java.net.URL} object; {@code null} if no resource with
2948      *         this name is found, the resource cannot be located by a URL, the
2949      *         resource is in a package that is not
2950      *         {@linkplain Module#isOpen(String, Module) open} to at least the caller
2951      *         module, or access to the resource is denied by the security
2952      *         manager.
2953      * @throws NullPointerException If {@code name} is {@code null}
2954      * @since  1.1
2955      * @revised 9
2956      */
2957     @CallerSensitive
2958     public URL getResource(String name) {
2959         name = resolveName(name);
2960 
2961         Module thisModule = getModule();
2962         if (thisModule.isNamed()) {
2963             // check if resource can be located by caller
2964             if (Resources.canEncapsulate(name)
2965                 && !isOpenToCaller(name, Reflection.getCallerClass())) {
2966                 return null;
2967             }
2968 
2969             // resource not encapsulated or in package open to caller
2970             String mn = thisModule.getName();
2971             ClassLoader cl = classLoader;
2972             try {
2973                 if (cl == null) {
2974                     return BootLoader.findResource(mn, name);
2975                 } else {
2976                     return cl.findResource(mn, name);
2977                 }
2978             } catch (IOException ioe) {
2979                 return null;
2980             }
2981         }
2982 
2983         // unnamed module
2984         ClassLoader cl = classLoader;
2985         if (cl == null) {
2986             return ClassLoader.getSystemResource(name);
2987         } else {
2988             return cl.getResource(name);
2989         }
2990     }
2991 
2992     /**
2993      * Returns true if a resource with the given name can be located by the
2994      * given caller. All resources in a module can be located by code in
2995      * the module. For other callers, then the package needs to be open to
2996      * the caller.
2997      */
2998     private boolean isOpenToCaller(String name, Class<?> caller) {
2999         // assert getModule().isNamed();
3000         Module thisModule = getModule();
3001         Module callerModule = (caller != null) ? caller.getModule() : null;
3002         if (callerModule != thisModule) {
3003             String pn = Resources.toPackageName(name);
3004             if (thisModule.getDescriptor().packages().contains(pn)) {
3005                 if (callerModule == null && !thisModule.isOpen(pn)) {
3006                     // no caller, package not open
3007                     return false;
3008                 }
3009                 if (!thisModule.isOpen(pn, callerModule)) {
3010                     // package not open to caller
3011                     return false;
3012                 }
3013             }
3014         }
3015         return true;
3016     }
3017 
3018 
3019     /** protection domain returned when the internal domain is null */
3020     private static java.security.ProtectionDomain allPermDomain;
3021 
3022     /**
3023      * Returns the {@code ProtectionDomain} of this class.  If there is a
3024      * security manager installed, this method first calls the security
3025      * manager's {@code checkPermission} method with a
3026      * {@code RuntimePermission("getProtectionDomain")} permission to
3027      * ensure it's ok to get the
3028      * {@code ProtectionDomain}.
3029      *
3030      * @return the ProtectionDomain of this class
3031      *
3032      * @throws SecurityException
3033      *        if a security manager exists and its
3034      *        {@code checkPermission} method doesn't allow
3035      *        getting the ProtectionDomain.
3036      *
3037      * @see java.security.ProtectionDomain
3038      * @see SecurityManager#checkPermission
3039      * @see java.lang.RuntimePermission
3040      * @since 1.2
3041      */
3042     public java.security.ProtectionDomain getProtectionDomain() {
3043         @SuppressWarnings("removal")
3044         SecurityManager sm = System.getSecurityManager();
3045         if (sm != null) {
3046             sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
3047         }
3048         return protectionDomain();
3049     }
3050 
3051     // package-private
3052     java.security.ProtectionDomain protectionDomain() {
3053         java.security.ProtectionDomain pd = getProtectionDomain0();
3054         if (pd == null) {
3055             if (allPermDomain == null) {
3056                 java.security.Permissions perms =
3057                     new java.security.Permissions();
3058                 perms.add(SecurityConstants.ALL_PERMISSION);
3059                 allPermDomain =
3060                     new java.security.ProtectionDomain(null, perms);
3061             }
3062             pd = allPermDomain;
3063         }
3064         return pd;
3065     }
3066 
3067     /**
3068      * Returns the ProtectionDomain of this class.
3069      */
3070     private native java.security.ProtectionDomain getProtectionDomain0();
3071 
3072     /*
3073      * Return the Virtual Machine's Class object for the named
3074      * primitive type.
3075      */
3076     static native Class<?> getPrimitiveClass(String name);
3077 
3078     /*
3079      * Check if client is allowed to access members.  If access is denied,
3080      * throw a SecurityException.
3081      *
3082      * This method also enforces package access.
3083      *
3084      * <p> Default policy: allow all clients access with normal Java access
3085      * control.
3086      *
3087      * <p> NOTE: should only be called if a SecurityManager is installed
3088      */
3089     private void checkMemberAccess(@SuppressWarnings("removal") SecurityManager sm, int which,
3090                                    Class<?> caller, boolean checkProxyInterfaces) {
3091         /* Default policy allows access to all {@link Member#PUBLIC} members,
3092          * as well as access to classes that have the same class loader as the caller.
3093          * In all other cases, it requires RuntimePermission("accessDeclaredMembers")
3094          * permission.
3095          */
3096         final ClassLoader ccl = ClassLoader.getClassLoader(caller);
3097         if (which != Member.PUBLIC) {
3098             final ClassLoader cl = classLoader;
3099             if (ccl != cl) {
3100                 sm.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3101             }
3102         }
3103         this.checkPackageAccess(sm, ccl, checkProxyInterfaces);
3104     }
3105 
3106     /*
3107      * Checks if a client loaded in ClassLoader ccl is allowed to access this
3108      * class under the current package access policy. If access is denied,
3109      * throw a SecurityException.
3110      *
3111      * NOTE: this method should only be called if a SecurityManager is active
3112      */
3113     private void checkPackageAccess(@SuppressWarnings("removal") SecurityManager sm, final ClassLoader ccl,
3114                                     boolean checkProxyInterfaces) {
3115         final ClassLoader cl = classLoader;
3116 
3117         if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
3118             String pkg = this.getPackageName();
3119             if (!pkg.isEmpty()) {
3120                 // skip the package access check on a proxy class in default proxy package
3121                 if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {
3122                     sm.checkPackageAccess(pkg);
3123                 }
3124             }
3125         }
3126         // check package access on the proxy interfaces
3127         if (checkProxyInterfaces && Proxy.isProxyClass(this)) {
3128             ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());
3129         }
3130     }
3131 
3132     /*
3133      * Checks if a client loaded in ClassLoader ccl is allowed to access the provided
3134      * classes under the current package access policy. If access is denied,
3135      * throw a SecurityException.
3136      *
3137      * NOTE: this method should only be called if a SecurityManager is active
3138      *       classes must be non-empty
3139      *       all classes provided must be loaded by the same ClassLoader
3140      * NOTE: this method does not support Proxy classes
3141      */
3142     private static void checkPackageAccessForPermittedSubclasses(@SuppressWarnings("removal") SecurityManager sm,
3143                                     final ClassLoader ccl, Class<?>[] subClasses) {
3144         final ClassLoader cl = subClasses[0].classLoader;
3145 
3146         if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
3147             Set<String> packages = new HashSet<>();
3148 
3149             for (Class<?> c : subClasses) {
3150                 if (Proxy.isProxyClass(c))
3151                     throw new InternalError("a permitted subclass should not be a proxy class: " + c);
3152                 String pkg = c.getPackageName();
3153                 if (!pkg.isEmpty()) {
3154                     packages.add(pkg);
3155                 }
3156             }
3157             for (String pkg : packages) {
3158                 sm.checkPackageAccess(pkg);
3159             }
3160         }
3161     }
3162 
3163     /**
3164      * Add a package name prefix if the name is not absolute. Remove leading "/"
3165      * if name is absolute
3166      */
3167     private String resolveName(String name) {
3168         if (!name.startsWith("/")) {
3169             String baseName = getPackageName();
3170             if (!baseName.isEmpty()) {
3171                 int len = baseName.length() + 1 + name.length();
3172                 StringBuilder sb = new StringBuilder(len);
3173                 name = sb.append(baseName.replace('.', '/'))
3174                     .append('/')
3175                     .append(name)
3176                     .toString();
3177             }
3178         } else {
3179             name = name.substring(1);
3180         }
3181         return name;
3182     }
3183 
3184     /**
3185      * Atomic operations support.
3186      */
3187     private static class Atomic {
3188         // initialize Unsafe machinery here, since we need to call Class.class instance method
3189         // and have to avoid calling it in the static initializer of the Class class...
3190         private static final Unsafe unsafe = Unsafe.getUnsafe();
3191         // offset of Class.reflectionData instance field
3192         private static final long reflectionDataOffset
3193                 = unsafe.objectFieldOffset(Class.class, "reflectionData");
3194         // offset of Class.annotationType instance field
3195         private static final long annotationTypeOffset
3196                 = unsafe.objectFieldOffset(Class.class, "annotationType");
3197         // offset of Class.annotationData instance field
3198         private static final long annotationDataOffset
3199                 = unsafe.objectFieldOffset(Class.class, "annotationData");
3200 
3201         static <T> boolean casReflectionData(Class<?> clazz,
3202                                              SoftReference<ReflectionData<T>> oldData,
3203                                              SoftReference<ReflectionData<T>> newData) {
3204             return unsafe.compareAndSetReference(clazz, reflectionDataOffset, oldData, newData);
3205         }
3206 
3207         static boolean casAnnotationType(Class<?> clazz,
3208                                          AnnotationType oldType,
3209                                          AnnotationType newType) {
3210             return unsafe.compareAndSetReference(clazz, annotationTypeOffset, oldType, newType);
3211         }
3212 
3213         static boolean casAnnotationData(Class<?> clazz,
3214                                          AnnotationData oldData,
3215                                          AnnotationData newData) {
3216             return unsafe.compareAndSetReference(clazz, annotationDataOffset, oldData, newData);
3217         }
3218     }
3219 
3220     /**
3221      * Reflection support.
3222      */
3223 
3224     // Reflection data caches various derived names and reflective members. Cached
3225     // values may be invalidated when JVM TI RedefineClasses() is called
3226     private static class ReflectionData<T> {
3227         volatile Field[] declaredFields;
3228         volatile Field[] publicFields;
3229         volatile Method[] declaredMethods;
3230         volatile Method[] publicMethods;
3231         volatile Constructor<T>[] declaredConstructors;
3232         volatile Constructor<T>[] publicConstructors;
3233         // Intermediate results for getFields and getMethods
3234         volatile Field[] declaredPublicFields;
3235         volatile Method[] declaredPublicMethods;
3236         volatile Class<?>[] interfaces;
3237 
3238         // Cached names
3239         String simpleName;
3240         String canonicalName;
3241         static final String NULL_SENTINEL = new String();
3242 
3243         // Value of classRedefinedCount when we created this ReflectionData instance
3244         final int redefinedCount;
3245 
3246         ReflectionData(int redefinedCount) {
3247             this.redefinedCount = redefinedCount;
3248         }
3249     }
3250 
3251     private transient volatile SoftReference<ReflectionData<T>> reflectionData;
3252 
3253     // Incremented by the VM on each call to JVM TI RedefineClasses()
3254     // that redefines this class or a superclass.
3255     private transient volatile int classRedefinedCount;
3256 
3257     // Lazily create and cache ReflectionData
3258     private ReflectionData<T> reflectionData() {
3259         SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
3260         int classRedefinedCount = this.classRedefinedCount;
3261         ReflectionData<T> rd;
3262         if (reflectionData != null &&
3263             (rd = reflectionData.get()) != null &&
3264             rd.redefinedCount == classRedefinedCount) {
3265             return rd;
3266         }
3267         // else no SoftReference or cleared SoftReference or stale ReflectionData
3268         // -> create and replace new instance
3269         return newReflectionData(reflectionData, classRedefinedCount);
3270     }
3271 
3272     private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
3273                                                 int classRedefinedCount) {
3274         while (true) {
3275             ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
3276             // try to CAS it...
3277             if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
3278                 return rd;
3279             }
3280             // else retry
3281             oldReflectionData = this.reflectionData;
3282             classRedefinedCount = this.classRedefinedCount;
3283             if (oldReflectionData != null &&
3284                 (rd = oldReflectionData.get()) != null &&
3285                 rd.redefinedCount == classRedefinedCount) {
3286                 return rd;
3287             }
3288         }
3289     }
3290 
3291     // Generic signature handling
3292     private native String getGenericSignature0();
3293 
3294     // Generic info repository; lazily initialized
3295     private transient volatile ClassRepository genericInfo;
3296 
3297     // accessor for factory
3298     private GenericsFactory getFactory() {
3299         // create scope and factory
3300         return CoreReflectionFactory.make(this, ClassScope.make(this));
3301     }
3302 
3303     // accessor for generic info repository;
3304     // generic info is lazily initialized
3305     private ClassRepository getGenericInfo() {
3306         ClassRepository genericInfo = this.genericInfo;
3307         if (genericInfo == null) {
3308             String signature = getGenericSignature0();
3309             if (signature == null) {
3310                 genericInfo = ClassRepository.NONE;
3311             } else {
3312                 genericInfo = ClassRepository.make(signature, getFactory());
3313             }
3314             this.genericInfo = genericInfo;
3315         }
3316         return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
3317     }
3318 
3319     // Annotations handling
3320     native byte[] getRawAnnotations();
3321     // Since 1.8
3322     native byte[] getRawTypeAnnotations();
3323     static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
3324         return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
3325     }
3326 
3327     native ConstantPool getConstantPool();
3328 
3329     //
3330     //
3331     // java.lang.reflect.Field handling
3332     //
3333     //
3334 
3335     // Returns an array of "root" fields. These Field objects must NOT
3336     // be propagated to the outside world, but must instead be copied
3337     // via ReflectionFactory.copyField.
3338     private Field[] privateGetDeclaredFields(boolean publicOnly) {
3339         Field[] res;
3340         ReflectionData<T> rd = reflectionData();
3341         if (rd != null) {
3342             res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
3343             if (res != null) return res;
3344         }
3345         // No cached value available; request value from VM
3346         res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
3347         if (rd != null) {
3348             if (publicOnly) {
3349                 rd.declaredPublicFields = res;
3350             } else {
3351                 rd.declaredFields = res;
3352             }
3353         }
3354         return res;
3355     }
3356 
3357     // Returns an array of "root" fields. These Field objects must NOT
3358     // be propagated to the outside world, but must instead be copied
3359     // via ReflectionFactory.copyField.
3360     private Field[] privateGetPublicFields() {
3361         Field[] res;
3362         ReflectionData<T> rd = reflectionData();
3363         if (rd != null) {
3364             res = rd.publicFields;
3365             if (res != null) return res;
3366         }
3367 
3368         // Use a linked hash set to ensure order is preserved and
3369         // fields from common super interfaces are not duplicated
3370         LinkedHashSet<Field> fields = new LinkedHashSet<>();
3371 
3372         // Local fields
3373         addAll(fields, privateGetDeclaredFields(true));
3374 
3375         // Direct superinterfaces, recursively
3376         for (Class<?> si : getInterfaces()) {
3377             addAll(fields, si.privateGetPublicFields());
3378         }
3379 
3380         // Direct superclass, recursively
3381         Class<?> sc = getSuperclass();
3382         if (sc != null) {
3383             addAll(fields, sc.privateGetPublicFields());
3384         }
3385 
3386         res = fields.toArray(new Field[0]);
3387         if (rd != null) {
3388             rd.publicFields = res;
3389         }
3390         return res;
3391     }
3392 
3393     private static void addAll(Collection<Field> c, Field[] o) {
3394         for (Field f : o) {
3395             c.add(f);
3396         }
3397     }
3398 
3399 
3400     //
3401     //
3402     // java.lang.reflect.Constructor handling
3403     //
3404     //
3405 
3406     // Returns an array of "root" constructors. These Constructor
3407     // objects must NOT be propagated to the outside world, but must
3408     // instead be copied via ReflectionFactory.copyConstructor.
3409     private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
3410         Constructor<T>[] res;
3411         ReflectionData<T> rd = reflectionData();
3412         if (rd != null) {
3413             res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
3414             if (res != null) return res;
3415         }
3416         // No cached value available; request value from VM
3417         if (isInterface()) {
3418             @SuppressWarnings("unchecked")
3419             Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
3420             res = temporaryRes;
3421         } else {
3422             res = getDeclaredConstructors0(publicOnly);
3423         }
3424         if (rd != null) {
3425             if (publicOnly) {
3426                 rd.publicConstructors = res;
3427             } else {
3428                 rd.declaredConstructors = res;
3429             }
3430         }
3431         return res;
3432     }
3433 
3434     //
3435     //
3436     // java.lang.reflect.Method handling
3437     //
3438     //
3439 
3440     // Returns an array of "root" methods. These Method objects must NOT
3441     // be propagated to the outside world, but must instead be copied
3442     // via ReflectionFactory.copyMethod.
3443     private Method[] privateGetDeclaredMethods(boolean publicOnly) {
3444         Method[] res;
3445         ReflectionData<T> rd = reflectionData();
3446         if (rd != null) {
3447             res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
3448             if (res != null) return res;
3449         }
3450         // No cached value available; request value from VM
3451         res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
3452         if (rd != null) {
3453             if (publicOnly) {
3454                 rd.declaredPublicMethods = res;
3455             } else {
3456                 rd.declaredMethods = res;
3457             }
3458         }
3459         return res;
3460     }
3461 
3462     // Returns an array of "root" methods. These Method objects must NOT
3463     // be propagated to the outside world, but must instead be copied
3464     // via ReflectionFactory.copyMethod.
3465     private Method[] privateGetPublicMethods() {
3466         Method[] res;
3467         ReflectionData<T> rd = reflectionData();
3468         if (rd != null) {
3469             res = rd.publicMethods;
3470             if (res != null) return res;
3471         }
3472 
3473         // No cached value available; compute value recursively.
3474         // Start by fetching public declared methods...
3475         PublicMethods pms = new PublicMethods();
3476         for (Method m : privateGetDeclaredMethods(/* publicOnly */ true)) {
3477             pms.merge(m);
3478         }
3479         // ...then recur over superclass methods...
3480         Class<?> sc = getSuperclass();
3481         if (sc != null) {
3482             for (Method m : sc.privateGetPublicMethods()) {
3483                 pms.merge(m);
3484             }
3485         }
3486         // ...and finally over direct superinterfaces.
3487         for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
3488             for (Method m : intf.privateGetPublicMethods()) {
3489                 // static interface methods are not inherited
3490                 if (!Modifier.isStatic(m.getModifiers())) {
3491                     pms.merge(m);
3492                 }
3493             }
3494         }
3495 
3496         res = pms.toArray();
3497         if (rd != null) {
3498             rd.publicMethods = res;
3499         }
3500         return res;
3501     }
3502 
3503 
3504     //
3505     // Helpers for fetchers of one field, method, or constructor
3506     //
3507 
3508     // This method does not copy the returned Field object!
3509     private static Field searchFields(Field[] fields, String name) {
3510         for (Field field : fields) {
3511             if (field.getName().equals(name)) {
3512                 return field;
3513             }
3514         }
3515         return null;
3516     }
3517 
3518     // Returns a "root" Field object. This Field object must NOT
3519     // be propagated to the outside world, but must instead be copied
3520     // via ReflectionFactory.copyField.
3521     private Field getField0(String name) {
3522         // Note: the intent is that the search algorithm this routine
3523         // uses be equivalent to the ordering imposed by
3524         // privateGetPublicFields(). It fetches only the declared
3525         // public fields for each class, however, to reduce the number
3526         // of Field objects which have to be created for the common
3527         // case where the field being requested is declared in the
3528         // class which is being queried.
3529         Field res;
3530         // Search declared public fields
3531         if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
3532             return res;
3533         }
3534         // Direct superinterfaces, recursively
3535         Class<?>[] interfaces = getInterfaces(/* cloneArray */ false);
3536         for (Class<?> c : interfaces) {
3537             if ((res = c.getField0(name)) != null) {
3538                 return res;
3539             }
3540         }
3541         // Direct superclass, recursively
3542         if (!isInterface()) {
3543             Class<?> c = getSuperclass();
3544             if (c != null) {
3545                 if ((res = c.getField0(name)) != null) {
3546                     return res;
3547                 }
3548             }
3549         }
3550         return null;
3551     }
3552 
3553     // This method does not copy the returned Method object!
3554     private static Method searchMethods(Method[] methods,
3555                                         String name,
3556                                         Class<?>[] parameterTypes)
3557     {
3558         ReflectionFactory fact = getReflectionFactory();
3559         Method res = null;
3560         for (Method m : methods) {
3561             if (m.getName().equals(name)
3562                 && arrayContentsEq(parameterTypes,
3563                                    fact.getExecutableSharedParameterTypes(m))
3564                 && (res == null
3565                     || (res.getReturnType() != m.getReturnType()
3566                         && res.getReturnType().isAssignableFrom(m.getReturnType()))))
3567                 res = m;
3568         }
3569         return res;
3570     }
3571 
3572     private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
3573 
3574     // Returns a "root" Method object. This Method object must NOT
3575     // be propagated to the outside world, but must instead be copied
3576     // via ReflectionFactory.copyMethod.
3577     private Method getMethod0(String name, Class<?>[] parameterTypes) {
3578         PublicMethods.MethodList res = getMethodsRecursive(
3579             name,
3580             parameterTypes == null ? EMPTY_CLASS_ARRAY : parameterTypes,
3581             /* includeStatic */ true);
3582         return res == null ? null : res.getMostSpecific();
3583     }
3584 
3585     // Returns a list of "root" Method objects. These Method objects must NOT
3586     // be propagated to the outside world, but must instead be copied
3587     // via ReflectionFactory.copyMethod.
3588     private PublicMethods.MethodList getMethodsRecursive(String name,
3589                                                          Class<?>[] parameterTypes,
3590                                                          boolean includeStatic) {
3591         // 1st check declared public methods
3592         Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);
3593         PublicMethods.MethodList res = PublicMethods.MethodList
3594             .filter(methods, name, parameterTypes, includeStatic);
3595         // if there is at least one match among declared methods, we need not
3596         // search any further as such match surely overrides matching methods
3597         // declared in superclass(es) or interface(s).
3598         if (res != null) {
3599             return res;
3600         }
3601 
3602         // if there was no match among declared methods,
3603         // we must consult the superclass (if any) recursively...
3604         Class<?> sc = getSuperclass();
3605         if (sc != null) {
3606             res = sc.getMethodsRecursive(name, parameterTypes, includeStatic);
3607         }
3608 
3609         // ...and coalesce the superclass methods with methods obtained
3610         // from directly implemented interfaces excluding static methods...
3611         for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
3612             res = PublicMethods.MethodList.merge(
3613                 res, intf.getMethodsRecursive(name, parameterTypes,
3614                                               /* includeStatic */ false));
3615         }
3616 
3617         return res;
3618     }
3619 
3620     // Returns a "root" Constructor object. This Constructor object must NOT
3621     // be propagated to the outside world, but must instead be copied
3622     // via ReflectionFactory.copyConstructor.
3623     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3624                                         int which) throws NoSuchMethodException
3625     {
3626         ReflectionFactory fact = getReflectionFactory();
3627         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3628         for (Constructor<T> constructor : constructors) {
3629             if (arrayContentsEq(parameterTypes,
3630                                 fact.getExecutableSharedParameterTypes(constructor))) {
3631                 return constructor;
3632             }
3633         }
3634         throw new NoSuchMethodException(methodToString("<init>", parameterTypes));
3635     }
3636 
3637     //
3638     // Other helpers and base implementation
3639     //
3640 
3641     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3642         if (a1 == null) {
3643             return a2 == null || a2.length == 0;
3644         }
3645 
3646         if (a2 == null) {
3647             return a1.length == 0;
3648         }
3649 
3650         if (a1.length != a2.length) {
3651             return false;
3652         }
3653 
3654         for (int i = 0; i < a1.length; i++) {
3655             if (a1[i] != a2[i]) {
3656                 return false;
3657             }
3658         }
3659 
3660         return true;
3661     }
3662 
3663     private static Field[] copyFields(Field[] arg) {
3664         Field[] out = new Field[arg.length];
3665         ReflectionFactory fact = getReflectionFactory();
3666         for (int i = 0; i < arg.length; i++) {
3667             out[i] = fact.copyField(arg[i]);
3668         }
3669         return out;
3670     }
3671 
3672     private static Method[] copyMethods(Method[] arg) {
3673         Method[] out = new Method[arg.length];
3674         ReflectionFactory fact = getReflectionFactory();
3675         for (int i = 0; i < arg.length; i++) {
3676             out[i] = fact.copyMethod(arg[i]);
3677         }
3678         return out;
3679     }
3680 
3681     private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
3682         Constructor<U>[] out = arg.clone();
3683         ReflectionFactory fact = getReflectionFactory();
3684         for (int i = 0; i < out.length; i++) {
3685             out[i] = fact.copyConstructor(out[i]);
3686         }
3687         return out;
3688     }
3689 
3690     private native Field[]       getDeclaredFields0(boolean publicOnly);
3691     private native Method[]      getDeclaredMethods0(boolean publicOnly);
3692     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3693     private native Class<?>[]    getDeclaredClasses0();
3694 
3695     /*
3696      * Returns an array containing the components of the Record attribute,
3697      * or null if the attribute is not present.
3698      *
3699      * Note that this method returns non-null array on a class with
3700      * the Record attribute even if this class is not a record.
3701      */
3702     private native RecordComponent[] getRecordComponents0();
3703     private native boolean       isRecord0();
3704 
3705     /**
3706      * Helper method to get the method name from arguments.
3707      */
3708     private String methodToString(String name, Class<?>[] argTypes) {
3709         return getName() + '.' + name +
3710                 ((argTypes == null || argTypes.length == 0) ?
3711                 "()" :
3712                 Arrays.stream(argTypes)
3713                         .map(c -> c == null ? "null" : c.getName())
3714                         .collect(Collectors.joining(",", "(", ")")));
3715     }
3716 
3717     /** use serialVersionUID from JDK 1.1 for interoperability */
3718     @java.io.Serial
3719     private static final long serialVersionUID = 3206093459760846163L;
3720 
3721 
3722     /**
3723      * Class Class is special cased within the Serialization Stream Protocol.
3724      *
3725      * A Class instance is written initially into an ObjectOutputStream in the
3726      * following format:
3727      * <pre>
3728      *      {@code TC_CLASS} ClassDescriptor
3729      *      A ClassDescriptor is a special cased serialization of
3730      *      a {@code java.io.ObjectStreamClass} instance.
3731      * </pre>
3732      * A new handle is generated for the initial time the class descriptor
3733      * is written into the stream. Future references to the class descriptor
3734      * are written as references to the initial class descriptor instance.
3735      *
3736      * @see java.io.ObjectStreamClass
3737      */
3738     @java.io.Serial
3739     private static final ObjectStreamField[] serialPersistentFields =
3740         new ObjectStreamField[0];
3741 
3742 
3743     /**
3744      * Returns the assertion status that would be assigned to this
3745      * class if it were to be initialized at the time this method is invoked.
3746      * If this class has had its assertion status set, the most recent
3747      * setting will be returned; otherwise, if any package default assertion
3748      * status pertains to this class, the most recent setting for the most
3749      * specific pertinent package default assertion status is returned;
3750      * otherwise, if this class is not a system class (i.e., it has a
3751      * class loader) its class loader's default assertion status is returned;
3752      * otherwise, the system class default assertion status is returned.
3753      *
3754      * @apiNote
3755      * Few programmers will have any need for this method; it is provided
3756      * for the benefit of the JDK itself.  (It allows a class to determine at
3757      * the time that it is initialized whether assertions should be enabled.)
3758      * Note that this method is not guaranteed to return the actual
3759      * assertion status that was (or will be) associated with the specified
3760      * class when it was (or will be) initialized.
3761      *
3762      * @return the desired assertion status of the specified class.
3763      * @see    java.lang.ClassLoader#setClassAssertionStatus
3764      * @see    java.lang.ClassLoader#setPackageAssertionStatus
3765      * @see    java.lang.ClassLoader#setDefaultAssertionStatus
3766      * @since  1.4
3767      */
3768     public boolean desiredAssertionStatus() {
3769         ClassLoader loader = classLoader;
3770         // If the loader is null this is a system class, so ask the VM
3771         if (loader == null)
3772             return desiredAssertionStatus0(this);
3773 
3774         // If the classloader has been initialized with the assertion
3775         // directives, ask it. Otherwise, ask the VM.
3776         synchronized(loader.assertionLock) {
3777             if (loader.classAssertionStatus != null) {
3778                 return loader.desiredAssertionStatus(getName());
3779             }
3780         }
3781         return desiredAssertionStatus0(this);
3782     }
3783 
3784     // Retrieves the desired assertion status of this class from the VM
3785     private static native boolean desiredAssertionStatus0(Class<?> clazz);
3786 
3787     /**
3788      * Returns true if and only if this class was declared as an enum in the
3789      * source code.
3790      *
3791      * Note that {@link java.lang.Enum} is not itself an enum class.
3792      *
3793      * Also note that if an enum constant is declared with a class body,
3794      * the class of that enum constant object is an anonymous class
3795      * and <em>not</em> the class of the declaring enum class. The
3796      * {@link Enum#getDeclaringClass} method of an enum constant can
3797      * be used to get the class of the enum class declaring the
3798      * constant.
3799      *
3800      * @return true if and only if this class was declared as an enum in the
3801      *     source code
3802      * @since 1.5
3803      * @jls 8.9.1 Enum Constants
3804      */
3805     public boolean isEnum() {
3806         // An enum must both directly extend java.lang.Enum and have
3807         // the ENUM bit set; classes for specialized enum constants
3808         // don't do the former.
3809         return (this.getModifiers() & ENUM) != 0 &&
3810         this.getSuperclass() == java.lang.Enum.class;
3811     }
3812 
3813     /**
3814      * Returns {@code true} if and only if this class is a record class.
3815      *
3816      * <p> The {@linkplain #getSuperclass() direct superclass} of a record
3817      * class is {@code java.lang.Record}. A record class is {@linkplain
3818      * Modifier#FINAL final}. A record class has (possibly zero) record
3819      * components; {@link #getRecordComponents()} returns a non-null but
3820      * possibly empty value for a record.
3821      *
3822      * <p> Note that class {@link Record} is not a record class and thus
3823      * invoking this method on class {@code Record} returns {@code false}.
3824      *
3825      * @return true if and only if this class is a record class, otherwise false
3826      * @jls 8.10 Record Classes
3827      * @since 16
3828      */
3829     public boolean isRecord() {
3830         // this superclass and final modifier check is not strictly necessary
3831         // they are intrinsified and serve as a fast-path check
3832         return getSuperclass() == java.lang.Record.class &&
3833                 (this.getModifiers() & Modifier.FINAL) != 0 &&
3834                 isRecord0();
3835     }
3836 
3837     // Fetches the factory for reflective objects
3838     @SuppressWarnings("removal")
3839     private static ReflectionFactory getReflectionFactory() {
3840         var factory = reflectionFactory;
3841         if (factory != null) {
3842             return factory;
3843         }
3844         return reflectionFactory =
3845                 java.security.AccessController.doPrivileged
3846                         (new ReflectionFactory.GetReflectionFactoryAction());
3847     }
3848     private static ReflectionFactory reflectionFactory;
3849 
3850     /**
3851      * Returns the elements of this enum class or null if this
3852      * Class object does not represent an enum class.
3853      *
3854      * @return an array containing the values comprising the enum class
3855      *     represented by this {@code Class} object in the order they're
3856      *     declared, or null if this {@code Class} object does not
3857      *     represent an enum class
3858      * @since 1.5
3859      * @jls 8.9.1 Enum Constants
3860      */
3861     public T[] getEnumConstants() {
3862         T[] values = getEnumConstantsShared();
3863         return (values != null) ? values.clone() : null;
3864     }
3865 
3866     /**
3867      * Returns the elements of this enum class or null if this
3868      * Class object does not represent an enum class;
3869      * identical to getEnumConstants except that the result is
3870      * uncloned, cached, and shared by all callers.
3871      */
3872     @SuppressWarnings("removal")
3873     T[] getEnumConstantsShared() {
3874         T[] constants = enumConstants;
3875         if (constants == null) {
3876             if (!isEnum()) return null;
3877             try {
3878                 final Method values = getMethod("values");
3879                 java.security.AccessController.doPrivileged(
3880                     new java.security.PrivilegedAction<>() {
3881                         public Void run() {
3882                                 values.setAccessible(true);
3883                                 return null;
3884                             }
3885                         });
3886                 @SuppressWarnings("unchecked")
3887                 T[] temporaryConstants = (T[])values.invoke(null);
3888                 enumConstants = constants = temporaryConstants;
3889             }
3890             // These can happen when users concoct enum-like classes
3891             // that don't comply with the enum spec.
3892             catch (InvocationTargetException | NoSuchMethodException |
3893                    IllegalAccessException ex) { return null; }
3894         }
3895         return constants;
3896     }
3897     private transient volatile T[] enumConstants;
3898 
3899     /**
3900      * Returns a map from simple name to enum constant.  This package-private
3901      * method is used internally by Enum to implement
3902      * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}
3903      * efficiently.  Note that the map is returned by this method is
3904      * created lazily on first use.  Typically it won't ever get created.
3905      */
3906     Map<String, T> enumConstantDirectory() {
3907         Map<String, T> directory = enumConstantDirectory;
3908         if (directory == null) {
3909             T[] universe = getEnumConstantsShared();
3910             if (universe == null)
3911                 throw new IllegalArgumentException(
3912                     getName() + " is not an enum class");
3913             directory = new HashMap<>((int)(universe.length / 0.75f) + 1);
3914             for (T constant : universe) {
3915                 directory.put(((Enum<?>)constant).name(), constant);
3916             }
3917             enumConstantDirectory = directory;
3918         }
3919         return directory;
3920     }
3921     private transient volatile Map<String, T> enumConstantDirectory;
3922 
3923     /**
3924      * Casts an object to the class or interface represented
3925      * by this {@code Class} object.
3926      *
3927      * @param obj the object to be cast
3928      * @return the object after casting, or null if obj is null
3929      *
3930      * @throws ClassCastException if the object is not
3931      * null and is not assignable to the type T.
3932      *
3933      * @since 1.5
3934      */
3935     @SuppressWarnings("unchecked")
3936     @IntrinsicCandidate
3937     public T cast(Object obj) {
3938         if (obj != null && !isInstance(obj))
3939             throw new ClassCastException(cannotCastMsg(obj));
3940         return (T) obj;
3941     }
3942 
3943     private String cannotCastMsg(Object obj) {
3944         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3945     }
3946 
3947     /**
3948      * Casts this {@code Class} object to represent a subclass of the class
3949      * represented by the specified class object.  Checks that the cast
3950      * is valid, and throws a {@code ClassCastException} if it is not.  If
3951      * this method succeeds, it always returns a reference to this {@code Class} object.
3952      *
3953      * <p>This method is useful when a client needs to "narrow" the type of
3954      * a {@code Class} object to pass it to an API that restricts the
3955      * {@code Class} objects that it is willing to accept.  A cast would
3956      * generate a compile-time warning, as the correctness of the cast
3957      * could not be checked at runtime (because generic types are implemented
3958      * by erasure).
3959      *
3960      * @param <U> the type to cast this {@code Class} object to
3961      * @param clazz the class of the type to cast this {@code Class} object to
3962      * @return this {@code Class} object, cast to represent a subclass of
3963      *    the specified class object.
3964      * @throws ClassCastException if this {@code Class} object does not
3965      *    represent a subclass of the specified class (here "subclass" includes
3966      *    the class itself).
3967      * @since 1.5
3968      */
3969     @SuppressWarnings("unchecked")
3970     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
3971         if (clazz.isAssignableFrom(this))
3972             return (Class<? extends U>) this;
3973         else
3974             throw new ClassCastException(this.toString());
3975     }
3976 
3977     /**
3978      * {@inheritDoc}
3979      * <p>Note that any annotation returned by this method is a
3980      * declaration annotation.
3981      *
3982      * @throws NullPointerException {@inheritDoc}
3983      * @since 1.5
3984      */
3985     @Override
3986     @SuppressWarnings("unchecked")
3987     public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
3988         Objects.requireNonNull(annotationClass);
3989 
3990         return (A) annotationData().annotations.get(annotationClass);
3991     }
3992 
3993     /**
3994      * {@inheritDoc}
3995      * @throws NullPointerException {@inheritDoc}
3996      * @since 1.5
3997      */
3998     @Override
3999     public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
4000         return GenericDeclaration.super.isAnnotationPresent(annotationClass);
4001     }
4002 
4003     /**
4004      * {@inheritDoc}
4005      * <p>Note that any annotations returned by this method are
4006      * declaration annotations.
4007      *
4008      * @throws NullPointerException {@inheritDoc}
4009      * @since 1.8
4010      */
4011     @Override
4012     public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {
4013         Objects.requireNonNull(annotationClass);
4014 
4015         AnnotationData annotationData = annotationData();
4016         return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations,
4017                                                           this,
4018                                                           annotationClass);
4019     }
4020 
4021     /**
4022      * {@inheritDoc}
4023      * <p>Note that any annotations returned by this method are
4024      * declaration annotations.
4025      *
4026      * @since 1.5
4027      */
4028     @Override
4029     public Annotation[] getAnnotations() {
4030         return AnnotationParser.toArray(annotationData().annotations);
4031     }
4032 
4033     /**
4034      * {@inheritDoc}
4035      * <p>Note that any annotation returned by this method is a
4036      * declaration annotation.
4037      *
4038      * @throws NullPointerException {@inheritDoc}
4039      * @since 1.8
4040      */
4041     @Override
4042     @SuppressWarnings("unchecked")
4043     public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
4044         Objects.requireNonNull(annotationClass);
4045 
4046         return (A) annotationData().declaredAnnotations.get(annotationClass);
4047     }
4048 
4049     /**
4050      * {@inheritDoc}
4051      * <p>Note that any annotations returned by this method are
4052      * declaration annotations.
4053      *
4054      * @throws NullPointerException {@inheritDoc}
4055      * @since 1.8
4056      */
4057     @Override
4058     public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {
4059         Objects.requireNonNull(annotationClass);
4060 
4061         return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,
4062                                                                  annotationClass);
4063     }
4064 
4065     /**
4066      * {@inheritDoc}
4067      * <p>Note that any annotations returned by this method are
4068      * declaration annotations.
4069      *
4070      * @since 1.5
4071      */
4072     @Override
4073     public Annotation[] getDeclaredAnnotations()  {
4074         return AnnotationParser.toArray(annotationData().declaredAnnotations);
4075     }
4076 
4077     // annotation data that might get invalidated when JVM TI RedefineClasses() is called
4078     private static class AnnotationData {
4079         final Map<Class<? extends Annotation>, Annotation> annotations;
4080         final Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
4081 
4082         // Value of classRedefinedCount when we created this AnnotationData instance
4083         final int redefinedCount;
4084 
4085         AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations,
4086                        Map<Class<? extends Annotation>, Annotation> declaredAnnotations,
4087                        int redefinedCount) {
4088             this.annotations = annotations;
4089             this.declaredAnnotations = declaredAnnotations;
4090             this.redefinedCount = redefinedCount;
4091         }
4092     }
4093 
4094     // Annotations cache
4095     @SuppressWarnings("UnusedDeclaration")
4096     private transient volatile AnnotationData annotationData;
4097 
4098     private AnnotationData annotationData() {
4099         while (true) { // retry loop
4100             AnnotationData annotationData = this.annotationData;
4101             int classRedefinedCount = this.classRedefinedCount;
4102             if (annotationData != null &&
4103                 annotationData.redefinedCount == classRedefinedCount) {
4104                 return annotationData;
4105             }
4106             // null or stale annotationData -> optimistically create new instance
4107             AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount);
4108             // try to install it
4109             if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) {
4110                 // successfully installed new AnnotationData
4111                 return newAnnotationData;
4112             }
4113         }
4114     }
4115 
4116     private AnnotationData createAnnotationData(int classRedefinedCount) {
4117         Map<Class<? extends Annotation>, Annotation> declaredAnnotations =
4118             AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this);
4119         Class<?> superClass = getSuperclass();
4120         Map<Class<? extends Annotation>, Annotation> annotations = null;
4121         if (superClass != null) {
4122             Map<Class<? extends Annotation>, Annotation> superAnnotations =
4123                 superClass.annotationData().annotations;
4124             for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) {
4125                 Class<? extends Annotation> annotationClass = e.getKey();
4126                 if (AnnotationType.getInstance(annotationClass).isInherited()) {
4127                     if (annotations == null) { // lazy construction
4128                         annotations = new LinkedHashMap<>((Math.max(
4129                                 declaredAnnotations.size(),
4130                                 Math.min(12, declaredAnnotations.size() + superAnnotations.size())
4131                             ) * 4 + 2) / 3
4132                         );
4133                     }
4134                     annotations.put(annotationClass, e.getValue());
4135                 }
4136             }
4137         }
4138         if (annotations == null) {
4139             // no inherited annotations -> share the Map with declaredAnnotations
4140             annotations = declaredAnnotations;
4141         } else {
4142             // at least one inherited annotation -> declared may override inherited
4143             annotations.putAll(declaredAnnotations);
4144         }
4145         return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount);
4146     }
4147 
4148     // Annotation interfaces cache their internal (AnnotationType) form
4149 
4150     @SuppressWarnings("UnusedDeclaration")
4151     private transient volatile AnnotationType annotationType;
4152 
4153     boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {
4154         return Atomic.casAnnotationType(this, oldType, newType);
4155     }
4156 
4157     AnnotationType getAnnotationType() {
4158         return annotationType;
4159     }
4160 
4161     Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() {
4162         return annotationData().declaredAnnotations;
4163     }
4164 
4165     /* Backing store of user-defined values pertaining to this class.
4166      * Maintained by the ClassValue class.
4167      */
4168     transient ClassValue.ClassValueMap classValueMap;
4169 
4170     /**
4171      * Returns an {@code AnnotatedType} object that represents the use of a
4172      * type to specify the superclass of the entity represented by this {@code
4173      * Class} object. (The <em>use</em> of type Foo to specify the superclass
4174      * in '...  extends Foo' is distinct from the <em>declaration</em> of class
4175      * Foo.)
4176      *
4177      * <p> If this {@code Class} object represents a class whose declaration
4178      * does not explicitly indicate an annotated superclass, then the return
4179      * value is an {@code AnnotatedType} object representing an element with no
4180      * annotations.
4181      *
4182      * <p> If this {@code Class} represents either the {@code Object} class, an
4183      * interface type, an array type, a primitive type, or void, the return
4184      * value is {@code null}.
4185      *
4186      * @return an object representing the superclass
4187      * @since 1.8
4188      */
4189     public AnnotatedType getAnnotatedSuperclass() {
4190         if (this == Object.class ||
4191                 isInterface() ||
4192                 isArray() ||
4193                 isPrimitive() ||
4194                 this == Void.TYPE) {
4195             return null;
4196         }
4197 
4198         return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
4199     }
4200 
4201     /**
4202      * Returns an array of {@code AnnotatedType} objects that represent the use
4203      * of types to specify superinterfaces of the entity represented by this
4204      * {@code Class} object. (The <em>use</em> of type Foo to specify a
4205      * superinterface in '... implements Foo' is distinct from the
4206      * <em>declaration</em> of interface Foo.)
4207      *
4208      * <p> If this {@code Class} object represents a class, the return value is
4209      * an array containing objects representing the uses of interface types to
4210      * specify interfaces implemented by the class. The order of the objects in
4211      * the array corresponds to the order of the interface types used in the
4212      * 'implements' clause of the declaration of this {@code Class} object.
4213      *
4214      * <p> If this {@code Class} object represents an interface, the return
4215      * value is an array containing objects representing the uses of interface
4216      * types to specify interfaces directly extended by the interface. The
4217      * order of the objects in the array corresponds to the order of the
4218      * interface types used in the 'extends' clause of the declaration of this
4219      * {@code Class} object.
4220      *
4221      * <p> If this {@code Class} object represents a class or interface whose
4222      * declaration does not explicitly indicate any annotated superinterfaces,
4223      * the return value is an array of length 0.
4224      *
4225      * <p> If this {@code Class} object represents either the {@code Object}
4226      * class, an array type, a primitive type, or void, the return value is an
4227      * array of length 0.
4228      *
4229      * @return an array representing the superinterfaces
4230      * @since 1.8
4231      */
4232     public AnnotatedType[] getAnnotatedInterfaces() {
4233          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
4234     }
4235 
4236     private native Class<?> getNestHost0();
4237 
4238     /**
4239      * Returns the nest host of the <a href=#nest>nest</a> to which the class
4240      * or interface represented by this {@code Class} object belongs.
4241      * Every class and interface belongs to exactly one nest.
4242      *
4243      * If the nest host of this class or interface has previously
4244      * been determined, then this method returns the nest host.
4245      * If the nest host of this class or interface has
4246      * not previously been determined, then this method determines the nest
4247      * host using the algorithm of JVMS 5.4.4, and returns it.
4248      *
4249      * Often, a class or interface belongs to a nest consisting only of itself,
4250      * in which case this method returns {@code this} to indicate that the class
4251      * or interface is the nest host.
4252      *
4253      * <p>If this {@code Class} object represents a primitive type, an array type,
4254      * or {@code void}, then this method returns {@code this},
4255      * indicating that the represented entity belongs to the nest consisting only of
4256      * itself, and is the nest host.
4257      *
4258      * @return the nest host of this class or interface
4259      *
4260      * @throws SecurityException
4261      *         If the returned class is not the current class, and
4262      *         if a security manager, <i>s</i>, is present and the caller's
4263      *         class loader is not the same as or an ancestor of the class
4264      *         loader for the returned class and invocation of {@link
4265      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
4266      *         denies access to the package of the returned class
4267      * @since 11
4268      * @jvms 4.7.28 The {@code NestHost} Attribute
4269      * @jvms 4.7.29 The {@code NestMembers} Attribute
4270      * @jvms 5.4.4 Access Control
4271      */
4272     @CallerSensitive
4273     public Class<?> getNestHost() {
4274         if (isPrimitive() || isArray()) {
4275             return this;
4276         }
4277 
4278         Class<?> host = getNestHost0();
4279         if (host == this) {
4280             return this;
4281         }
4282         // returning a different class requires a security check
4283         @SuppressWarnings("removal")
4284         SecurityManager sm = System.getSecurityManager();
4285         if (sm != null) {
4286             checkPackageAccess(sm,
4287                                ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
4288         }
4289         return host;
4290     }
4291 
4292     /**
4293      * Determines if the given {@code Class} is a nestmate of the
4294      * class or interface represented by this {@code Class} object.
4295      * Two classes or interfaces are nestmates
4296      * if they have the same {@linkplain #getNestHost() nest host}.
4297      *
4298      * @param c the class to check
4299      * @return {@code true} if this class and {@code c} are members of
4300      * the same nest; and {@code false} otherwise.
4301      *
4302      * @since 11
4303      */
4304     public boolean isNestmateOf(Class<?> c) {
4305         if (this == c) {
4306             return true;
4307         }
4308         if (isPrimitive() || isArray() ||
4309             c.isPrimitive() || c.isArray()) {
4310             return false;
4311         }
4312 
4313         return getNestHost() == c.getNestHost();
4314     }
4315 
4316     private native Class<?>[] getNestMembers0();
4317 
4318     /**
4319      * Returns an array containing {@code Class} objects representing all the
4320      * classes and interfaces that are members of the nest to which the class
4321      * or interface represented by this {@code Class} object belongs.
4322      *
4323      * First, this method obtains the {@linkplain #getNestHost() nest host},
4324      * {@code H}, of the nest to which the class or interface represented by
4325      * this {@code Class} object belongs. The zeroth element of the returned
4326      * array is {@code H}.
4327      *
4328      * Then, for each class or interface {@code C} which is recorded by {@code H}
4329      * as being a member of its nest, this method attempts to obtain the {@code Class}
4330      * object for {@code C} (using {@linkplain #getClassLoader() the defining class
4331      * loader} of the current {@code Class} object), and then obtains the
4332      * {@linkplain #getNestHost() nest host} of the nest to which {@code C} belongs.
4333      * The classes and interfaces which are recorded by {@code H} as being members
4334      * of its nest, and for which {@code H} can be determined as their nest host,
4335      * are indicated by subsequent elements of the returned array. The order of
4336      * such elements is unspecified. Duplicates are permitted.
4337      *
4338      * <p>If this {@code Class} object represents a primitive type, an array type,
4339      * or {@code void}, then this method returns a single-element array containing
4340      * {@code this}.
4341      *
4342      * @apiNote
4343      * The returned array includes only the nest members recorded in the {@code NestMembers}
4344      * attribute, and not any hidden classes that were added to the nest via
4345      * {@link MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
4346      * Lookup::defineHiddenClass}.
4347      *
4348      * @return an array of all classes and interfaces in the same nest as
4349      * this class or interface
4350      *
4351      * @throws SecurityException
4352      * If any returned class is not the current class, and
4353      * if a security manager, <i>s</i>, is present and the caller's
4354      * class loader is not the same as or an ancestor of the class
4355      * loader for that returned class and invocation of {@link
4356      * SecurityManager#checkPackageAccess s.checkPackageAccess()}
4357      * denies access to the package of that returned class
4358      *
4359      * @since 11
4360      * @see #getNestHost()
4361      * @jvms 4.7.28 The {@code NestHost} Attribute
4362      * @jvms 4.7.29 The {@code NestMembers} Attribute
4363      */
4364     @CallerSensitive
4365     public Class<?>[] getNestMembers() {
4366         if (isPrimitive() || isArray()) {
4367             return new Class<?>[] { this };
4368         }
4369         Class<?>[] members = getNestMembers0();
4370         // Can't actually enable this due to bootstrapping issues
4371         // assert(members.length != 1 || members[0] == this); // expected invariant from VM
4372 
4373         if (members.length > 1) {
4374             // If we return anything other than the current class we need
4375             // a security check
4376             @SuppressWarnings("removal")
4377             SecurityManager sm = System.getSecurityManager();
4378             if (sm != null) {
4379                 checkPackageAccess(sm,
4380                                    ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
4381             }
4382         }
4383         return members;
4384     }
4385 
4386     /**
4387      * Returns the descriptor string of the entity (class, interface, array class,
4388      * primitive type, or {@code void}) represented by this {@code Class} object.
4389      *
4390      * <p> If this {@code Class} object represents a class or interface,
4391      * not an array class, then:
4392      * <ul>
4393      * <li> If the class or interface is not {@linkplain Class#isHidden() hidden},
4394      *      then the result is a field descriptor (JVMS {@jvms 4.3.2})
4395      *      for the class or interface. Calling
4396      *      {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor}
4397      *      with the result descriptor string produces a {@link ClassDesc ClassDesc}
4398      *      describing this class or interface.
4399      * <li> If the class or interface is {@linkplain Class#isHidden() hidden},
4400      *      then the result is a string of the form:
4401      *      <blockquote>
4402      *      {@code "L" +} <em>N</em> {@code + "." + <suffix> + ";"}
4403      *      </blockquote>
4404      *      where <em>N</em> is the <a href="ClassLoader.html#binary-name">binary name</a>
4405      *      encoded in internal form indicated by the {@code class} file passed to
4406      *      {@link MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
4407      *      Lookup::defineHiddenClass}, and {@code <suffix>} is an unqualified name.
4408      *      A hidden class or interface has no {@linkplain ClassDesc nominal descriptor}.
4409      *      The result string is not a type descriptor.
4410      * </ul>
4411      *
4412      * <p> If this {@code Class} object represents an array class, then
4413      * the result is a string consisting of one or more '{@code [}' characters
4414      * representing the depth of the array nesting, followed by the
4415      * descriptor string of the element type.
4416      * <ul>
4417      * <li> If the element type is not a {@linkplain Class#isHidden() hidden} class
4418      * or interface, then this array class can be described nominally.
4419      * Calling {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor}
4420      * with the result descriptor string produces a {@link ClassDesc ClassDesc}
4421      * describing this array class.
4422      * <li> If the element type is a {@linkplain Class#isHidden() hidden} class or
4423      * interface, then this array class cannot be described nominally.
4424      * The result string is not a type descriptor.
4425      * </ul>
4426      *
4427      * <p> If this {@code Class} object represents a primitive type or
4428      * {@code void}, then the result is a field descriptor string which
4429      * is a one-letter code corresponding to a primitive type or {@code void}
4430      * ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}).
4431      *
4432      * @apiNote
4433      * This is not a strict inverse of {@link #forName};
4434      * distinct classes which share a common name but have different class loaders
4435      * will have identical descriptor strings.
4436      *
4437      * @return the descriptor string for this {@code Class} object
4438      * @jvms 4.3.2 Field Descriptors
4439      * @since 12
4440      */
4441     @Override
4442     public String descriptorString() {
4443         if (isPrimitive())
4444             return Wrapper.forPrimitiveType(this).basicTypeString();
4445 
4446         if (isArray()) {
4447             return "[" + componentType.descriptorString();
4448         } else if (isHidden()) {
4449             String name = getName();
4450             int index = name.indexOf('/');
4451             return new StringBuilder(name.length() + 2)
4452                     .append('L')
4453                     .append(name.substring(0, index).replace('.', '/'))
4454                     .append('.')
4455                     .append(name, index + 1, name.length())
4456                     .append(';')
4457                     .toString();
4458         } else {
4459             String name = getName().replace('.', '/');
4460             return new StringBuilder(name.length() + 2)
4461                     .append('L')
4462                     .append(name)
4463                     .append(';')
4464                     .toString();
4465         }
4466     }
4467 
4468     /**
4469      * Returns the component type of this {@code Class}, if it describes
4470      * an array type, or {@code null} otherwise.
4471      *
4472      * @implSpec
4473      * Equivalent to {@link Class#getComponentType()}.
4474      *
4475      * @return a {@code Class} describing the component type, or {@code null}
4476      * if this {@code Class} does not describe an array type
4477      * @since 12
4478      */
4479     @Override
4480     public Class<?> componentType() {
4481         return isArray() ? componentType : null;
4482     }
4483 
4484     /**
4485      * Returns a {@code Class} for an array type whose component type
4486      * is described by this {@linkplain Class}.
4487      *
4488      * @throws UnsupportedOperationException if this component type is {@linkplain
4489      *         Void#TYPE void} or if the number of dimensions of the resulting array
4490      *         type would exceed 255.
4491      * @return a {@code Class} describing the array type
4492      * @jvms 4.3.2 Field Descriptors
4493      * @jvms 4.4.1 The {@code CONSTANT_Class_info} Structure
4494      * @since 12
4495      */
4496     @Override
4497     public Class<?> arrayType() {
4498         try {
4499             return Array.newInstance(this, 0).getClass();
4500         } catch (IllegalArgumentException iae) {
4501             throw new UnsupportedOperationException(iae);
4502         }
4503     }
4504 
4505     /**
4506      * Returns a nominal descriptor for this instance, if one can be
4507      * constructed, or an empty {@link Optional} if one cannot be.
4508      *
4509      * @return An {@link Optional} containing the resulting nominal descriptor,
4510      * or an empty {@link Optional} if one cannot be constructed.
4511      * @since 12
4512      */
4513     @Override
4514     public Optional<ClassDesc> describeConstable() {
4515         Class<?> c = isArray() ? elementType() : this;
4516         return c.isHidden() ? Optional.empty()
4517                             : Optional.of(ClassDesc.ofDescriptor(descriptorString()));
4518    }
4519 
4520     /**
4521      * Returns {@code true} if and only if the underlying class is a hidden class.
4522      *
4523      * @return {@code true} if and only if this class is a hidden class.
4524      *
4525      * @since 15
4526      * @see MethodHandles.Lookup#defineHiddenClass
4527      */
4528     @IntrinsicCandidate
4529     public native boolean isHidden();
4530 
4531     /**
4532      * Returns an array containing {@code Class} objects representing the
4533      * direct subinterfaces or subclasses permitted to extend or
4534      * implement this class or interface if it is sealed.  The order of such elements
4535      * is unspecified. The array is empty if this sealed class or interface has no
4536      * permitted subclass. If this {@code Class} object represents a primitive type,
4537      * {@code void}, an array type, or a class or interface that is not sealed,
4538      * that is {@link #isSealed()} returns {@code false}, then this method returns {@code null}.
4539      * Conversely, if {@link #isSealed()} returns {@code true}, then this method
4540      * returns a non-null value.
4541      *
4542      * For each class or interface {@code C} which is recorded as a permitted
4543      * direct subinterface or subclass of this class or interface,
4544      * this method attempts to obtain the {@code Class}
4545      * object for {@code C} (using {@linkplain #getClassLoader() the defining class
4546      * loader} of the current {@code Class} object).
4547      * The {@code Class} objects which can be obtained and which are direct
4548      * subinterfaces or subclasses of this class or interface,
4549      * are indicated by elements of the returned array. If a {@code Class} object
4550      * cannot be obtained, it is silently ignored, and not included in the result
4551      * array.
4552      *
4553      * @return an array of {@code Class} objects of the permitted subclasses of this class or interface,
4554      *         or {@code null} if this class or interface is not sealed.
4555      *
4556      * @throws SecurityException
4557      *         If a security manager, <i>s</i>, is present and the caller's
4558      *         class loader is not the same as or an ancestor of the class
4559      *         loader for that returned class and invocation of {@link
4560      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
4561      *         denies access to the package of any class in the returned array.
4562      *
4563      * @jls 8.1 Class Declarations
4564      * @jls 9.1 Interface Declarations
4565      * @since 17
4566      */
4567     @CallerSensitive
4568     public Class<?>[] getPermittedSubclasses() {
4569         Class<?>[] subClasses;
4570         if (isArray() || isPrimitive() || (subClasses = getPermittedSubclasses0()) == null) {
4571             return null;
4572         }
4573         if (subClasses.length > 0) {
4574             if (Arrays.stream(subClasses).anyMatch(c -> !isDirectSubType(c))) {
4575                 subClasses = Arrays.stream(subClasses)
4576                                    .filter(this::isDirectSubType)
4577                                    .toArray(s -> new Class<?>[s]);
4578             }
4579         }
4580         if (subClasses.length > 0) {
4581             // If we return some classes we need a security check:
4582             @SuppressWarnings("removal")
4583             SecurityManager sm = System.getSecurityManager();
4584             if (sm != null) {
4585                 checkPackageAccessForPermittedSubclasses(sm,
4586                                              ClassLoader.getClassLoader(Reflection.getCallerClass()),
4587                                              subClasses);
4588             }
4589         }
4590         return subClasses;
4591     }
4592 
4593     private boolean isDirectSubType(Class<?> c) {
4594         if (isInterface()) {
4595             for (Class<?> i : c.getInterfaces(/* cloneArray */ false)) {
4596                 if (i == this) {
4597                     return true;
4598                 }
4599             }
4600         } else {
4601             return c.getSuperclass() == this;
4602         }
4603         return false;
4604     }
4605 
4606     /**
4607      * Returns {@code true} if and only if this {@code Class} object represents
4608      * a sealed class or interface. If this {@code Class} object represents a
4609      * primitive type, {@code void}, or an array type, this method returns
4610      * {@code false}. A sealed class or interface has (possibly zero) permitted
4611      * subclasses; {@link #getPermittedSubclasses()} returns a non-null but
4612      * possibly empty value for a sealed class or interface.
4613      *
4614      * @return {@code true} if and only if this {@code Class} object represents
4615      * a sealed class or interface.
4616      *
4617      * @jls 8.1 Class Declarations
4618      * @jls 9.1 Interface Declarations
4619      * @since 17
4620      */
4621     public boolean isSealed() {
4622         if (isArray() || isPrimitive()) {
4623             return false;
4624         }
4625         return getPermittedSubclasses() != null;
4626     }
4627 
4628     private native Class<?>[] getPermittedSubclasses0();
4629 }