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