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