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