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