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