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