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