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