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