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