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