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