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