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