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