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