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