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