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