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