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