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