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