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