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