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