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