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