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