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