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