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