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