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