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