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