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