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