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