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