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