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.CallerSensitiveAdapter;
  77 import jdk.internal.reflect.ConstantPool;
  78 import jdk.internal.reflect.Reflection;
  79 import jdk.internal.reflect.ReflectionFactory;
  80 import jdk.internal.vm.annotation.ForceInline;
  81 import jdk.internal.vm.annotation.IntrinsicCandidate;
  82 import sun.invoke.util.Wrapper;
  83 import sun.reflect.generics.factory.CoreReflectionFactory;
  84 import sun.reflect.generics.factory.GenericsFactory;
  85 import sun.reflect.generics.repository.ClassRepository;
  86 import sun.reflect.generics.repository.MethodRepository;
  87 import sun.reflect.generics.repository.ConstructorRepository;
  88 import sun.reflect.generics.scope.ClassScope;
  89 import sun.security.util.SecurityConstants;
  90 import sun.reflect.annotation.*;
  91 import sun.reflect.misc.ReflectUtil;
  92 
  93 /**
  94  * Instances of the class {@code Class} represent classes and
  95  * interfaces in a running Java application. An enum class and a record
  96  * class are kinds of class; an annotation interface is a kind of
  97  * interface. Every array also belongs to a class that is reflected as
  98  * a {@code Class} object that is shared by all arrays with the same
  99  * element type and number of dimensions.  The primitive Java types
 100  * ({@code boolean}, {@code byte}, {@code char}, {@code short}, {@code
 101  * int}, {@code long}, {@code float}, and {@code double}), and the
 102  * keyword {@code void} are also represented as {@code Class} objects.
 103  *
 104  * <p> {@code Class} has no public constructor. Instead a {@code Class}
 105  * object is constructed automatically by the Java Virtual Machine when
 106  * a class is derived from the bytes of a {@code class} file through
 107  * the invocation of one of the following methods:
 108  * <ul>
 109  * <li> {@link ClassLoader#defineClass(String, byte[], int, int) ClassLoader::defineClass}
 110  * <li> {@link java.lang.invoke.MethodHandles.Lookup#defineClass(byte[])
 111  *      java.lang.invoke.MethodHandles.Lookup::defineClass}
 112  * <li> {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
 113  *      java.lang.invoke.MethodHandles.Lookup::defineHiddenClass}
 114  * </ul>
 115  *
 116  * <p> The methods of class {@code Class} expose many characteristics of a
 117  * class or interface. Most characteristics are derived from the {@code class}
 118  * file that the class loader passed to the Java Virtual Machine or
 119  * from the {@code class} file passed to {@code Lookup::defineClass}
 120  * or {@code Lookup::defineHiddenClass}.
 121  * A few characteristics are determined by the class loading environment
 122  * at run time, such as the module returned by {@link #getModule() getModule()}.
 123  *
 124  * <p> The following example uses a {@code Class} object to print the
 125  * class name of an object:
 126  *
 127  * <blockquote><pre>
 128  *     void printClassName(Object obj) {
 129  *         System.out.println("The class of " + obj +
 130  *                            " is " + obj.getClass().getName());
 131  *     }
 132  * </pre></blockquote>
 133  *
 134  * It is also possible to get the {@code Class} object for a named
 135  * class or interface (or for {@code void}) using a <i>class literal</i>.
 136  * For example:
 137  *
 138  * <blockquote>
 139  *     {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
 140  * </blockquote>
 141  *
 142  * <p> Some methods of class {@code Class} expose whether the declaration of
 143  * a class or interface in Java source code was <em>enclosed</em> within
 144  * another declaration. Other methods describe how a class or interface
 145  * is situated in a <em>nest</em>. A <a id="nest">nest</a> is a set of
 146  * classes and interfaces, in the same run-time package, that
 147  * allow mutual access to their {@code private} members.
 148  * The classes and interfaces are known as <em>nestmates</em>.
 149  * One nestmate acts as the
 150  * <em>nest host</em>, and enumerates the other nestmates which
 151  * belong to the nest; each of them in turn records it as the nest host.
 152  * The classes and interfaces which belong to a nest, including its host, are
 153  * determined when
 154  * {@code class} files are generated, for example, a Java compiler
 155  * will typically record a top-level class as the host of a nest where the
 156  * other members are the classes and interfaces whose declarations are
 157  * enclosed within the top-level class declaration.
 158  *
 159  * <p> A class or interface created by the invocation of
 160  * {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
 161  * Lookup::defineHiddenClass} is a {@linkplain Class#isHidden() <em>hidden</em>}
 162  * class or interface.
 163  * All kinds of class, including enum classes and record classes, may be
 164  * hidden classes; all kinds of interface, including annotation interfaces,
 165  * may be hidden interfaces.
 166  *
 167  * The {@linkplain #getName() name of a hidden class or interface} is
 168  * not a <a href="ClassLoader.html#binary-name">binary name</a>,
 169  * which means the following:
 170  * <ul>
 171  * <li>A hidden class or interface cannot be referenced by the constant pools
 172  *     of other classes and interfaces.
 173  * <li>A hidden class or interface cannot be described in
 174  *     {@linkplain java.lang.constant.ConstantDesc <em>nominal form</em>} by
 175  *     {@link #describeConstable() Class::describeConstable},
 176  *     {@link ClassDesc#of(String) ClassDesc::of}, or
 177  *     {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor}.
 178  * <li>A hidden class or interface cannot be discovered by {@link #forName Class::forName}
 179  *     or {@link ClassLoader#loadClass(String, boolean) ClassLoader::loadClass}.
 180  * </ul>
 181  *
 182  * A hidden class or interface is never an array class, but may be
 183  * the element type of an array. In all other respects, the fact that
 184  * a class or interface is hidden has no bearing on the characteristics
 185  * exposed by the methods of class {@code Class}.
 186  *
 187  * @param <T> the type of the class modeled by this {@code Class}
 188  * object.  For example, the type of {@code String.class} is {@code
 189  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
 190  * unknown.
 191  *
 192  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
 193  * @since   1.0
 194  * @jls 15.8.2 Class Literals
 195  */
 196 public final class Class<T> implements java.io.Serializable,
 197                               GenericDeclaration,
 198                               Type,
 199                               AnnotatedElement,
 200                               TypeDescriptor.OfField<Class<?>>,
 201                               Constable {
 202     private static final int ANNOTATION = 0x00002000;
 203     private static final int ENUM       = 0x00004000;
 204     private static final int SYNTHETIC  = 0x00001000;
 205     private static final int PRIMITIVE_CLASS = 0x00000100;
 206 
 207     private static native void registerNatives();
 208     static {
 209         registerNatives();
 210     }
 211 
 212     /*
 213      * Private constructor. Only the Java Virtual Machine creates Class objects.
 214      * This constructor is not used and prevents the default constructor being
 215      * generated.
 216      */
 217     private Class(ClassLoader loader, Class<?> arrayComponentType) {
 218         // Initialize final field for classLoader.  The initialization value of non-null
 219         // prevents future JIT optimizations from assuming this final field is null.
 220         classLoader = loader;
 221         componentType = arrayComponentType;
 222     }
 223 
 224     /**
 225      * Converts the object to a string. The string representation is the
 226      * string "class" or "interface", followed by a space, and then by the
 227      * name of the class in the format returned by {@code getName}.
 228      * If this {@code Class} object represents a primitive type,
 229      * this method returns the name of the primitive type.  If
 230      * this {@code Class} object represents void this method returns
 231      * "void". If this {@code Class} object represents an array type,
 232      * this method returns "class " followed by {@code getName}.
 233      *
 234      * @return a string representation of this {@code Class} object.
 235      */
 236     public String toString() {
 237         String s = isPrimitive() ? "" : "class ";
 238         if (isInterface()) {
 239             s = "interface ";
 240         }
 241         if (isPrimitiveClass()) {
 242             s = "primitive ";
 243         }
 244         // Avoid invokedynamic based String concat, might be not available
 245         s = s.concat(getName());
 246         if (isPrimitiveClass() && isPrimaryType()) {
 247             s = s.concat(".ref");
 248         }
 249         return s;
 250     }
 251 
 252     /**
 253      * Returns a string describing this {@code Class}, including
 254      * information about modifiers and type parameters.
 255      *
 256      * The string is formatted as a list of type modifiers, if any,
 257      * followed by the kind of type (empty string for primitive types
 258      * and {@code class}, {@code enum}, {@code interface},
 259      * {@code @interface}, or {@code record} as appropriate), followed
 260      * by the type's name, followed by an angle-bracketed
 261      * comma-separated list of the type's type parameters, if any,
 262      * including informative bounds on the type parameters, if any.
 263      *
 264      * A space is used to separate modifiers from one another and to
 265      * separate any modifiers from the kind of type. The modifiers
 266      * occur in canonical order. If there are no type parameters, the
 267      * type parameter list is elided.
 268      *
 269      * For an array type, the string starts with the type name,
 270      * followed by an angle-bracketed comma-separated list of the
 271      * type's type parameters, if any, followed by a sequence of
 272      * {@code []} characters, one set of brackets per dimension of
 273      * the array.
 274      *
 275      * <p>Note that since information about the runtime representation
 276      * of a type is being generated, modifiers not present on the
 277      * originating source code or illegal on the originating source
 278      * code may be present.
 279      *
 280      * @return a string describing this {@code Class}, including
 281      * information about modifiers and type parameters
 282      *
 283      * @since 1.8
 284      */
 285     public String toGenericString() {
 286         if (isPrimitive()) {
 287             return toString();
 288         } else {
 289             StringBuilder sb = new StringBuilder();
 290             Class<?> component = this;
 291             int arrayDepth = 0;
 292 
 293             if (isArray()) {
 294                 do {
 295                     arrayDepth++;
 296                     component = component.getComponentType();
 297                 } while (component.isArray());
 298                 sb.append(component.getName());
 299             } else {
 300                 // Class modifiers are a superset of interface modifiers
 301                 int modifiers = getModifiers() & Modifier.classModifiers();
 302                 if (modifiers != 0) {
 303                     sb.append(Modifier.toString(modifiers));
 304                     sb.append(' ');
 305                 }
 306 
 307                 if (isAnnotation()) {
 308                     sb.append('@');
 309                 }
 310                 if (isPrimitiveClass()) {
 311                     sb.append("primitive ");
 312                 }
 313                 if (isInterface()) { // Note: all annotation interfaces are interfaces
 314                     sb.append("interface");
 315                 } else {
 316                     if (isEnum())
 317                         sb.append("enum");
 318                     else if (isRecord())
 319                         sb.append("record");
 320                     else
 321                         sb.append("class");
 322                 }
 323                 sb.append(' ');
 324                 sb.append(getName());
 325             }
 326 
 327             TypeVariable<?>[] typeparms = component.getTypeParameters();
 328             if (typeparms.length > 0) {
 329                 sb.append(Arrays.stream(typeparms)
 330                           .map(Class::typeVarBounds)
 331                           .collect(Collectors.joining(",", "<", ">")));
 332             }
 333 
 334             if (arrayDepth > 0) sb.append("[]".repeat(arrayDepth));
 335 
 336             return sb.toString();
 337         }
 338     }
 339 
 340     static String typeVarBounds(TypeVariable<?> typeVar) {
 341         Type[] bounds = typeVar.getBounds();
 342         if (bounds.length == 1 && bounds[0].equals(Object.class)) {
 343             return typeVar.getName();
 344         } else {
 345             return typeVar.getName() + " extends " +
 346                 Arrays.stream(bounds)
 347                 .map(Type::getTypeName)
 348                 .collect(Collectors.joining(" & "));
 349         }
 350     }
 351 
 352     /**
 353      * Returns the {@code Class} object associated with the class or
 354      * interface with the given string name.  Invoking this method is
 355      * equivalent to:
 356      *
 357      * <blockquote>
 358      *  {@code Class.forName(className, true, currentLoader)}
 359      * </blockquote>
 360      *
 361      * where {@code currentLoader} denotes the defining class loader of
 362      * the current class.
 363      *
 364      * <p> For example, the following code fragment returns the
 365      * runtime {@code Class} descriptor for the class named
 366      * {@code java.lang.Thread}:
 367      *
 368      * <blockquote>
 369      *   {@code Class t = Class.forName("java.lang.Thread")}
 370      * </blockquote>
 371      * <p>
 372      * A call to {@code forName("X")} causes the class named
 373      * {@code X} to be initialized.
 374      *
 375      * @param      className   the fully qualified name of the desired class.
 376      * @return     the {@code Class} object for the class with the
 377      *             specified name.
 378      * @throws    LinkageError if the linkage fails
 379      * @throws    ExceptionInInitializerError if the initialization provoked
 380      *            by this method fails
 381      * @throws    ClassNotFoundException if the class cannot be located
 382      *
 383      * @jls 12.2 Loading of Classes and Interfaces
 384      * @jls 12.3 Linking of Classes and Interfaces
 385      * @jls 12.4 Initialization of Classes and Interfaces
 386      */
 387     @CallerSensitive
 388     public static Class<?> forName(String className)
 389                 throws ClassNotFoundException {
 390         Class<?> caller = Reflection.getCallerClass();
 391         return forName(className, caller);
 392     }
 393 
 394     // Caller-sensitive adapter method for reflective invocation
 395     @CallerSensitiveAdapter
 396     private static Class<?> forName(String className, Class<?> caller)
 397             throws ClassNotFoundException {
 398         return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
 399     }
 400 
 401     /**
 402      * Returns the {@code Class} object associated with the class or
 403      * interface with the given string name, using the given class loader.
 404      * Given the fully qualified name for a class or interface (in the same
 405      * format returned by {@code getName}) this method attempts to
 406      * locate and load the class or interface.  The specified class
 407      * loader is used to load the class or interface.  If the parameter
 408      * {@code loader} is null, the class is loaded through the bootstrap
 409      * class loader.  The class is initialized only if the
 410      * {@code initialize} parameter is {@code true} and if it has
 411      * not been initialized earlier.
 412      *
 413      * <p> If {@code name} denotes a primitive type or void, an attempt
 414      * will be made to locate a user-defined class in the unnamed package whose
 415      * name is {@code name}. Therefore, this method cannot be used to
 416      * obtain any of the {@code Class} objects representing primitive
 417      * types or void.
 418      *
 419      * <p> If {@code name} denotes an array class, the component type of
 420      * the array class is loaded but not initialized.
 421      *
 422      * <p> For example, in an instance method the expression:
 423      *
 424      * <blockquote>
 425      *  {@code Class.forName("Foo")}
 426      * </blockquote>
 427      *
 428      * is equivalent to:
 429      *
 430      * <blockquote>
 431      *  {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
 432      * </blockquote>
 433      *
 434      * Note that this method throws errors related to loading, linking
 435      * or initializing as specified in Sections {@jls 12.2}, {@jls
 436      * 12.3}, and {@jls 12.4} of <cite>The Java Language
 437      * Specification</cite>.
 438      * Note that this method does not check whether the requested class
 439      * is accessible to its caller.
 440      *
 441      * @param name       fully qualified name of the desired class
 442 
 443      * @param initialize if {@code true} the class will be initialized
 444      *                   (which implies linking). See Section {@jls
 445      *                   12.4} of <cite>The Java Language
 446      *                   Specification</cite>.
 447      * @param loader     class loader from which the class must be loaded
 448      * @return           class object representing the desired class
 449      *
 450      * @throws    LinkageError if the linkage fails
 451      * @throws    ExceptionInInitializerError if the initialization provoked
 452      *            by this method fails
 453      * @throws    ClassNotFoundException if the class cannot be located by
 454      *            the specified class loader
 455      * @throws    SecurityException
 456      *            if a security manager is present, and the {@code loader} is
 457      *            {@code null}, and the caller's class loader is not
 458      *            {@code null}, and the caller does not have the
 459      *            {@link RuntimePermission}{@code ("getClassLoader")}
 460      *
 461      * @see       java.lang.Class#forName(String)
 462      * @see       java.lang.ClassLoader
 463      *
 464      * @jls 12.2 Loading of Classes and Interfaces
 465      * @jls 12.3 Linking of Classes and Interfaces
 466      * @jls 12.4 Initialization of Classes and Interfaces
 467      * @since     1.2
 468      */
 469     @CallerSensitive
 470     public static Class<?> forName(String name, boolean initialize,
 471                                    ClassLoader loader)
 472         throws ClassNotFoundException
 473     {
 474         Class<?> caller = null;
 475         @SuppressWarnings("removal")
 476         SecurityManager sm = System.getSecurityManager();
 477         if (sm != null) {
 478             // Reflective call to get caller class is only needed if a security manager
 479             // is present.  Avoid the overhead of making this call otherwise.
 480             caller = Reflection.getCallerClass();
 481         }
 482         return forName(name, initialize, loader, caller);
 483     }
 484 
 485     // Caller-sensitive adapter method for reflective invocation
 486     @CallerSensitiveAdapter
 487     private static Class<?> forName(String name, boolean initialize, ClassLoader loader, Class<?> caller)
 488             throws ClassNotFoundException
 489     {
 490         @SuppressWarnings("removal")
 491         SecurityManager sm = System.getSecurityManager();
 492         if (sm != null) {
 493             // Reflective call to get caller class is only needed if a security manager
 494             // is present.  Avoid the overhead of making this call otherwise.
 495             if (loader == null) {
 496                 ClassLoader ccl = ClassLoader.getClassLoader(caller);
 497                 if (ccl != null) {
 498                     sm.checkPermission(
 499                             SecurityConstants.GET_CLASSLOADER_PERMISSION);
 500                 }
 501             }
 502         }
 503         return forName0(name, initialize, loader, caller);
 504     }
 505 
 506     /** Called after security check for system loader access checks have been made. */
 507     private static native Class<?> forName0(String name, boolean initialize,
 508                                     ClassLoader loader,
 509                                     Class<?> caller)
 510         throws ClassNotFoundException;
 511 
 512 
 513     /**
 514      * Returns the {@code Class} with the given <a href="ClassLoader.html#binary-name">
 515      * binary name</a> in the given module.
 516      *
 517      * <p> This method attempts to locate and load the class or interface.
 518      * It does not link the class, and does not run the class initializer.
 519      * If the class is not found, this method returns {@code null}. </p>
 520      *
 521      * <p> If the class loader of the given module defines other modules and
 522      * the given name is a class defined in a different module, this method
 523      * returns {@code null} after the class is loaded. </p>
 524      *
 525      * <p> This method does not check whether the requested class is
 526      * accessible to its caller. </p>
 527      *
 528      * @apiNote
 529      * This method returns {@code null} on failure rather than
 530      * throwing a {@link ClassNotFoundException}, as is done by
 531      * the {@link #forName(String, boolean, ClassLoader)} method.
 532      * The security check is a stack-based permission check if the caller
 533      * loads a class in another module.
 534      *
 535      * @param  module   A module
 536      * @param  name     The <a href="ClassLoader.html#binary-name">binary name</a>
 537      *                  of the class
 538      * @return {@code Class} object of the given name defined in the given module;
 539      *         {@code null} if not found.
 540      *
 541      * @throws NullPointerException if the given module or name is {@code null}
 542      *
 543      * @throws LinkageError if the linkage fails
 544      *
 545      * @throws SecurityException
 546      *         <ul>
 547      *         <li> if the caller is not the specified module and
 548      *         {@code RuntimePermission("getClassLoader")} permission is denied; or</li>
 549      *         <li> access to the module content is denied. For example,
 550      *         permission check will be performed when a class loader calls
 551      *         {@link ModuleReader#open(String)} to read the bytes of a class file
 552      *         in a module.</li>
 553      *         </ul>
 554      *
 555      * @jls 12.2 Loading of Classes and Interfaces
 556      * @jls 12.3 Linking of Classes and Interfaces
 557      * @since 9
 558      */
 559     @SuppressWarnings("removal")
 560     @CallerSensitive
 561     public static Class<?> forName(Module module, String name) {
 562         Class<?> caller = null;
 563         SecurityManager sm = System.getSecurityManager();
 564         if (sm != null) {
 565             caller = Reflection.getCallerClass();
 566         }
 567         return forName(module, name, caller);
 568     }
 569 
 570     // Caller-sensitive adapter method for reflective invocation
 571     @SuppressWarnings("removal")
 572     @CallerSensitiveAdapter
 573     private static Class<?> forName(Module module, String name, Class<?> caller) {
 574         Objects.requireNonNull(module);
 575         Objects.requireNonNull(name);
 576 
 577         ClassLoader cl;
 578         SecurityManager sm = System.getSecurityManager();
 579         if (sm != null) {
 580             if (caller != null && caller.getModule() != module) {
 581                 // if caller is null, Class.forName is the last java frame on the stack.
 582                 // java.base has all permissions
 583                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 584             }
 585             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
 586             cl = AccessController.doPrivileged(pa);
 587         } else {
 588             cl = module.getClassLoader();
 589         }
 590 
 591         if (cl != null) {
 592             return cl.loadClass(module, name);
 593         } else {
 594             return BootLoader.loadClass(module, name);
 595         }
 596     }
 597 
 598     // set by VM if this class is an exotic type such as primitive class
 599     // otherwise, these two fields are null
 600     private transient Class<T> primaryType;
 601     private transient Class<T> secondaryType;
 602 
 603     /**
 604      * Returns {@code true} if this class is a primitive class.
 605      * <p>
 606      * Each primitive class has a {@linkplain #isPrimaryType() primary type}
 607      * representing the <em>primitive reference type</em> and a
 608      * {@linkplain #isValueType() secondary type} representing
 609      * the <em>primitive value type</em>.  The primitive reference type
 610      * and primitive value type can be obtained by calling the
 611      * {@link #asPrimaryType()} and {@link #asValueType} method
 612      * of a primitive class respectively.
 613      *
 614      * @return {@code true} if this class is a primitive class, otherwise {@code false}
 615      * @see #asPrimaryType()
 616      * @see #asValueType()
 617      * @since Valhalla
 618      */
 619     public boolean isPrimitiveClass() {
 620         return (this.getModifiers() & PRIMITIVE_CLASS) != 0;
 621     }
 622 
 623     /**
 624      * Returns a {@code Class} object representing the primary type
 625      * of this class or interface.
 626      * <p>
 627      * If this {@code Class} object represents a primitive type or an array type,
 628      * then this method returns this class.
 629      * <p>
 630      * If this {@code Class} object represents a {@linkplain #isPrimitiveClass()
 631      * primitive class}, then this method returns the <em>primitive reference type</em>
 632      * type of this primitive class.
 633      * <p>
 634      * Otherwise, this {@code Class} object represents a non-primitive class or interface
 635      * and this method returns this class.
 636      *
 637      * @return the {@code Class} representing the primary type of
 638      *         this class or interface
 639      * @since Valhalla
 640      */
 641     @IntrinsicCandidate
 642     public Class<?> asPrimaryType() {
 643         return isPrimitiveClass() ? primaryType : this;
 644     }
 645 
 646     /**
 647      * Returns a {@code Class} object representing the <em>primitive value type</em>
 648      * of this class if this class is a {@linkplain #isPrimitiveClass() primitive class}.
 649      *
 650      * @apiNote Alternatively, this method returns null if this class is not
 651      *          a primitive class rather than throwing UOE.
 652      *
 653      * @return the {@code Class} representing the {@linkplain #isValueType()
 654      * primitive value type} of this class if this class is a primitive class
 655      * @throws UnsupportedOperationException if this class or interface
 656      *         is not a primitive class
 657      * @since Valhalla
 658      */
 659     @IntrinsicCandidate
 660     public Class<?> asValueType() {
 661         if (isPrimitiveClass())
 662             return secondaryType;
 663 
 664         throw new UnsupportedOperationException(this.getName().concat(" is not a primitive class"));
 665     }
 666 
 667     /**
 668      * Returns {@code true} if this {@code Class} object represents the primary type
 669      * of this class or interface.
 670      * <p>
 671      * If this {@code Class} object represents a primitive type or an array type,
 672      * then this method returns {@code true}.
 673      * <p>
 674      * If this {@code Class} object represents a {@linkplain #isPrimitiveClass()
 675      * primitive}, then this method returns {@code true} if this {@code Class}
 676      * object represents a primitive reference type, or returns {@code false}
 677      * if this {@code Class} object represents a primitive value type.
 678      * <p>
 679      * If this {@code Class} object represents a non-primitive class or interface,
 680      * then this method returns {@code true}.
 681      *
 682      * @return {@code true} if this {@code Class} object represents
 683      * the primary type of this class or interface
 684      * @since Valhalla
 685      */
 686     public boolean isPrimaryType() {
 687         if (isPrimitiveClass()) {
 688             return this == primaryType;
 689         }
 690         return true;
 691     }
 692 
 693     /**
 694      * Returns {@code true} if this {@code Class} object represents
 695      * a {@linkplain #isPrimitiveClass() primitive} value type.
 696      *
 697      * @return {@code true} if this {@code Class} object represents the
 698      * value type of a primitive class
 699      * @since Valhalla
 700      */
 701     public boolean isValueType() {
 702         return isPrimitiveClass() && this == secondaryType;
 703     }
 704 
 705     /**
 706      * Creates a new instance of the class represented by this {@code Class}
 707      * object.  The class is instantiated as if by a {@code new}
 708      * expression with an empty argument list.  The class is initialized if it
 709      * has not already been initialized.
 710      *
 711      * @deprecated This method propagates any exception thrown by the
 712      * nullary constructor, including a checked exception.  Use of
 713      * this method effectively bypasses the compile-time exception
 714      * checking that would otherwise be performed by the compiler.
 715      * The {@link
 716      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
 717      * Constructor.newInstance} method avoids this problem by wrapping
 718      * any exception thrown by the constructor in a (checked) {@link
 719      * java.lang.reflect.InvocationTargetException}.
 720      *
 721      * <p>The call
 722      *
 723      * <pre>{@code
 724      * clazz.newInstance()
 725      * }</pre>
 726      *
 727      * can be replaced by
 728      *
 729      * <pre>{@code
 730      * clazz.getDeclaredConstructor().newInstance()
 731      * }</pre>
 732      *
 733      * The latter sequence of calls is inferred to be able to throw
 734      * the additional exception types {@link
 735      * InvocationTargetException} and {@link
 736      * NoSuchMethodException}. Both of these exception types are
 737      * subclasses of {@link ReflectiveOperationException}.
 738      *
 739      * @return  a newly allocated instance of the class represented by this
 740      *          object.
 741      * @throws  IllegalAccessException  if the class or its nullary
 742      *          constructor is not accessible.
 743      * @throws  InstantiationException
 744      *          if this {@code Class} represents an abstract class,
 745      *          an interface, an array class, a primitive type, or void;
 746      *          or if the class has no nullary constructor;
 747      *          or if the instantiation fails for some other reason.
 748      * @throws  ExceptionInInitializerError if the initialization
 749      *          provoked by this method fails.
 750      * @throws  SecurityException
 751      *          If a security manager, <i>s</i>, is present and
 752      *          the caller's class loader is not the same as or an
 753      *          ancestor of the class loader for the current class and
 754      *          invocation of {@link SecurityManager#checkPackageAccess
 755      *          s.checkPackageAccess()} denies access to the package
 756      *          of this class.
 757      */
 758     @SuppressWarnings("removal")
 759     @CallerSensitive
 760     @Deprecated(since="9")
 761     public T newInstance()
 762         throws InstantiationException, IllegalAccessException
 763     {
 764         SecurityManager sm = System.getSecurityManager();
 765         if (sm != null) {
 766             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false);
 767         }
 768 
 769         // Constructor lookup
 770         Constructor<T> tmpConstructor = cachedConstructor;
 771         if (tmpConstructor == null) {
 772             if (this == Class.class) {
 773                 throw new IllegalAccessException(
 774                     "Can not call newInstance() on the Class for java.lang.Class"
 775                 );
 776             }
 777             try {
 778                 Class<?>[] empty = {};
 779                 final Constructor<T> c = getReflectionFactory().copyConstructor(
 780                     getConstructor0(empty, Member.DECLARED));
 781                 // Disable accessibility checks on the constructor
 782                 // access check is done with the true caller
 783                 java.security.AccessController.doPrivileged(
 784                     new java.security.PrivilegedAction<>() {
 785                         public Void run() {
 786                                 c.setAccessible(true);
 787                                 return null;
 788                             }
 789                         });
 790                 cachedConstructor = tmpConstructor = c;
 791             } catch (NoSuchMethodException e) {
 792                 throw (InstantiationException)
 793                     new InstantiationException(getName()).initCause(e);
 794             }
 795         }
 796 
 797         try {
 798             Class<?> caller = Reflection.getCallerClass();
 799             return getReflectionFactory().newInstance(tmpConstructor, null, caller);
 800         } catch (InvocationTargetException e) {
 801             Unsafe.getUnsafe().throwException(e.getTargetException());
 802             // Not reached
 803             return null;
 804         }
 805     }
 806 
 807     private transient volatile Constructor<T> cachedConstructor;
 808 
 809     /**
 810      * Determines if the specified {@code Object} is assignment-compatible
 811      * with the object represented by this {@code Class}.  This method is
 812      * the dynamic equivalent of the Java language {@code instanceof}
 813      * operator. The method returns {@code true} if the specified
 814      * {@code Object} argument is non-null and can be cast to the
 815      * reference type represented by this {@code Class} object without
 816      * raising a {@code ClassCastException.} It returns {@code false}
 817      * otherwise.
 818      *
 819      * <p> Specifically, if this {@code Class} object represents a
 820      * declared class, this method returns {@code true} if the specified
 821      * {@code Object} argument is an instance of the represented class (or
 822      * of any of its subclasses); it returns {@code false} otherwise. If
 823      * this {@code Class} object represents an array class, this method
 824      * returns {@code true} if the specified {@code Object} argument
 825      * can be converted to an object of the array class by an identity
 826      * conversion or by a widening reference conversion; it returns
 827      * {@code false} otherwise. If this {@code Class} object
 828      * represents an interface, this method returns {@code true} if the
 829      * class or any superclass of the specified {@code Object} argument
 830      * implements this interface; it returns {@code false} otherwise. If
 831      * this {@code Class} object represents a primitive type, this method
 832      * returns {@code false}.
 833      *
 834      * @param   obj the object to check
 835      * @return  true if {@code obj} is an instance of this class
 836      *
 837      * @since 1.1
 838      */
 839     @IntrinsicCandidate
 840     public native boolean isInstance(Object obj);
 841 
 842 
 843     /**
 844      * Determines if the class or interface represented by this
 845      * {@code Class} object is either the same as, or is a superclass or
 846      * superinterface of, the class or interface represented by the specified
 847      * {@code Class} parameter. It returns {@code true} if so;
 848      * otherwise it returns {@code false}. If this {@code Class}
 849      * object represents the {@linkplain #isPrimaryType() reference type}
 850      * of a {@linkplain #isPrimitiveClass() primitive class}, this method
 851      * return {@code true} if the specified {@code Class} parameter represents
 852      * the same primitive class. If this {@code Class}
 853      * object represents a primitive type, this method returns
 854      * {@code true} if the specified {@code Class} parameter is
 855      * exactly this {@code Class} object; otherwise it returns
 856      * {@code false}.
 857      *
 858      * <p> Specifically, this method tests whether the type represented by the
 859      * specified {@code Class} parameter can be converted to the type
 860      * represented by this {@code Class} object via an identity conversion
 861      * or via a widening reference conversion or via a primitive widening
 862      * conversion. See <cite>The Java Language Specification</cite>,
 863      * sections {@jls 5.1.1} and {@jls 5.1.4}, for details.
 864      *
 865      * @param     cls the {@code Class} object to be checked
 866      * @return    the {@code boolean} value indicating whether objects of the
 867      *            type {@code cls} can be assigned to objects of this class
 868      * @throws    NullPointerException if the specified Class parameter is
 869      *            null.
 870      * @since     1.1
 871      */
 872     @IntrinsicCandidate
 873     public native boolean isAssignableFrom(Class<?> cls);
 874 
 875 
 876     /**
 877      * Determines if this {@code Class} object represents an
 878      * interface type.
 879      *
 880      * @return  {@code true} if this {@code Class} object represents an interface;
 881      *          {@code false} otherwise.
 882      */
 883     @IntrinsicCandidate
 884     public native boolean isInterface();
 885 
 886 
 887     /**
 888      * Determines if this {@code Class} object represents an array class.
 889      *
 890      * @return  {@code true} if this {@code Class} object represents an array class;
 891      *          {@code false} otherwise.
 892      * @since   1.1
 893      */
 894     @IntrinsicCandidate
 895     public native boolean isArray();
 896 
 897 
 898     /**
 899      * Determines if the specified {@code Class} object represents a
 900      * primitive type.
 901      *
 902      * <p> There are nine predefined {@code Class} objects to represent
 903      * the eight primitive types and void.  These are created by the Java
 904      * Virtual Machine, and have the same names as the primitive types that
 905      * they represent, namely {@code boolean}, {@code byte},
 906      * {@code char}, {@code short}, {@code int},
 907      * {@code long}, {@code float}, and {@code double}.
 908      *
 909      * <p> These objects may only be accessed via the following public static
 910      * final variables, and are the only {@code Class} objects for which
 911      * this method returns {@code true}.
 912      *
 913      * @return true if and only if this class represents a primitive type
 914      *
 915      * @see     java.lang.Boolean#TYPE
 916      * @see     java.lang.Character#TYPE
 917      * @see     java.lang.Byte#TYPE
 918      * @see     java.lang.Short#TYPE
 919      * @see     java.lang.Integer#TYPE
 920      * @see     java.lang.Long#TYPE
 921      * @see     java.lang.Float#TYPE
 922      * @see     java.lang.Double#TYPE
 923      * @see     java.lang.Void#TYPE
 924      * @since 1.1
 925      */
 926     @IntrinsicCandidate
 927     public native boolean isPrimitive();
 928 
 929     /**
 930      * Returns true if this {@code Class} object represents an annotation
 931      * interface.  Note that if this method returns true, {@link #isInterface()}
 932      * would also return true, as all annotation interfaces are also interfaces.
 933      *
 934      * @return {@code true} if this {@code Class} object represents an annotation
 935      *      interface; {@code false} otherwise
 936      * @since 1.5
 937      */
 938     public boolean isAnnotation() {
 939         return (getModifiers() & ANNOTATION) != 0;
 940     }
 941 
 942     /**
 943      *{@return {@code true} if and only if this class has the synthetic modifier
 944      * bit set}
 945      *
 946      * @jls 13.1 The Form of a Binary
 947      * @jvms 4.1 The {@code ClassFile} Structure
 948      * @see <a
 949      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
 950      * programming language and JVM modeling in core reflection</a>
 951      * @since 1.5
 952      */
 953     public boolean isSynthetic() {
 954         return (getModifiers() & SYNTHETIC) != 0;
 955     }
 956 
 957     /**
 958      * Returns the  name of the entity (class, interface, array class,
 959      * primitive type, or void) represented by this {@code Class} object.
 960      *
 961      * <p> If this {@code Class} object represents a class or interface,
 962      * not an array class, then:
 963      * <ul>
 964      * <li> If the class or interface is not {@linkplain #isHidden() hidden},
 965      *      then the <a href="ClassLoader.html#binary-name">binary name</a>
 966      *      of the class or interface is returned.
 967      * <li> If the class or interface is hidden, then the result is a string
 968      *      of the form: {@code N + '/' + <suffix>}
 969      *      where {@code N} is the <a href="ClassLoader.html#binary-name">binary name</a>
 970      *      indicated by the {@code class} file passed to
 971      *      {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
 972      *      Lookup::defineHiddenClass}, and {@code <suffix>} is an unqualified name.
 973      * </ul>
 974      *
 975      * <p> If this {@code Class} object represents an array class, then
 976      * the result is a string consisting of one or more '{@code [}' characters
 977      * representing the depth of the array nesting, followed by the element
 978      * type as encoded using the following table:
 979      *
 980      * <blockquote><table class="striped">
 981      * <caption style="display:none">Element types and encodings</caption>
 982      * <thead>
 983      * <tr><th scope="col"> Element Type <th scope="col"> Encoding
 984      * </thead>
 985      * <tbody style="text-align:left">
 986      * <tr><th scope="row"> {@code boolean} <td style="text-align:center"> {@code Z}
 987      * <tr><th scope="row"> {@code byte}    <td style="text-align:center"> {@code B}
 988      * <tr><th scope="row"> {@code char}    <td style="text-align:center"> {@code C}
 989      * <tr><th scope="row"> class or interface with <a href="ClassLoader.html#binary-name">binary name</a> <i>N</i>
 990      *                                      <td style="text-align:center"> {@code L}<em>N</em>{@code ;}
 991      * <tr><th scope="row"> {@linkplain #isPrimitiveClass() primitive class} with <a href="ClassLoader.html#binary-name">binary name</a> <i>N</i>
 992      *                                      <td style="text-align:center"> {@code Q}<em>N</em>{@code ;}
 993      * <tr><th scope="row"> {@code double}  <td style="text-align:center"> {@code D}
 994      * <tr><th scope="row"> {@code float}   <td style="text-align:center"> {@code F}
 995      * <tr><th scope="row"> {@code int}     <td style="text-align:center"> {@code I}
 996      * <tr><th scope="row"> {@code long}    <td style="text-align:center"> {@code J}
 997      * <tr><th scope="row"> {@code short}   <td style="text-align:center"> {@code S}
 998      * </tbody>
 999      * </table></blockquote>
1000      *
1001      * <p> If this {@code Class} object represents a primitive type or {@code void},
1002      * then the result is a string with the same spelling as the Java language
1003      * keyword which corresponds to the primitive type or {@code void}.
1004      *
1005      * <p> Examples:
1006      * <blockquote><pre>
1007      * String.class.getName()
1008      *     returns "java.lang.String"
1009      * byte.class.getName()
1010      *     returns "byte"
1011      * Point.class.getName()
1012      *     returns "Point"
1013      * (new Object[3]).getClass().getName()
1014      *     returns "[Ljava.lang.Object;"
1015      * (new Point[3]).getClass().getName()
1016      *     returns "[QPoint;"
1017      * (new Point.ref[3][4]).getClass().getName()
1018      *     returns "[[LPoint;"
1019      * (new int[3][4][5][6][7][8][9]).getClass().getName()
1020      *     returns "[[[[[[[I"
1021      * </pre></blockquote>
1022      *
1023      * @return  the name of the class, interface, or other entity
1024      *          represented by this {@code Class} object.
1025      * @jls 13.1 The Form of a Binary
1026      */
1027     public String getName() {
1028         String name = this.name;
1029         return name != null ? name : initClassName();
1030     }
1031 
1032     // Cache the name to reduce the number of calls into the VM.
1033     // This field would be set by VM itself during initClassName call.
1034     private transient String name;
1035     private native String initClassName();
1036 
1037     /**
1038      * Returns the class loader for the class.  Some implementations may use
1039      * null to represent the bootstrap class loader. This method will return
1040      * null in such implementations if this class was loaded by the bootstrap
1041      * class loader.
1042      *
1043      * <p>If this {@code Class} object
1044      * represents a primitive type or void, null is returned.
1045      *
1046      * @return  the class loader that loaded the class or interface
1047      *          represented by this {@code Class} object.
1048      * @throws  SecurityException
1049      *          if a security manager is present, and the caller's class loader
1050      *          is not {@code null} and is not the same as or an ancestor of the
1051      *          class loader for the class whose class loader is requested,
1052      *          and the caller does not have the
1053      *          {@link RuntimePermission}{@code ("getClassLoader")}
1054      * @see java.lang.ClassLoader
1055      * @see SecurityManager#checkPermission
1056      * @see java.lang.RuntimePermission
1057      */
1058     @CallerSensitive
1059     @ForceInline // to ensure Reflection.getCallerClass optimization
1060     public ClassLoader getClassLoader() {
1061         ClassLoader cl = classLoader;
1062         if (cl == null)
1063             return null;
1064         @SuppressWarnings("removal")
1065         SecurityManager sm = System.getSecurityManager();
1066         if (sm != null) {
1067             ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass());
1068         }
1069         return cl;
1070     }
1071 
1072     // Package-private to allow ClassLoader access
1073     ClassLoader getClassLoader0() { return classLoader; }
1074 
1075     /**
1076      * Returns the module that this class or interface is a member of.
1077      *
1078      * If this class represents an array type then this method returns the
1079      * {@code Module} for the element type. If this class represents a
1080      * primitive type or void, then the {@code Module} object for the
1081      * {@code java.base} module is returned.
1082      *
1083      * If this class is in an unnamed module then the {@linkplain
1084      * ClassLoader#getUnnamedModule() unnamed} {@code Module} of the class
1085      * loader for this class is returned.
1086      *
1087      * @return the module that this class or interface is a member of
1088      *
1089      * @since 9
1090      */
1091     public Module getModule() {
1092         return module;
1093     }
1094 
1095     // set by VM
1096     private transient Module module;
1097 
1098     // Initialized in JVM not by private constructor
1099     // This field is filtered from reflection access, i.e. getDeclaredField
1100     // will throw NoSuchFieldException
1101     private final ClassLoader classLoader;
1102 
1103     // Set by VM
1104     private transient Object classData;
1105 
1106     // package-private
1107     Object getClassData() {
1108         return classData;
1109     }
1110 
1111     /**
1112      * Returns an array of {@code TypeVariable} objects that represent the
1113      * type variables declared by the generic declaration represented by this
1114      * {@code GenericDeclaration} object, in declaration order.  Returns an
1115      * array of length 0 if the underlying generic declaration declares no type
1116      * variables.
1117      *
1118      * @return an array of {@code TypeVariable} objects that represent
1119      *     the type variables declared by this generic declaration
1120      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
1121      *     signature of this generic declaration does not conform to
1122      *     the format specified in section {@jvms 4.7.9} of
1123      *     <cite>The Java Virtual Machine Specification</cite>
1124      * @since 1.5
1125      */
1126     @SuppressWarnings("unchecked")
1127     public TypeVariable<Class<T>>[] getTypeParameters() {
1128         ClassRepository info = getGenericInfo();
1129         if (info != null)
1130             return (TypeVariable<Class<T>>[])info.getTypeParameters();
1131         else
1132             return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];
1133     }
1134 
1135 
1136     /**
1137      * Returns the {@code Class} representing the direct superclass of the
1138      * entity (class, interface, primitive type or void) represented by
1139      * this {@code Class}.  If this {@code Class} represents either the
1140      * {@code Object} class, an interface, a primitive type, or void, then
1141      * null is returned.  If this {@code Class} object represents an array class
1142      * then the {@code Class} object representing the {@code Object} class is
1143      * returned.
1144      *
1145      * @return the direct superclass of the class represented by this {@code Class} object
1146      */
1147     @IntrinsicCandidate
1148     public native Class<? super T> getSuperclass();
1149 
1150 
1151     /**
1152      * Returns the {@code Type} representing the direct superclass of
1153      * the entity (class, interface, primitive type or void) represented by
1154      * this {@code Class} object.
1155      *
1156      * <p>If the superclass is a parameterized type, the {@code Type}
1157      * object returned must accurately reflect the actual type
1158      * arguments used in the source code. The parameterized type
1159      * representing the superclass is created if it had not been
1160      * created before. See the declaration of {@link
1161      * java.lang.reflect.ParameterizedType ParameterizedType} for the
1162      * semantics of the creation process for parameterized types.  If
1163      * this {@code Class} object represents either the {@code Object}
1164      * class, an interface, a primitive type, or void, then null is
1165      * returned.  If this {@code Class} object represents an array class
1166      * then the {@code Class} object representing the {@code Object} class is
1167      * returned.
1168      *
1169      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
1170      *     class signature does not conform to the format specified in
1171      *     section {@jvms 4.7.9} of <cite>The Java Virtual
1172      *     Machine Specification</cite>
1173      * @throws TypeNotPresentException if the generic superclass
1174      *     refers to a non-existent type declaration
1175      * @throws java.lang.reflect.MalformedParameterizedTypeException if the
1176      *     generic superclass refers to a parameterized type that cannot be
1177      *     instantiated  for any reason
1178      * @return the direct superclass of the class represented by this {@code Class} object
1179      * @since 1.5
1180      */
1181     public Type getGenericSuperclass() {
1182         ClassRepository info = getGenericInfo();
1183         if (info == null) {
1184             return getSuperclass();
1185         }
1186 
1187         // Historical irregularity:
1188         // Generic signature marks interfaces with superclass = Object
1189         // but this API returns null for interfaces
1190         if (isInterface()) {
1191             return null;
1192         }
1193 
1194         return info.getSuperclass();
1195     }
1196 
1197     /**
1198      * Gets the package of this class.
1199      *
1200      * <p>If this class represents an array type, a primitive type or void,
1201      * this method returns {@code null}.
1202      *
1203      * @return the package of this class.
1204      * @revised 9
1205      */
1206     public Package getPackage() {
1207         if (isPrimitive() || isArray()) {
1208             return null;
1209         }
1210         ClassLoader cl = classLoader;
1211         return cl != null ? cl.definePackage(this)
1212                           : BootLoader.definePackage(this);
1213     }
1214 
1215     /**
1216      * Returns the fully qualified package name.
1217      *
1218      * <p> If this class is a top level class, then this method returns the fully
1219      * qualified name of the package that the class is a member of, or the
1220      * empty string if the class is in an unnamed package.
1221      *
1222      * <p> If this class is a member class, then this method is equivalent to
1223      * invoking {@code getPackageName()} on the {@linkplain #getEnclosingClass
1224      * enclosing class}.
1225      *
1226      * <p> If this class is a {@linkplain #isLocalClass local class} or an {@linkplain
1227      * #isAnonymousClass() anonymous class}, then this method is equivalent to
1228      * invoking {@code getPackageName()} on the {@linkplain #getDeclaringClass
1229      * declaring class} of the {@linkplain #getEnclosingMethod enclosing method} or
1230      * {@linkplain #getEnclosingConstructor enclosing constructor}.
1231      *
1232      * <p> If this class represents an array type then this method returns the
1233      * package name of the element type. If this class represents a primitive
1234      * type or void then the package name "{@code java.lang}" is returned.
1235      *
1236      * @return the fully qualified package name
1237      *
1238      * @since 9
1239      * @jls 6.7 Fully Qualified Names
1240      */
1241     public String getPackageName() {
1242         String pn = this.packageName;
1243         if (pn == null) {
1244             Class<?> c = isArray() ? elementType() : this;
1245             if (c.isPrimitive()) {
1246                 pn = "java.lang";
1247             } else {
1248                 String cn = c.getName();
1249                 int dot = cn.lastIndexOf('.');
1250                 pn = (dot != -1) ? cn.substring(0, dot).intern() : "";
1251             }
1252             this.packageName = pn;
1253         }
1254         return pn;
1255     }
1256 
1257     // cached package name
1258     private transient String packageName;
1259 
1260     /**
1261      * Returns the interfaces directly implemented by the class or interface
1262      * represented by this {@code Class} object.
1263      *
1264      * <p>If this {@code Class} object represents a class, the return value is an array
1265      * containing objects representing all interfaces directly implemented by
1266      * the class.  The order of the interface objects in the array corresponds
1267      * to the order of the interface names in the {@code implements} clause of
1268      * the declaration of the class represented by this {@code Class} object.  For example,
1269      * given the declaration:
1270      * <blockquote>
1271      * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
1272      * </blockquote>
1273      * suppose the value of {@code s} is an instance of
1274      * {@code Shimmer}; the value of the expression:
1275      * <blockquote>
1276      * {@code s.getClass().getInterfaces()[0]}
1277      * </blockquote>
1278      * is the {@code Class} object that represents interface
1279      * {@code FloorWax}; and the value of:
1280      * <blockquote>
1281      * {@code s.getClass().getInterfaces()[1]}
1282      * </blockquote>
1283      * is the {@code Class} object that represents interface
1284      * {@code DessertTopping}.
1285      *
1286      * <p>If this {@code Class} object represents an interface, the array contains objects
1287      * representing all interfaces directly extended by the interface.  The
1288      * order of the interface objects in the array corresponds to the order of
1289      * the interface names in the {@code extends} clause of the declaration of
1290      * the interface represented by this {@code Class} object.
1291      *
1292      * <p>If this {@code Class} object represents a class or interface that implements no
1293      * interfaces, the method returns an array of length 0.
1294      *
1295      * <p>If this {@code Class} object represents a primitive type or void, the method
1296      * returns an array of length 0.
1297      *
1298      * <p>If this {@code Class} object represents an array type, the
1299      * interfaces {@code Cloneable} and {@code java.io.Serializable} are
1300      * returned in that order.
1301      *
1302      * @return an array of interfaces directly implemented by this class
1303      */
1304     public Class<?>[] getInterfaces() {
1305         // defensively copy before handing over to user code
1306         return getInterfaces(true);
1307     }
1308 
1309     private Class<?>[] getInterfaces(boolean cloneArray) {
1310         ReflectionData<T> rd = reflectionData();
1311         if (rd == null) {
1312             // no cloning required
1313             return getInterfaces0();
1314         } else {
1315             Class<?>[] interfaces = rd.interfaces;
1316             if (interfaces == null) {
1317                 interfaces = getInterfaces0();
1318                 rd.interfaces = interfaces;
1319             }
1320             // defensively copy if requested
1321             return cloneArray ? interfaces.clone() : interfaces;
1322         }
1323     }
1324 
1325     private native Class<?>[] getInterfaces0();
1326 
1327     /**
1328      * Returns the {@code Type}s representing the interfaces
1329      * directly implemented by the class or interface represented by
1330      * this {@code Class} object.
1331      *
1332      * <p>If a superinterface is a parameterized type, the
1333      * {@code Type} object returned for it must accurately reflect
1334      * the actual type arguments used in the source code. The
1335      * parameterized type representing each superinterface is created
1336      * if it had not been created before. See the declaration of
1337      * {@link java.lang.reflect.ParameterizedType ParameterizedType}
1338      * for the semantics of the creation process for parameterized
1339      * types.
1340      *
1341      * <p>If this {@code Class} object represents a class, the return value is an array
1342      * containing objects representing all interfaces directly implemented by
1343      * the class.  The order of the interface objects in the array corresponds
1344      * to the order of the interface names in the {@code implements} clause of
1345      * the declaration of the class represented by this {@code Class} object.
1346      *
1347      * <p>If this {@code Class} object represents an interface, the array contains objects
1348      * representing all interfaces directly extended by the interface.  The
1349      * order of the interface objects in the array corresponds to the order of
1350      * the interface names in the {@code extends} clause of the declaration of
1351      * the interface represented by this {@code Class} object.
1352      *
1353      * <p>If this {@code Class} object represents a class or interface that implements no
1354      * interfaces, the method returns an array of length 0.
1355      *
1356      * <p>If this {@code Class} object represents a primitive type or void, the method
1357      * returns an array of length 0.
1358      *
1359      * <p>If this {@code Class} object represents an array type, the
1360      * interfaces {@code Cloneable} and {@code java.io.Serializable} are
1361      * returned in that order.
1362      *
1363      * @throws java.lang.reflect.GenericSignatureFormatError
1364      *     if the generic class signature does not conform to the
1365      *     format specified in section {@jvms 4.7.9} of <cite>The
1366      *     Java Virtual Machine Specification</cite>
1367      * @throws TypeNotPresentException if any of the generic
1368      *     superinterfaces refers to a non-existent type declaration
1369      * @throws java.lang.reflect.MalformedParameterizedTypeException
1370      *     if any of the generic superinterfaces refer to a parameterized
1371      *     type that cannot be instantiated for any reason
1372      * @return an array of interfaces directly implemented by this class
1373      * @since 1.5
1374      */
1375     public Type[] getGenericInterfaces() {
1376         ClassRepository info = getGenericInfo();
1377         return (info == null) ?  getInterfaces() : info.getSuperInterfaces();
1378     }
1379 
1380 
1381     /**
1382      * Returns the {@code Class} representing the component type of an
1383      * array.  If this class does not represent an array class this method
1384      * returns null.
1385      *
1386      * @return the {@code Class} representing the component type of this
1387      * class if this class is an array
1388      * @see     java.lang.reflect.Array
1389      * @since 1.1
1390      */
1391     public Class<?> getComponentType() {
1392         // Only return for array types. Storage may be reused for Class for instance types.
1393         if (isArray()) {
1394             return componentType;
1395         } else {
1396             return null;
1397         }
1398     }
1399 
1400     private final Class<?> componentType;
1401 
1402     /*
1403      * Returns the {@code Class} representing the element type of an array class.
1404      * If this class does not represent an array class, then this method returns
1405      * {@code null}.
1406      */
1407     private Class<?> elementType() {
1408         if (!isArray()) return null;
1409 
1410         Class<?> c = this;
1411         while (c.isArray()) {
1412             c = c.getComponentType();
1413         }
1414         return c;
1415     }
1416 
1417     /**
1418      * Returns the Java language modifiers for this class or interface, encoded
1419      * in an integer. The modifiers consist of the Java Virtual Machine's
1420      * constants for {@code public}, {@code protected},
1421      * {@code private}, {@code final}, {@code static},
1422      * {@code abstract} and {@code interface}; they should be decoded
1423      * using the methods of class {@code Modifier}.
1424      *
1425      * <p> If the underlying class is an array class, then its
1426      * {@code public}, {@code private} and {@code protected}
1427      * modifiers are the same as those of its component type.  If this
1428      * {@code Class} object represents a primitive type or void, its
1429      * {@code public} modifier is always {@code true}, and its
1430      * {@code protected} and {@code private} modifiers are always
1431      * {@code false}. If this {@code Class} object represents an array class, a
1432      * primitive type or void, then its {@code final} modifier is always
1433      * {@code true} and its interface modifier is always
1434      * {@code false}. The values of its other modifiers are not determined
1435      * by this specification.
1436      *
1437      * <p> The modifier encodings are defined in section {@jvms 4.1}
1438      * of <cite>The Java Virtual Machine Specification</cite>.
1439      *
1440      * @return the {@code int} representing the modifiers for this class
1441      * @see     java.lang.reflect.Modifier
1442      * @see <a
1443      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1444      * programming language and JVM modeling in core reflection</a>
1445      * @since 1.1
1446      * @jls 8.1.1 Class Modifiers
1447      * @jls 9.1.1. Interface Modifiers
1448      */
1449     @IntrinsicCandidate
1450     public native int getModifiers();
1451 

1452     /**
1453      * Gets the signers of this class.
1454      *
1455      * @return  the signers of this class, or null if there are no signers.  In
1456      *          particular, this method returns null if this {@code Class} object represents
1457      *          a primitive type or void.
1458      * @since   1.1
1459      */
1460     public native Object[] getSigners();
1461 

1462     /**
1463      * Set the signers of this class.
1464      */
1465     native void setSigners(Object[] signers);
1466 
1467 
1468     /**
1469      * If this {@code Class} object represents a local or anonymous
1470      * class within a method, returns a {@link
1471      * java.lang.reflect.Method Method} object representing the
1472      * immediately enclosing method of the underlying class. Returns
1473      * {@code null} otherwise.
1474      *
1475      * In particular, this method returns {@code null} if the underlying
1476      * class is a local or anonymous class immediately enclosed by a class or
1477      * interface declaration, instance initializer or static initializer.
1478      *
1479      * @return the immediately enclosing method of the underlying class, if
1480      *     that class is a local or anonymous class; otherwise {@code null}.
1481      *
1482      * @throws SecurityException
1483      *         If a security manager, <i>s</i>, is present and any of the
1484      *         following conditions is met:
1485      *
1486      *         <ul>
1487      *
1488      *         <li> the caller's class loader is not the same as the
1489      *         class loader of the enclosing class and invocation of
1490      *         {@link SecurityManager#checkPermission
1491      *         s.checkPermission} method with
1492      *         {@code RuntimePermission("accessDeclaredMembers")}
1493      *         denies access to the methods within the enclosing class
1494      *
1495      *         <li> the caller's class loader is not the same as or an
1496      *         ancestor of the class loader for the enclosing class and
1497      *         invocation of {@link SecurityManager#checkPackageAccess
1498      *         s.checkPackageAccess()} denies access to the package
1499      *         of the enclosing class
1500      *
1501      *         </ul>
1502      * @since 1.5
1503      */
1504     @CallerSensitive
1505     public Method getEnclosingMethod() throws SecurityException {
1506         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1507 
1508         if (enclosingInfo == null)
1509             return null;
1510         else {
1511             if (!enclosingInfo.isMethod())
1512                 return null;
1513 
1514             MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
1515                                                               getFactory());
1516             Class<?>   returnType       = toClass(typeInfo.getReturnType());
1517             Type []    parameterTypes   = typeInfo.getParameterTypes();
1518             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1519 
1520             // Convert Types to Classes; returned types *should*
1521             // be class objects since the methodDescriptor's used
1522             // don't have generics information
1523             for(int i = 0; i < parameterClasses.length; i++)
1524                 parameterClasses[i] = toClass(parameterTypes[i]);
1525 
1526             // Perform access check
1527             final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1528             @SuppressWarnings("removal")
1529             SecurityManager sm = System.getSecurityManager();
1530             if (sm != null) {
1531                 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED,
1532                                                      Reflection.getCallerClass(), true);
1533             }
1534             Method[] candidates = enclosingCandidate.privateGetDeclaredMethods(false);
1535 
1536             /*
1537              * Loop over all declared methods; match method name,
1538              * number of and type of parameters, *and* return
1539              * type.  Matching return type is also necessary
1540              * because of covariant returns, etc.
1541              */
1542             ReflectionFactory fact = getReflectionFactory();
1543             for (Method m : candidates) {
1544                 if (m.getName().equals(enclosingInfo.getName()) &&
1545                     arrayContentsEq(parameterClasses,
1546                                     fact.getExecutableSharedParameterTypes(m))) {
1547                     // finally, check return type
1548                     if (m.getReturnType().equals(returnType)) {
1549                         return fact.copyMethod(m);
1550                     }
1551                 }
1552             }
1553 
1554             throw new InternalError("Enclosing method not found");
1555         }
1556     }
1557 
1558     private native Object[] getEnclosingMethod0();
1559 
1560     private EnclosingMethodInfo getEnclosingMethodInfo() {
1561         Object[] enclosingInfo = getEnclosingMethod0();
1562         if (enclosingInfo == null)
1563             return null;
1564         else {
1565             return new EnclosingMethodInfo(enclosingInfo);
1566         }
1567     }
1568 
1569     private static final class EnclosingMethodInfo {
1570         private final Class<?> enclosingClass;
1571         private final String name;
1572         private final String descriptor;
1573 
1574         static void validate(Object[] enclosingInfo) {
1575             if (enclosingInfo.length != 3)
1576                 throw new InternalError("Malformed enclosing method information");
1577             try {
1578                 // The array is expected to have three elements:
1579 
1580                 // the immediately enclosing class
1581                 Class<?> enclosingClass = (Class<?>)enclosingInfo[0];
1582                 assert(enclosingClass != null);
1583 
1584                 // the immediately enclosing method or constructor's
1585                 // name (can be null).
1586                 String name = (String)enclosingInfo[1];
1587 
1588                 // the immediately enclosing method or constructor's
1589                 // descriptor (null iff name is).
1590                 String descriptor = (String)enclosingInfo[2];
1591                 assert((name != null && descriptor != null) || name == descriptor);
1592             } catch (ClassCastException cce) {
1593                 throw new InternalError("Invalid type in enclosing method information", cce);
1594             }
1595         }
1596 
1597         EnclosingMethodInfo(Object[] enclosingInfo) {
1598             validate(enclosingInfo);
1599             this.enclosingClass = (Class<?>)enclosingInfo[0];
1600             this.name = (String)enclosingInfo[1];
1601             this.descriptor = (String)enclosingInfo[2];
1602         }
1603 
1604         boolean isPartial() {
1605             return enclosingClass == null || name == null || descriptor == null;
1606         }
1607 
1608         boolean isConstructor() { return !isPartial() && "<init>".equals(name); }
1609 
1610         boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }
1611 
1612         Class<?> getEnclosingClass() { return enclosingClass; }
1613 
1614         String getName() { return name; }
1615 
1616         String getDescriptor() { return descriptor; }
1617 
1618     }
1619 
1620     private static Class<?> toClass(Type o) {
1621         if (o instanceof GenericArrayType)
1622             return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
1623                                      0)
1624                 .getClass();
1625         return (Class<?>)o;
1626      }
1627 
1628     /**
1629      * If this {@code Class} object represents a local or anonymous
1630      * class within a constructor, returns a {@link
1631      * java.lang.reflect.Constructor Constructor} object representing
1632      * the immediately enclosing constructor of the underlying
1633      * class. Returns {@code null} otherwise.  In particular, this
1634      * method returns {@code null} if the underlying class is a local
1635      * or anonymous class immediately enclosed by a class or
1636      * interface declaration, instance initializer or static initializer.
1637      *
1638      * @return the immediately enclosing constructor of the underlying class, if
1639      *     that class is a local or anonymous class; otherwise {@code null}.
1640      * @throws SecurityException
1641      *         If a security manager, <i>s</i>, is present and any of the
1642      *         following conditions is met:
1643      *
1644      *         <ul>
1645      *
1646      *         <li> the caller's class loader is not the same as the
1647      *         class loader of the enclosing class and invocation of
1648      *         {@link SecurityManager#checkPermission
1649      *         s.checkPermission} method with
1650      *         {@code RuntimePermission("accessDeclaredMembers")}
1651      *         denies access to the constructors within the enclosing class
1652      *
1653      *         <li> the caller's class loader is not the same as or an
1654      *         ancestor of the class loader for the enclosing class and
1655      *         invocation of {@link SecurityManager#checkPackageAccess
1656      *         s.checkPackageAccess()} denies access to the package
1657      *         of the enclosing class
1658      *
1659      *         </ul>
1660      * @since 1.5
1661      */
1662     @CallerSensitive
1663     public Constructor<?> getEnclosingConstructor() throws SecurityException {
1664         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1665 
1666         if (enclosingInfo == null)
1667             return null;
1668         else {
1669             if (!enclosingInfo.isConstructor())
1670                 return null;
1671 
1672             ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
1673                                                                         getFactory());
1674             Type []    parameterTypes   = typeInfo.getParameterTypes();
1675             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1676 
1677             // Convert Types to Classes; returned types *should*
1678             // be class objects since the methodDescriptor's used
1679             // don't have generics information
1680             for(int i = 0; i < parameterClasses.length; i++)
1681                 parameterClasses[i] = toClass(parameterTypes[i]);
1682 
1683             // Perform access check
1684             final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1685             @SuppressWarnings("removal")
1686             SecurityManager sm = System.getSecurityManager();
1687             if (sm != null) {
1688                 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED,
1689                                                      Reflection.getCallerClass(), true);
1690             }
1691 
1692             Constructor<?>[] candidates = enclosingCandidate
1693                     .privateGetDeclaredConstructors(false);
1694             /*
1695              * Loop over all declared constructors; match number
1696              * of and type of parameters.
1697              */
1698             ReflectionFactory fact = getReflectionFactory();
1699             for (Constructor<?> c : candidates) {
1700                 if (arrayContentsEq(parameterClasses,
1701                                     fact.getExecutableSharedParameterTypes(c))) {
1702                     return fact.copyConstructor(c);
1703                 }
1704             }
1705 
1706             throw new InternalError("Enclosing constructor not found");
1707         }
1708     }
1709 
1710 
1711     /**
1712      * If the class or interface represented by this {@code Class} object
1713      * is a member of another class, returns the {@code Class} object
1714      * representing the class in which it was declared.  This method returns
1715      * null if this class or interface is not a member of any other class.  If
1716      * this {@code Class} object represents an array class, a primitive
1717      * type, or void,then this method returns null.
1718      *
1719      * @return the declaring class for this class
1720      * @throws SecurityException
1721      *         If a security manager, <i>s</i>, is present and the caller's
1722      *         class loader is not the same as or an ancestor of the class
1723      *         loader for the declaring class and invocation of {@link
1724      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
1725      *         denies access to the package of the declaring class
1726      * @since 1.1
1727      */
1728     @CallerSensitive
1729     public Class<?> getDeclaringClass() throws SecurityException {
1730         final Class<?> candidate = getDeclaringClass0();
1731 
1732         if (candidate != null) {
1733             @SuppressWarnings("removal")
1734             SecurityManager sm = System.getSecurityManager();
1735             if (sm != null) {
1736                 candidate.checkPackageAccess(sm,
1737                     ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
1738             }
1739         }
1740         return candidate;
1741     }
1742 
1743     private native Class<?> getDeclaringClass0();
1744 
1745 
1746     /**
1747      * Returns the immediately enclosing class of the underlying
1748      * class.  If the underlying class is a top level class this
1749      * method returns {@code null}.
1750      * @return the immediately enclosing class of the underlying class
1751      * @throws     SecurityException
1752      *             If a security manager, <i>s</i>, is present and the caller's
1753      *             class loader is not the same as or an ancestor of the class
1754      *             loader for the enclosing class and invocation of {@link
1755      *             SecurityManager#checkPackageAccess s.checkPackageAccess()}
1756      *             denies access to the package of the enclosing class
1757      * @since 1.5
1758      */
1759     @CallerSensitive
1760     public Class<?> getEnclosingClass() throws SecurityException {
1761         // There are five kinds of classes (or interfaces):
1762         // a) Top level classes
1763         // b) Nested classes (static member classes)
1764         // c) Inner classes (non-static member classes)
1765         // d) Local classes (named classes declared within a method)
1766         // e) Anonymous classes
1767 
1768 
1769         // JVM Spec 4.7.7: A class must have an EnclosingMethod
1770         // attribute if and only if it is a local class or an
1771         // anonymous class.
1772         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1773         Class<?> enclosingCandidate;
1774 
1775         if (enclosingInfo == null) {
1776             // This is a top level or a nested class or an inner class (a, b, or c)
1777             enclosingCandidate = getDeclaringClass0();
1778         } else {
1779             Class<?> enclosingClass = enclosingInfo.getEnclosingClass();
1780             // This is a local class or an anonymous class (d or e)
1781             if (enclosingClass == this || enclosingClass == null)
1782                 throw new InternalError("Malformed enclosing method information");
1783             else
1784                 enclosingCandidate = enclosingClass;
1785         }
1786 
1787         if (enclosingCandidate != null) {
1788             @SuppressWarnings("removal")
1789             SecurityManager sm = System.getSecurityManager();
1790             if (sm != null) {
1791                 enclosingCandidate.checkPackageAccess(sm,
1792                     ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
1793             }
1794         }
1795         return enclosingCandidate;
1796     }
1797 
1798     /**
1799      * Returns the simple name of the underlying class as given in the
1800      * source code. An empty string is returned if the underlying class is
1801      * {@linkplain #isAnonymousClass() anonymous}.
1802      * A {@linkplain #isSynthetic() synthetic class}, one not present
1803      * in source code, can have a non-empty name including special
1804      * characters, such as "{@code $}".
1805      *
1806      * <p>The simple name of an {@linkplain #isArray() array class} is the simple name of the
1807      * component type with "[]" appended.  In particular the simple
1808      * name of an array class whose component type is anonymous is "[]".
1809      *
1810      * @return the simple name of the underlying class
1811      * @since 1.5
1812      */
1813     public String getSimpleName() {
1814         ReflectionData<T> rd = reflectionData();
1815         String simpleName = rd.simpleName;
1816         if (simpleName == null) {
1817             rd.simpleName = simpleName = getSimpleName0();
1818         }
1819         return simpleName;
1820     }
1821 
1822     private String getSimpleName0() {
1823         if (isArray()) {
1824             return getComponentType().getSimpleName().concat("[]");
1825         }
1826         String simpleName = getSimpleBinaryName();
1827         if (simpleName == null) { // top level class
1828             simpleName = getName();
1829             simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1830         }
1831         return simpleName;
1832     }
1833 
1834     /**
1835      * Return an informative string for the name of this class or interface.
1836      *
1837      * @return an informative string for the name of this class or interface
1838      * @since 1.8
1839      */
1840     public String getTypeName() {
1841         if (isArray()) {
1842             try {
1843                 Class<?> cl = this;
1844                 int dimensions = 0;
1845                 do {
1846                     dimensions++;
1847                     cl = cl.getComponentType();
1848                 } while (cl.isArray());
1849                 return cl.getTypeName().concat("[]".repeat(dimensions));
1850             } catch (Throwable e) { /*FALLTHRU*/ }
1851         }
1852         if (isPrimitiveClass()) {
1853             // TODO: null-default
1854             return isPrimaryType() ? getName().concat(".ref") : getName();
1855         } else {
1856             return getName();
1857         }
1858     }
1859 
1860     /**
1861      * Returns the canonical name of the underlying class as
1862      * defined by <cite>The Java Language Specification</cite>.
1863      * Returns {@code null} if the underlying class does not have a canonical
1864      * name. Classes without canonical names include:
1865      * <ul>
1866      * <li>a {@linkplain #isLocalClass() local class}
1867      * <li>a {@linkplain #isAnonymousClass() anonymous class}
1868      * <li>a {@linkplain #isHidden() hidden class}
1869      * <li>an array whose component type does not have a canonical name</li>
1870      * </ul>
1871      *
1872      * @return the canonical name of the underlying class if it exists, and
1873      * {@code null} otherwise.
1874      * @since 1.5
1875      */
1876     public String getCanonicalName() {
1877         ReflectionData<T> rd = reflectionData();
1878         String canonicalName = rd.canonicalName;
1879         if (canonicalName == null) {
1880             rd.canonicalName = canonicalName = getCanonicalName0();
1881         }
1882         return canonicalName == ReflectionData.NULL_SENTINEL? null : canonicalName;
1883     }
1884 
1885     private String getCanonicalName0() {
1886         if (isArray()) {
1887             String canonicalName = getComponentType().getCanonicalName();
1888             if (canonicalName != null)
1889                 return canonicalName.concat("[]");
1890             else
1891                 return ReflectionData.NULL_SENTINEL;
1892         }
1893         if (isHidden() || isLocalOrAnonymousClass())
1894             return ReflectionData.NULL_SENTINEL;
1895         Class<?> enclosingClass = getEnclosingClass();
1896         if (enclosingClass == null) { // top level class
1897             return getName();
1898         } else {
1899             String enclosingName = enclosingClass.getCanonicalName();
1900             if (enclosingName == null)
1901                 return ReflectionData.NULL_SENTINEL;
1902             String simpleName = getSimpleName();
1903             return new StringBuilder(enclosingName.length() + simpleName.length() + 1)
1904                     .append(enclosingName)
1905                     .append('.')
1906                     .append(simpleName)
1907                     .toString();
1908         }
1909     }
1910 
1911     /**
1912      * Returns {@code true} if and only if the underlying class
1913      * is an anonymous class.
1914      *
1915      * @apiNote
1916      * An anonymous class is not a {@linkplain #isHidden() hidden class}.
1917      *
1918      * @return {@code true} if and only if this class is an anonymous class.
1919      * @since 1.5
1920      * @jls 15.9.5 Anonymous Class Declarations
1921      */
1922     public boolean isAnonymousClass() {
1923         return !isArray() && isLocalOrAnonymousClass() &&
1924                 getSimpleBinaryName0() == null;
1925     }
1926 
1927     /**
1928      * Returns {@code true} if and only if the underlying class
1929      * is a local class.
1930      *
1931      * @return {@code true} if and only if this class is a local class.
1932      * @since 1.5
1933      * @jls 14.3 Local Class Declarations
1934      */
1935     public boolean isLocalClass() {
1936         return isLocalOrAnonymousClass() &&
1937                 (isArray() || getSimpleBinaryName0() != null);
1938     }
1939 
1940     /**
1941      * Returns {@code true} if and only if the underlying class
1942      * is a member class.
1943      *
1944      * @return {@code true} if and only if this class is a member class.
1945      * @since 1.5
1946      * @jls 8.5 Member Type Declarations
1947      */
1948     public boolean isMemberClass() {
1949         return !isLocalOrAnonymousClass() && getDeclaringClass0() != null;
1950     }
1951 
1952     /**
1953      * Returns the "simple binary name" of the underlying class, i.e.,
1954      * the binary name without the leading enclosing class name.
1955      * Returns {@code null} if the underlying class is a top level
1956      * class.
1957      */
1958     private String getSimpleBinaryName() {
1959         if (isTopLevelClass())
1960             return null;
1961         String name = getSimpleBinaryName0();
1962         if (name == null) // anonymous class
1963             return "";
1964         return name;
1965     }
1966 
1967     private native String getSimpleBinaryName0();
1968 
1969     /**
1970      * Returns {@code true} if this is a top level class.  Returns {@code false}
1971      * otherwise.
1972      */
1973     private boolean isTopLevelClass() {
1974         return !isLocalOrAnonymousClass() && getDeclaringClass0() == null;
1975     }
1976 
1977     /**
1978      * Returns {@code true} if this is a local class or an anonymous
1979      * class.  Returns {@code false} otherwise.
1980      */
1981     private boolean isLocalOrAnonymousClass() {
1982         // JVM Spec 4.7.7: A class must have an EnclosingMethod
1983         // attribute if and only if it is a local class or an
1984         // anonymous class.
1985         return hasEnclosingMethodInfo();
1986     }
1987 
1988     private boolean hasEnclosingMethodInfo() {
1989         Object[] enclosingInfo = getEnclosingMethod0();
1990         if (enclosingInfo != null) {
1991             EnclosingMethodInfo.validate(enclosingInfo);
1992             return true;
1993         }
1994         return false;
1995     }
1996 
1997     /**
1998      * Returns an array containing {@code Class} objects representing all
1999      * the public classes and interfaces that are members of the class
2000      * represented by this {@code Class} object.  This includes public
2001      * class and interface members inherited from superclasses and public class
2002      * and interface members declared by the class.  This method returns an
2003      * array of length 0 if this {@code Class} object has no public member
2004      * classes or interfaces.  This method also returns an array of length 0 if
2005      * this {@code Class} object represents a primitive type, an array
2006      * class, or void.
2007      *
2008      * @return the array of {@code Class} objects representing the public
2009      *         members of this class
2010      * @throws SecurityException
2011      *         If a security manager, <i>s</i>, is present and
2012      *         the caller's class loader is not the same as or an
2013      *         ancestor of the class loader for the current class and
2014      *         invocation of {@link SecurityManager#checkPackageAccess
2015      *         s.checkPackageAccess()} denies access to the package
2016      *         of this class.
2017      *
2018      * @since 1.1
2019      */
2020     @SuppressWarnings("removal")
2021     @CallerSensitive
2022     public Class<?>[] getClasses() {
2023         SecurityManager sm = System.getSecurityManager();
2024         if (sm != null) {
2025             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false);
2026         }
2027 
2028         // Privileged so this implementation can look at DECLARED classes,
2029         // something the caller might not have privilege to do.  The code here
2030         // is allowed to look at DECLARED classes because (1) it does not hand
2031         // out anything other than public members and (2) public member access
2032         // has already been ok'd by the SecurityManager.
2033 
2034         return java.security.AccessController.doPrivileged(
2035             new java.security.PrivilegedAction<>() {
2036                 public Class<?>[] run() {
2037                     List<Class<?>> list = new ArrayList<>();
2038                     Class<?> currentClass = Class.this;
2039                     while (currentClass != null) {
2040                         for (Class<?> m : currentClass.getDeclaredClasses()) {
2041                             if (Modifier.isPublic(m.getModifiers())) {
2042                                 list.add(m);
2043                             }
2044                         }
2045                         currentClass = currentClass.getSuperclass();
2046                     }
2047                     return list.toArray(new Class<?>[0]);
2048                 }
2049             });
2050     }
2051 
2052 
2053     /**
2054      * Returns an array containing {@code Field} objects reflecting all
2055      * the accessible public fields of the class or interface represented by
2056      * this {@code Class} object.
2057      *
2058      * <p> If this {@code Class} object represents a class or interface with
2059      * no accessible public fields, then this method returns an array of length
2060      * 0.
2061      *
2062      * <p> If this {@code Class} object represents a class, then this method
2063      * returns the public fields of the class and of all its superclasses and
2064      * superinterfaces.
2065      *
2066      * <p> If this {@code Class} object represents an interface, then this
2067      * method returns the fields of the interface and of all its
2068      * superinterfaces.
2069      *
2070      * <p> If this {@code Class} object represents an array type, a primitive
2071      * type, or void, then this method returns an array of length 0.
2072      *
2073      * <p> The elements in the returned array are not sorted and are not in any
2074      * particular order.
2075      *
2076      * @return the array of {@code Field} objects representing the
2077      *         public fields
2078      * @throws SecurityException
2079      *         If a security manager, <i>s</i>, is present and
2080      *         the caller's class loader is not the same as or an
2081      *         ancestor of the class loader for the current class and
2082      *         invocation of {@link SecurityManager#checkPackageAccess
2083      *         s.checkPackageAccess()} denies access to the package
2084      *         of this class.
2085      *
2086      * @since 1.1
2087      * @jls 8.2 Class Members
2088      * @jls 8.3 Field Declarations
2089      */
2090     @CallerSensitive
2091     public Field[] getFields() throws SecurityException {
2092         @SuppressWarnings("removal")
2093         SecurityManager sm = System.getSecurityManager();
2094         if (sm != null) {
2095             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
2096         }
2097         return copyFields(privateGetPublicFields());
2098     }
2099 
2100 
2101     /**
2102      * Returns an array containing {@code Method} objects reflecting all the
2103      * public methods of the class or interface represented by this {@code
2104      * Class} object, including those declared by the class or interface and
2105      * those inherited from superclasses and superinterfaces.
2106      *
2107      * <p> If this {@code Class} object represents an array type, then the
2108      * returned array has a {@code Method} object for each of the public
2109      * methods inherited by the array type from {@code Object}. It does not
2110      * contain a {@code Method} object for {@code clone()}.
2111      *
2112      * <p> If this {@code Class} object represents an interface then the
2113      * returned array does not contain any implicitly declared methods from
2114      * {@code Object}. Therefore, if no methods are explicitly declared in
2115      * this interface or any of its superinterfaces then the returned array
2116      * has length 0. (Note that a {@code Class} object which represents a class
2117      * always has public methods, inherited from {@code Object}.)
2118      *
2119      * <p> The returned array never contains methods with names "{@code <init>}"
2120      * or "{@code <clinit>}".
2121      *
2122      * <p> The elements in the returned array are not sorted and are not in any
2123      * particular order.
2124      *
2125      * <p> Generally, the result is computed as with the following 4 step algorithm.
2126      * Let C be the class or interface represented by this {@code Class} object:
2127      * <ol>
2128      * <li> A union of methods is composed of:
2129      *   <ol type="a">
2130      *   <li> C's declared public instance and static methods as returned by
2131      *        {@link #getDeclaredMethods()} and filtered to include only public
2132      *        methods.</li>
2133      *   <li> If C is a class other than {@code Object}, then include the result
2134      *        of invoking this algorithm recursively on the superclass of C.</li>
2135      *   <li> Include the results of invoking this algorithm recursively on all
2136      *        direct superinterfaces of C, but include only instance methods.</li>
2137      *   </ol></li>
2138      * <li> Union from step 1 is partitioned into subsets of methods with same
2139      *      signature (name, parameter types) and return type.</li>
2140      * <li> Within each such subset only the most specific methods are selected.
2141      *      Let method M be a method from a set of methods with same signature
2142      *      and return type. M is most specific if there is no such method
2143      *      N != M from the same set, such that N is more specific than M.
2144      *      N is more specific than M if:
2145      *   <ol type="a">
2146      *   <li> N is declared by a class and M is declared by an interface; or</li>
2147      *   <li> N and M are both declared by classes or both by interfaces and
2148      *        N's declaring type is the same as or a subtype of M's declaring type
2149      *        (clearly, if M's and N's declaring types are the same type, then
2150      *        M and N are the same method).</li>
2151      *   </ol></li>
2152      * <li> The result of this algorithm is the union of all selected methods from
2153      *      step 3.</li>
2154      * </ol>
2155      *
2156      * @apiNote There may be more than one method with a particular name
2157      * and parameter types in a class because while the Java language forbids a
2158      * class to declare multiple methods with the same signature but different
2159      * return types, the Java virtual machine does not.  This
2160      * increased flexibility in the virtual machine can be used to
2161      * implement various language features.  For example, covariant
2162      * returns can be implemented with {@linkplain
2163      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
2164      * method and the overriding method would have the same
2165      * signature but different return types.
2166      *
2167      * @return the array of {@code Method} objects representing the
2168      *         public methods of this class
2169      * @throws SecurityException
2170      *         If a security manager, <i>s</i>, is present and
2171      *         the caller's class loader is not the same as or an
2172      *         ancestor of the class loader for the current class and
2173      *         invocation of {@link SecurityManager#checkPackageAccess
2174      *         s.checkPackageAccess()} denies access to the package
2175      *         of this class.
2176      *
2177      * @jls 8.2 Class Members
2178      * @jls 8.4 Method Declarations
2179      * @since 1.1
2180      */
2181     @CallerSensitive
2182     public Method[] getMethods() throws SecurityException {
2183         @SuppressWarnings("removal")
2184         SecurityManager sm = System.getSecurityManager();
2185         if (sm != null) {
2186             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
2187         }
2188         return copyMethods(privateGetPublicMethods());
2189     }
2190 
2191 
2192     /**
2193      * Returns an array containing {@code Constructor} objects reflecting
2194      * all the public constructors of the class represented by this
2195      * {@code Class} object.  An array of length 0 is returned if the
2196      * class has no public constructors, or if the class is an array class, or
2197      * if the class reflects a primitive type or void.
2198      *
2199      * @apiNote
2200      * While this method returns an array of {@code
2201      * Constructor<T>} objects (that is an array of constructors from
2202      * this class), the return type of this method is {@code
2203      * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
2204      * might be expected.  This less informative return type is
2205      * necessary since after being returned from this method, the
2206      * array could be modified to hold {@code Constructor} objects for
2207      * different classes, which would violate the type guarantees of
2208      * {@code Constructor<T>[]}.
2209      *
2210      * @return the array of {@code Constructor} objects representing the
2211      *         public constructors of this class
2212      * @throws SecurityException
2213      *         If a security manager, <i>s</i>, is present and
2214      *         the caller's class loader is not the same as or an
2215      *         ancestor of the class loader for the current class and
2216      *         invocation of {@link SecurityManager#checkPackageAccess
2217      *         s.checkPackageAccess()} denies access to the package
2218      *         of this class.
2219      *
2220      * @since 1.1
2221      */
2222     @CallerSensitive
2223     public Constructor<?>[] getConstructors() throws SecurityException {
2224         @SuppressWarnings("removal")
2225         SecurityManager sm = System.getSecurityManager();
2226         if (sm != null) {
2227             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
2228         }
2229         return copyConstructors(privateGetDeclaredConstructors(true));
2230     }
2231 
2232 
2233     /**
2234      * Returns a {@code Field} object that reflects the specified public member
2235      * field of the class or interface represented by this {@code Class}
2236      * object. The {@code name} parameter is a {@code String} specifying the
2237      * simple name of the desired field.
2238      *
2239      * <p> The field to be reflected is determined by the algorithm that
2240      * follows.  Let C be the class or interface represented by this {@code Class} object:
2241      *
2242      * <OL>
2243      * <LI> If C declares a public field with the name specified, that is the
2244      *      field to be reflected.</LI>
2245      * <LI> If no field was found in step 1 above, this algorithm is applied
2246      *      recursively to each direct superinterface of C. The direct
2247      *      superinterfaces are searched in the order they were declared.</LI>
2248      * <LI> If no field was found in steps 1 and 2 above, and C has a
2249      *      superclass S, then this algorithm is invoked recursively upon S.
2250      *      If C has no superclass, then a {@code NoSuchFieldException}
2251      *      is thrown.</LI>
2252      * </OL>
2253      *
2254      * <p> If this {@code Class} object represents an array type, then this
2255      * method does not find the {@code length} field of the array type.
2256      *
2257      * @param name the field name
2258      * @return the {@code Field} object of this class specified by
2259      *         {@code name}
2260      * @throws NoSuchFieldException if a field with the specified name is
2261      *         not found.
2262      * @throws NullPointerException if {@code name} is {@code null}
2263      * @throws SecurityException
2264      *         If a security manager, <i>s</i>, is present and
2265      *         the caller's class loader is not the same as or an
2266      *         ancestor of the class loader for the current class and
2267      *         invocation of {@link SecurityManager#checkPackageAccess
2268      *         s.checkPackageAccess()} denies access to the package
2269      *         of this class.
2270      *
2271      * @since 1.1
2272      * @jls 8.2 Class Members
2273      * @jls 8.3 Field Declarations
2274      */
2275     @CallerSensitive
2276     public Field getField(String name)
2277         throws NoSuchFieldException, SecurityException {
2278         Objects.requireNonNull(name);
2279         @SuppressWarnings("removal")
2280         SecurityManager sm = System.getSecurityManager();
2281         if (sm != null) {
2282             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
2283         }
2284         Field field = getField0(name);
2285         if (field == null) {
2286             throw new NoSuchFieldException(name);
2287         }
2288         return getReflectionFactory().copyField(field);
2289     }
2290 
2291 
2292     /**
2293      * Returns a {@code Method} object that reflects the specified public
2294      * member method of the class or interface represented by this
2295      * {@code Class} object. The {@code name} parameter is a
2296      * {@code String} specifying the simple name of the desired method. The
2297      * {@code parameterTypes} parameter is an array of {@code Class}
2298      * objects that identify the method's formal parameter types, in declared
2299      * order. If {@code parameterTypes} is {@code null}, it is
2300      * treated as if it were an empty array.
2301      *
2302      * <p> If this {@code Class} object represents an array type, then this
2303      * method finds any public method inherited by the array type from
2304      * {@code Object} except method {@code clone()}.
2305      *
2306      * <p> If this {@code Class} object represents an interface then this
2307      * method does not find any implicitly declared method from
2308      * {@code Object}. Therefore, if no methods are explicitly declared in
2309      * this interface or any of its superinterfaces, then this method does not
2310      * find any method.
2311      *
2312      * <p> This method does not find any method with name "{@code <init>}" or
2313      * "{@code <clinit>}".
2314      *
2315      * <p> Generally, the method to be reflected is determined by the 4 step
2316      * algorithm that follows.
2317      * Let C be the class or interface represented by this {@code Class} object:
2318      * <ol>
2319      * <li> A union of methods is composed of:
2320      *   <ol type="a">
2321      *   <li> C's declared public instance and static methods as returned by
2322      *        {@link #getDeclaredMethods()} and filtered to include only public
2323      *        methods that match given {@code name} and {@code parameterTypes}</li>
2324      *   <li> If C is a class other than {@code Object}, then include the result
2325      *        of invoking this algorithm recursively on the superclass of C.</li>
2326      *   <li> Include the results of invoking this algorithm recursively on all
2327      *        direct superinterfaces of C, but include only instance methods.</li>
2328      *   </ol></li>
2329      * <li> This union is partitioned into subsets of methods with same
2330      *      return type (the selection of methods from step 1 also guarantees that
2331      *      they have the same method name and parameter types).</li>
2332      * <li> Within each such subset only the most specific methods are selected.
2333      *      Let method M be a method from a set of methods with same VM
2334      *      signature (return type, name, parameter types).
2335      *      M is most specific if there is no such method N != M from the same
2336      *      set, such that N is more specific than M. N is more specific than M
2337      *      if:
2338      *   <ol type="a">
2339      *   <li> N is declared by a class and M is declared by an interface; or</li>
2340      *   <li> N and M are both declared by classes or both by interfaces and
2341      *        N's declaring type is the same as or a subtype of M's declaring type
2342      *        (clearly, if M's and N's declaring types are the same type, then
2343      *        M and N are the same method).</li>
2344      *   </ol></li>
2345      * <li> The result of this algorithm is chosen arbitrarily from the methods
2346      *      with most specific return type among all selected methods from step 3.
2347      *      Let R be a return type of a method M from the set of all selected methods
2348      *      from step 3. M is a method with most specific return type if there is
2349      *      no such method N != M from the same set, having return type S != R,
2350      *      such that S is a subtype of R as determined by
2351      *      R.class.{@link #isAssignableFrom}(S.class).
2352      * </ol>
2353      *
2354      * @apiNote There may be more than one method with matching name and
2355      * parameter types in a class because while the Java language forbids a
2356      * class to declare multiple methods with the same signature but different
2357      * return types, the Java virtual machine does not.  This
2358      * increased flexibility in the virtual machine can be used to
2359      * implement various language features.  For example, covariant
2360      * returns can be implemented with {@linkplain
2361      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
2362      * method and the overriding method would have the same
2363      * signature but different return types. This method would return the
2364      * overriding method as it would have a more specific return type.
2365      *
2366      * @param name the name of the method
2367      * @param parameterTypes the list of parameters
2368      * @return the {@code Method} object that matches the specified
2369      *         {@code name} and {@code parameterTypes}
2370      * @throws NoSuchMethodException if a matching method is not found
2371      *         or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
2372      * @throws NullPointerException if {@code name} is {@code null}
2373      * @throws SecurityException
2374      *         If a security manager, <i>s</i>, is present and
2375      *         the caller's class loader is not the same as or an
2376      *         ancestor of the class loader for the current class and
2377      *         invocation of {@link SecurityManager#checkPackageAccess
2378      *         s.checkPackageAccess()} denies access to the package
2379      *         of this class.
2380      *
2381      * @jls 8.2 Class Members
2382      * @jls 8.4 Method Declarations
2383      * @since 1.1
2384      */
2385     @CallerSensitive
2386     public Method getMethod(String name, Class<?>... parameterTypes)
2387         throws NoSuchMethodException, SecurityException {
2388         Objects.requireNonNull(name);
2389         @SuppressWarnings("removal")
2390         SecurityManager sm = System.getSecurityManager();
2391         if (sm != null) {
2392             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
2393         }
2394         Method method = getMethod0(name, parameterTypes);
2395         if (method == null) {
2396             throw new NoSuchMethodException(methodToString(name, parameterTypes));
2397         }
2398         return getReflectionFactory().copyMethod(method);
2399     }
2400 
2401     /**
2402      * Returns a {@code Constructor} object that reflects the specified
2403      * public constructor of the class represented by this {@code Class}
2404      * object. The {@code parameterTypes} parameter is an array of
2405      * {@code Class} objects that identify the constructor's formal
2406      * parameter types, in declared order.
2407      *
2408      * If this {@code Class} object represents an inner class
2409      * declared in a non-static context, the formal parameter types
2410      * include the explicit enclosing instance as the first parameter.
2411      *
2412      * <p> The constructor to reflect is the public constructor of the class
2413      * represented by this {@code Class} object whose formal parameter
2414      * types match those specified by {@code parameterTypes}.
2415      *
2416      * @param parameterTypes the parameter array
2417      * @return the {@code Constructor} object of the public constructor that
2418      *         matches the specified {@code parameterTypes}
2419      * @throws NoSuchMethodException if a matching method is not found.
2420      * @throws SecurityException
2421      *         If a security manager, <i>s</i>, is present and
2422      *         the caller's class loader is not the same as or an
2423      *         ancestor of the class loader for the current class and
2424      *         invocation of {@link SecurityManager#checkPackageAccess
2425      *         s.checkPackageAccess()} denies access to the package
2426      *         of this class.
2427      *
2428      * @since 1.1
2429      */
2430     @CallerSensitive
2431     public Constructor<T> getConstructor(Class<?>... parameterTypes)
2432         throws NoSuchMethodException, SecurityException
2433     {
2434         @SuppressWarnings("removal")
2435         SecurityManager sm = System.getSecurityManager();
2436         if (sm != null) {
2437             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
2438         }
2439         return getReflectionFactory().copyConstructor(
2440             getConstructor0(parameterTypes, Member.PUBLIC));
2441     }
2442 
2443 
2444     /**
2445      * Returns an array of {@code Class} objects reflecting all the
2446      * classes and interfaces declared as members of the class represented by
2447      * this {@code Class} object. This includes public, protected, default
2448      * (package) access, and private classes and interfaces declared by the
2449      * class, but excludes inherited classes and interfaces.  This method
2450      * returns an array of length 0 if the class declares no classes or
2451      * interfaces as members, or if this {@code Class} object represents a
2452      * primitive type, an array class, or void.
2453      *
2454      * @return the array of {@code Class} objects representing all the
2455      *         declared members of this class
2456      * @throws SecurityException
2457      *         If a security manager, <i>s</i>, is present and any of the
2458      *         following conditions is met:
2459      *
2460      *         <ul>
2461      *
2462      *         <li> the caller's class loader is not the same as the
2463      *         class loader of this class and invocation of
2464      *         {@link SecurityManager#checkPermission
2465      *         s.checkPermission} method with
2466      *         {@code RuntimePermission("accessDeclaredMembers")}
2467      *         denies access to the declared classes within this class
2468      *
2469      *         <li> the caller's class loader is not the same as or an
2470      *         ancestor of the class loader for the current class and
2471      *         invocation of {@link SecurityManager#checkPackageAccess
2472      *         s.checkPackageAccess()} denies access to the package
2473      *         of this class
2474      *
2475      *         </ul>
2476      *
2477      * @since 1.1
2478      * @jls 8.5 Member Type Declarations
2479      */
2480     @CallerSensitive
2481     public Class<?>[] getDeclaredClasses() throws SecurityException {
2482         @SuppressWarnings("removal")
2483         SecurityManager sm = System.getSecurityManager();
2484         if (sm != null) {
2485             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), false);
2486         }
2487         return getDeclaredClasses0();
2488     }
2489 
2490 
2491     /**
2492      * Returns an array of {@code Field} objects reflecting all the fields
2493      * declared by the class or interface represented by this
2494      * {@code Class} object. This includes public, protected, default
2495      * (package) access, and private fields, but excludes inherited fields.
2496      *
2497      * <p> If this {@code Class} object represents a class or interface with no
2498      * declared fields, then this method returns an array of length 0.
2499      *
2500      * <p> If this {@code Class} object represents an array type, a primitive
2501      * type, or void, then this method returns an array of length 0.
2502      *
2503      * <p> The elements in the returned array are not sorted and are not in any
2504      * particular order.
2505      *
2506      * @return  the array of {@code Field} objects representing all the
2507      *          declared fields of this class
2508      * @throws  SecurityException
2509      *          If a security manager, <i>s</i>, is present and any of the
2510      *          following conditions is met:
2511      *
2512      *          <ul>
2513      *
2514      *          <li> the caller's class loader is not the same as the
2515      *          class loader of this class and invocation of
2516      *          {@link SecurityManager#checkPermission
2517      *          s.checkPermission} method with
2518      *          {@code RuntimePermission("accessDeclaredMembers")}
2519      *          denies access to the declared fields within this class
2520      *
2521      *          <li> the caller's class loader is not the same as or an
2522      *          ancestor of the class loader for the current class and
2523      *          invocation of {@link SecurityManager#checkPackageAccess
2524      *          s.checkPackageAccess()} denies access to the package
2525      *          of this class
2526      *
2527      *          </ul>
2528      *
2529      * @since 1.1
2530      * @jls 8.2 Class Members
2531      * @jls 8.3 Field Declarations
2532      */
2533     @CallerSensitive
2534     public Field[] getDeclaredFields() throws SecurityException {
2535         @SuppressWarnings("removal")
2536         SecurityManager sm = System.getSecurityManager();
2537         if (sm != null) {
2538             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2539         }
2540         return copyFields(privateGetDeclaredFields(false));
2541     }
2542 
2543     /**
2544      * Returns an array of {@code RecordComponent} objects representing all the
2545      * record components of this record class, or {@code null} if this class is
2546      * not a record class.
2547      *
2548      * <p> The components are returned in the same order that they are declared
2549      * in the record header. The array is empty if this record class has no
2550      * components. If the class is not a record class, that is {@link
2551      * #isRecord()} returns {@code false}, then this method returns {@code null}.
2552      * Conversely, if {@link #isRecord()} returns {@code true}, then this method
2553      * returns a non-null value.
2554      *
2555      * @apiNote
2556      * <p> The following method can be used to find the record canonical constructor:
2557      *
2558      * <pre>{@code
2559      * static <T extends Record> Constructor<T> getCanonicalConstructor(Class<T> cls)
2560      *     throws NoSuchMethodException {
2561      *   Class<?>[] paramTypes =
2562      *     Arrays.stream(cls.getRecordComponents())
2563      *           .map(RecordComponent::getType)
2564      *           .toArray(Class<?>[]::new);
2565      *   return cls.getDeclaredConstructor(paramTypes);
2566      * }}</pre>
2567      *
2568      * @return  An array of {@code RecordComponent} objects representing all the
2569      *          record components of this record class, or {@code null} if this
2570      *          class is not a record class
2571      * @throws  SecurityException
2572      *          If a security manager, <i>s</i>, is present and any of the
2573      *          following conditions is met:
2574      *
2575      *          <ul>
2576      *
2577      *          <li> the caller's class loader is not the same as the
2578      *          class loader of this class and invocation of
2579      *          {@link SecurityManager#checkPermission
2580      *          s.checkPermission} method with
2581      *          {@code RuntimePermission("accessDeclaredMembers")}
2582      *          denies access to the declared methods within this class
2583      *
2584      *          <li> the caller's class loader is not the same as or an
2585      *          ancestor of the class loader for the current class and
2586      *          invocation of {@link SecurityManager#checkPackageAccess
2587      *          s.checkPackageAccess()} denies access to the package
2588      *          of this class
2589      *
2590      *          </ul>
2591      *
2592      * @jls 8.10 Record Classes
2593      * @since 16
2594      */
2595     @CallerSensitive
2596     public RecordComponent[] getRecordComponents() {
2597         @SuppressWarnings("removal")
2598         SecurityManager sm = System.getSecurityManager();
2599         if (sm != null) {
2600             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2601         }
2602         if (!isRecord()) {
2603             return null;
2604         }
2605         return getRecordComponents0();
2606     }
2607 
2608     /**
2609      * Returns an array containing {@code Method} objects reflecting all the
2610      * declared methods of the class or interface represented by this {@code
2611      * Class} object, including public, protected, default (package)
2612      * access, and private methods, but excluding inherited methods.
2613      * The declared methods may include methods <em>not</em> in the
2614      * source of the class or interface, including {@linkplain
2615      * Method#isBridge bridge methods} and other {@linkplain
2616      * Executable#isSynthetic synthetic} methods added by compilers.
2617      *
2618      * <p> If this {@code Class} object represents a class or interface that
2619      * has multiple declared methods with the same name and parameter types,
2620      * but different return types, then the returned array has a {@code Method}
2621      * object for each such method.
2622      *
2623      * <p> If this {@code Class} object represents a class or interface that
2624      * has a class initialization method {@code <clinit>}, then the returned
2625      * array does <em>not</em> have a corresponding {@code Method} object.
2626      *
2627      * <p> If this {@code Class} object represents a class or interface with no
2628      * declared methods, then the returned array has length 0.
2629      *
2630      * <p> If this {@code Class} object represents an array type, a primitive
2631      * type, or void, then the returned array has length 0.
2632      *
2633      * <p> The elements in the returned array are not sorted and are not in any
2634      * particular order.
2635      *
2636      * @return  the array of {@code Method} objects representing all the
2637      *          declared methods of this class
2638      * @throws  SecurityException
2639      *          If a security manager, <i>s</i>, is present and any of the
2640      *          following conditions is met:
2641      *
2642      *          <ul>
2643      *
2644      *          <li> the caller's class loader is not the same as the
2645      *          class loader of this class and invocation of
2646      *          {@link SecurityManager#checkPermission
2647      *          s.checkPermission} method with
2648      *          {@code RuntimePermission("accessDeclaredMembers")}
2649      *          denies access to the declared methods within this class
2650      *
2651      *          <li> the caller's class loader is not the same as or an
2652      *          ancestor of the class loader for the current class and
2653      *          invocation of {@link SecurityManager#checkPackageAccess
2654      *          s.checkPackageAccess()} denies access to the package
2655      *          of this class
2656      *
2657      *          </ul>
2658      *
2659      * @jls 8.2 Class Members
2660      * @jls 8.4 Method Declarations
2661      * @see <a
2662      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
2663      * programming language and JVM modeling in core reflection</a>
2664      * @since 1.1
2665      */
2666     @CallerSensitive
2667     public Method[] getDeclaredMethods() throws SecurityException {
2668         @SuppressWarnings("removal")
2669         SecurityManager sm = System.getSecurityManager();
2670         if (sm != null) {
2671             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2672         }
2673         return copyMethods(privateGetDeclaredMethods(false));
2674     }
2675 
2676 
2677     /**
2678      * Returns an array of {@code Constructor} objects reflecting all the
2679      * constructors declared by the class represented by this
2680      * {@code Class} object. These are public, protected, default
2681      * (package) access, and private constructors.  The elements in the array
2682      * returned are not sorted and are not in any particular order.  If the
2683      * class has a default constructor, it is included in the returned array.
2684      * This method returns an array of length 0 if this {@code Class}
2685      * object represents an interface, a primitive type, an array class, or
2686      * void.
2687      *
2688      * <p> See <cite>The Java Language Specification</cite>,
2689      * section {@jls 8.2}.
2690      *
2691      * @return  the array of {@code Constructor} objects representing all the
2692      *          declared constructors of this class
2693      * @throws  SecurityException
2694      *          If a security manager, <i>s</i>, is present and any of the
2695      *          following conditions is met:
2696      *
2697      *          <ul>
2698      *
2699      *          <li> the caller's class loader is not the same as the
2700      *          class loader of this class and invocation of
2701      *          {@link SecurityManager#checkPermission
2702      *          s.checkPermission} method with
2703      *          {@code RuntimePermission("accessDeclaredMembers")}
2704      *          denies access to the declared constructors within this class
2705      *
2706      *          <li> the caller's class loader is not the same as or an
2707      *          ancestor of the class loader for the current class and
2708      *          invocation of {@link SecurityManager#checkPackageAccess
2709      *          s.checkPackageAccess()} denies access to the package
2710      *          of this class
2711      *
2712      *          </ul>
2713      *
2714      * @since 1.1
2715      * @jls 8.8 Constructor Declarations
2716      */
2717     @CallerSensitive
2718     public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
2719         @SuppressWarnings("removal")
2720         SecurityManager sm = System.getSecurityManager();
2721         if (sm != null) {
2722             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2723         }
2724         return copyConstructors(privateGetDeclaredConstructors(false));
2725     }
2726 
2727 
2728     /**
2729      * Returns a {@code Field} object that reflects the specified declared
2730      * field of the class or interface represented by this {@code Class}
2731      * object. The {@code name} parameter is a {@code String} that specifies
2732      * the simple name of the desired field.
2733      *
2734      * <p> If this {@code Class} object represents an array type, then this
2735      * method does not find the {@code length} field of the array type.
2736      *
2737      * @param name the name of the field
2738      * @return  the {@code Field} object for the specified field in this
2739      *          class
2740      * @throws  NoSuchFieldException if a field with the specified name is
2741      *          not found.
2742      * @throws  NullPointerException if {@code name} is {@code null}
2743      * @throws  SecurityException
2744      *          If a security manager, <i>s</i>, is present and any of the
2745      *          following conditions is met:
2746      *
2747      *          <ul>
2748      *
2749      *          <li> the caller's class loader is not the same as the
2750      *          class loader of this class and invocation of
2751      *          {@link SecurityManager#checkPermission
2752      *          s.checkPermission} method with
2753      *          {@code RuntimePermission("accessDeclaredMembers")}
2754      *          denies access to the declared field
2755      *
2756      *          <li> the caller's class loader is not the same as or an
2757      *          ancestor of the class loader for the current class and
2758      *          invocation of {@link SecurityManager#checkPackageAccess
2759      *          s.checkPackageAccess()} denies access to the package
2760      *          of this class
2761      *
2762      *          </ul>
2763      *
2764      * @since 1.1
2765      * @jls 8.2 Class Members
2766      * @jls 8.3 Field Declarations
2767      */
2768     @CallerSensitive
2769     public Field getDeclaredField(String name)
2770         throws NoSuchFieldException, SecurityException {
2771         Objects.requireNonNull(name);
2772         @SuppressWarnings("removal")
2773         SecurityManager sm = System.getSecurityManager();
2774         if (sm != null) {
2775             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2776         }
2777         Field field = searchFields(privateGetDeclaredFields(false), name);
2778         if (field == null) {
2779             throw new NoSuchFieldException(name);
2780         }
2781         return getReflectionFactory().copyField(field);
2782     }
2783 
2784 
2785     /**
2786      * Returns a {@code Method} object that reflects the specified
2787      * declared method of the class or interface represented by this
2788      * {@code Class} object. The {@code name} parameter is a
2789      * {@code String} that specifies the simple name of the desired
2790      * method, and the {@code parameterTypes} parameter is an array of
2791      * {@code Class} objects that identify the method's formal parameter
2792      * types, in declared order.  If more than one method with the same
2793      * parameter types is declared in a class, and one of these methods has a
2794      * return type that is more specific than any of the others, that method is
2795      * returned; otherwise one of the methods is chosen arbitrarily.  If the
2796      * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
2797      * is raised.
2798      *
2799      * <p> If this {@code Class} object represents an array type, then this
2800      * method does not find the {@code clone()} method.
2801      *
2802      * @param name the name of the method
2803      * @param parameterTypes the parameter array
2804      * @return  the {@code Method} object for the method of this class
2805      *          matching the specified name and parameters
2806      * @throws  NoSuchMethodException if a matching method is not found.
2807      * @throws  NullPointerException if {@code name} is {@code null}
2808      * @throws  SecurityException
2809      *          If a security manager, <i>s</i>, is present and any of the
2810      *          following conditions is met:
2811      *
2812      *          <ul>
2813      *
2814      *          <li> the caller's class loader is not the same as the
2815      *          class loader of this class and invocation of
2816      *          {@link SecurityManager#checkPermission
2817      *          s.checkPermission} method with
2818      *          {@code RuntimePermission("accessDeclaredMembers")}
2819      *          denies access to the declared method
2820      *
2821      *          <li> the caller's class loader is not the same as or an
2822      *          ancestor of the class loader for the current class and
2823      *          invocation of {@link SecurityManager#checkPackageAccess
2824      *          s.checkPackageAccess()} denies access to the package
2825      *          of this class
2826      *
2827      *          </ul>
2828      *
2829      * @jls 8.2 Class Members
2830      * @jls 8.4 Method Declarations
2831      * @since 1.1
2832      */
2833     @CallerSensitive
2834     public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2835         throws NoSuchMethodException, SecurityException {
2836         Objects.requireNonNull(name);
2837         @SuppressWarnings("removal")
2838         SecurityManager sm = System.getSecurityManager();
2839         if (sm != null) {
2840             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2841         }
2842         Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
2843         if (method == null) {
2844             throw new NoSuchMethodException(methodToString(name, parameterTypes));
2845         }
2846         return getReflectionFactory().copyMethod(method);
2847     }
2848 
2849     /**
2850      * Returns the list of {@code Method} objects for the declared public
2851      * methods of this class or interface that have the specified method name
2852      * and parameter types.
2853      *
2854      * @param name the name of the method
2855      * @param parameterTypes the parameter array
2856      * @return the list of {@code Method} objects for the public methods of
2857      *         this class matching the specified name and parameters
2858      */
2859     List<Method> getDeclaredPublicMethods(String name, Class<?>... parameterTypes) {
2860         Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);
2861         ReflectionFactory factory = getReflectionFactory();
2862         List<Method> result = new ArrayList<>();
2863         for (Method method : methods) {
2864             if (method.getName().equals(name)
2865                 && Arrays.equals(
2866                     factory.getExecutableSharedParameterTypes(method),
2867                     parameterTypes)) {
2868                 result.add(factory.copyMethod(method));
2869             }
2870         }
2871         return result;
2872     }
2873 
2874     /**
2875      * Returns a {@code Constructor} object that reflects the specified
2876      * constructor of the class or interface represented by this
2877      * {@code Class} object.  The {@code parameterTypes} parameter is
2878      * an array of {@code Class} objects that identify the constructor's
2879      * formal parameter types, in declared order.
2880      *
2881      * If this {@code Class} object represents an inner class
2882      * declared in a non-static context, the formal parameter types
2883      * include the explicit enclosing instance as the first parameter.
2884      *
2885      * @param parameterTypes the parameter array
2886      * @return  The {@code Constructor} object for the constructor with the
2887      *          specified parameter list
2888      * @throws  NoSuchMethodException if a matching method is not found.
2889      * @throws  SecurityException
2890      *          If a security manager, <i>s</i>, is present and any of the
2891      *          following conditions is met:
2892      *
2893      *          <ul>
2894      *
2895      *          <li> the caller's class loader is not the same as the
2896      *          class loader of this class and invocation of
2897      *          {@link SecurityManager#checkPermission
2898      *          s.checkPermission} method with
2899      *          {@code RuntimePermission("accessDeclaredMembers")}
2900      *          denies access to the declared constructor
2901      *
2902      *          <li> the caller's class loader is not the same as or an
2903      *          ancestor of the class loader for the current class and
2904      *          invocation of {@link SecurityManager#checkPackageAccess
2905      *          s.checkPackageAccess()} denies access to the package
2906      *          of this class
2907      *
2908      *          </ul>
2909      *
2910      * @since 1.1
2911      */
2912     @CallerSensitive
2913     public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
2914         throws NoSuchMethodException, SecurityException
2915     {
2916         @SuppressWarnings("removal")
2917         SecurityManager sm = System.getSecurityManager();
2918         if (sm != null) {
2919             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2920         }
2921 
2922         return getReflectionFactory().copyConstructor(
2923             getConstructor0(parameterTypes, Member.DECLARED));
2924     }
2925 
2926     /**
2927      * Finds a resource with a given name.
2928      *
2929      * <p> If this class is in a named {@link Module Module} then this method
2930      * will attempt to find the resource in the module. This is done by
2931      * delegating to the module's class loader {@link
2932      * ClassLoader#findResource(String,String) findResource(String,String)}
2933      * method, invoking it with the module name and the absolute name of the
2934      * resource. Resources in named modules are subject to the rules for
2935      * encapsulation specified in the {@code Module} {@link
2936      * Module#getResourceAsStream getResourceAsStream} method and so this
2937      * method returns {@code null} when the resource is a
2938      * non-"{@code .class}" resource in a package that is not open to the
2939      * caller's module.
2940      *
2941      * <p> Otherwise, if this class is not in a named module then the rules for
2942      * searching resources associated with a given class are implemented by the
2943      * defining {@linkplain ClassLoader class loader} of the class.  This method
2944      * delegates to this {@code Class} object's class loader.
2945      * If this {@code Class} object was loaded by the bootstrap class loader,
2946      * the method delegates to {@link ClassLoader#getSystemResourceAsStream}.
2947      *
2948      * <p> Before delegation, an absolute resource name is constructed from the
2949      * given resource name using this algorithm:
2950      *
2951      * <ul>
2952      *
2953      * <li> If the {@code name} begins with a {@code '/'}
2954      * (<code>'&#92;u002f'</code>), then the absolute name of the resource is the
2955      * portion of the {@code name} following the {@code '/'}.
2956      *
2957      * <li> Otherwise, the absolute name is of the following form:
2958      *
2959      * <blockquote>
2960      *   {@code modified_package_name/name}
2961      * </blockquote>
2962      *
2963      * <p> Where the {@code modified_package_name} is the package name of this
2964      * object with {@code '/'} substituted for {@code '.'}
2965      * (<code>'&#92;u002e'</code>).
2966      *
2967      * </ul>
2968      *
2969      * @param  name name of the desired resource
2970      * @return  A {@link java.io.InputStream} object; {@code null} if no
2971      *          resource with this name is found, the resource is in a package
2972      *          that is not {@linkplain Module#isOpen(String, Module) open} to at
2973      *          least the caller module, or access to the resource is denied
2974      *          by the security manager.
2975      * @throws  NullPointerException If {@code name} is {@code null}
2976      *
2977      * @see Module#getResourceAsStream(String)
2978      * @since  1.1
2979      * @revised 9
2980      */
2981     @CallerSensitive
2982     public InputStream getResourceAsStream(String name) {
2983         name = resolveName(name);
2984 
2985         Module thisModule = getModule();
2986         if (thisModule.isNamed()) {
2987             // check if resource can be located by caller
2988             if (Resources.canEncapsulate(name)
2989                 && !isOpenToCaller(name, Reflection.getCallerClass())) {
2990                 return null;
2991             }
2992 
2993             // resource not encapsulated or in package open to caller
2994             String mn = thisModule.getName();
2995             ClassLoader cl = classLoader;
2996             try {
2997 
2998                 // special-case built-in class loaders to avoid the
2999                 // need for a URL connection
3000                 if (cl == null) {
3001                     return BootLoader.findResourceAsStream(mn, name);
3002                 } else if (cl instanceof BuiltinClassLoader) {
3003                     return ((BuiltinClassLoader) cl).findResourceAsStream(mn, name);
3004                 } else {
3005                     URL url = cl.findResource(mn, name);
3006                     return (url != null) ? url.openStream() : null;
3007                 }
3008 
3009             } catch (IOException | SecurityException e) {
3010                 return null;
3011             }
3012         }
3013 
3014         // unnamed module
3015         ClassLoader cl = classLoader;
3016         if (cl == null) {
3017             return ClassLoader.getSystemResourceAsStream(name);
3018         } else {
3019             return cl.getResourceAsStream(name);
3020         }
3021     }
3022 
3023     /**
3024      * Finds a resource with a given name.
3025      *
3026      * <p> If this class is in a named {@link Module Module} then this method
3027      * will attempt to find the resource in the module. This is done by
3028      * delegating to the module's class loader {@link
3029      * ClassLoader#findResource(String,String) findResource(String,String)}
3030      * method, invoking it with the module name and the absolute name of the
3031      * resource. Resources in named modules are subject to the rules for
3032      * encapsulation specified in the {@code Module} {@link
3033      * Module#getResourceAsStream getResourceAsStream} method and so this
3034      * method returns {@code null} when the resource is a
3035      * non-"{@code .class}" resource in a package that is not open to the
3036      * caller's module.
3037      *
3038      * <p> Otherwise, if this class is not in a named module then the rules for
3039      * searching resources associated with a given class are implemented by the
3040      * defining {@linkplain ClassLoader class loader} of the class.  This method
3041      * delegates to this {@code Class} object's class loader.
3042      * If this {@code Class} object was loaded by the bootstrap class loader,
3043      * the method delegates to {@link ClassLoader#getSystemResource}.
3044      *
3045      * <p> Before delegation, an absolute resource name is constructed from the
3046      * given resource name using this algorithm:
3047      *
3048      * <ul>
3049      *
3050      * <li> If the {@code name} begins with a {@code '/'}
3051      * (<code>'&#92;u002f'</code>), then the absolute name of the resource is the
3052      * portion of the {@code name} following the {@code '/'}.
3053      *
3054      * <li> Otherwise, the absolute name is of the following form:
3055      *
3056      * <blockquote>
3057      *   {@code modified_package_name/name}
3058      * </blockquote>
3059      *
3060      * <p> Where the {@code modified_package_name} is the package name of this
3061      * object with {@code '/'} substituted for {@code '.'}
3062      * (<code>'&#92;u002e'</code>).
3063      *
3064      * </ul>
3065      *
3066      * @param  name name of the desired resource
3067      * @return A {@link java.net.URL} object; {@code null} if no resource with
3068      *         this name is found, the resource cannot be located by a URL, the
3069      *         resource is in a package that is not
3070      *         {@linkplain Module#isOpen(String, Module) open} to at least the caller
3071      *         module, or access to the resource is denied by the security
3072      *         manager.
3073      * @throws NullPointerException If {@code name} is {@code null}
3074      * @since  1.1
3075      * @revised 9
3076      */
3077     @CallerSensitive
3078     public URL getResource(String name) {
3079         name = resolveName(name);
3080 
3081         Module thisModule = getModule();
3082         if (thisModule.isNamed()) {
3083             // check if resource can be located by caller
3084             if (Resources.canEncapsulate(name)
3085                 && !isOpenToCaller(name, Reflection.getCallerClass())) {
3086                 return null;
3087             }
3088 
3089             // resource not encapsulated or in package open to caller
3090             String mn = thisModule.getName();
3091             ClassLoader cl = classLoader;
3092             try {
3093                 if (cl == null) {
3094                     return BootLoader.findResource(mn, name);
3095                 } else {
3096                     return cl.findResource(mn, name);
3097                 }
3098             } catch (IOException ioe) {
3099                 return null;
3100             }
3101         }
3102 
3103         // unnamed module
3104         ClassLoader cl = classLoader;
3105         if (cl == null) {
3106             return ClassLoader.getSystemResource(name);
3107         } else {
3108             return cl.getResource(name);
3109         }
3110     }
3111 
3112     /**
3113      * Returns true if a resource with the given name can be located by the
3114      * given caller. All resources in a module can be located by code in
3115      * the module. For other callers, then the package needs to be open to
3116      * the caller.
3117      */
3118     private boolean isOpenToCaller(String name, Class<?> caller) {
3119         // assert getModule().isNamed();
3120         Module thisModule = getModule();
3121         Module callerModule = (caller != null) ? caller.getModule() : null;
3122         if (callerModule != thisModule) {
3123             String pn = Resources.toPackageName(name);
3124             if (thisModule.getDescriptor().packages().contains(pn)) {
3125                 if (callerModule == null && !thisModule.isOpen(pn)) {
3126                     // no caller, package not open
3127                     return false;
3128                 }
3129                 if (!thisModule.isOpen(pn, callerModule)) {
3130                     // package not open to caller
3131                     return false;
3132                 }
3133             }
3134         }
3135         return true;
3136     }
3137 
3138 
3139     /** protection domain returned when the internal domain is null */
3140     private static java.security.ProtectionDomain allPermDomain;
3141 
3142     /**
3143      * Returns the {@code ProtectionDomain} of this class.  If there is a
3144      * security manager installed, this method first calls the security
3145      * manager's {@code checkPermission} method with a
3146      * {@code RuntimePermission("getProtectionDomain")} permission to
3147      * ensure it's ok to get the
3148      * {@code ProtectionDomain}.
3149      *
3150      * @return the ProtectionDomain of this class
3151      *
3152      * @throws SecurityException
3153      *        if a security manager exists and its
3154      *        {@code checkPermission} method doesn't allow
3155      *        getting the ProtectionDomain.
3156      *
3157      * @see java.security.ProtectionDomain
3158      * @see SecurityManager#checkPermission
3159      * @see java.lang.RuntimePermission
3160      * @since 1.2
3161      */
3162     public java.security.ProtectionDomain getProtectionDomain() {
3163         @SuppressWarnings("removal")
3164         SecurityManager sm = System.getSecurityManager();
3165         if (sm != null) {
3166             sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
3167         }
3168         return protectionDomain();
3169     }
3170 
3171     // package-private
3172     java.security.ProtectionDomain protectionDomain() {
3173         java.security.ProtectionDomain pd = getProtectionDomain0();
3174         if (pd == null) {
3175             if (allPermDomain == null) {
3176                 java.security.Permissions perms =
3177                     new java.security.Permissions();
3178                 perms.add(SecurityConstants.ALL_PERMISSION);
3179                 allPermDomain =
3180                     new java.security.ProtectionDomain(null, perms);
3181             }
3182             pd = allPermDomain;
3183         }
3184         return pd;
3185     }
3186 
3187     /**
3188      * Returns the ProtectionDomain of this class.
3189      */
3190     private native java.security.ProtectionDomain getProtectionDomain0();
3191 
3192     /*
3193      * Return the Virtual Machine's Class object for the named
3194      * primitive type.
3195      */
3196     static native Class<?> getPrimitiveClass(String name);
3197 
3198     /*
3199      * Check if client is allowed to access members.  If access is denied,
3200      * throw a SecurityException.
3201      *
3202      * This method also enforces package access.
3203      *
3204      * <p> Default policy: allow all clients access with normal Java access
3205      * control.
3206      *
3207      * <p> NOTE: should only be called if a SecurityManager is installed
3208      */
3209     private void checkMemberAccess(@SuppressWarnings("removal") SecurityManager sm, int which,
3210                                    Class<?> caller, boolean checkProxyInterfaces) {
3211         /* Default policy allows access to all {@link Member#PUBLIC} members,
3212          * as well as access to classes that have the same class loader as the caller.
3213          * In all other cases, it requires RuntimePermission("accessDeclaredMembers")
3214          * permission.
3215          */
3216         final ClassLoader ccl = ClassLoader.getClassLoader(caller);
3217         if (which != Member.PUBLIC) {
3218             final ClassLoader cl = classLoader;
3219             if (ccl != cl) {
3220                 sm.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3221             }
3222         }
3223         this.checkPackageAccess(sm, ccl, checkProxyInterfaces);
3224     }
3225 
3226     /*
3227      * Checks if a client loaded in ClassLoader ccl is allowed to access this
3228      * class under the current package access policy. If access is denied,
3229      * throw a SecurityException.
3230      *
3231      * NOTE: this method should only be called if a SecurityManager is active
3232      */
3233     private void checkPackageAccess(@SuppressWarnings("removal") SecurityManager sm, final ClassLoader ccl,
3234                                     boolean checkProxyInterfaces) {
3235         final ClassLoader cl = classLoader;
3236 
3237         if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
3238             String pkg = this.getPackageName();
3239             if (!pkg.isEmpty()) {
3240                 // skip the package access check on a proxy class in default proxy package
3241                 if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {
3242                     sm.checkPackageAccess(pkg);
3243                 }
3244             }
3245         }
3246         // check package access on the proxy interfaces
3247         if (checkProxyInterfaces && Proxy.isProxyClass(this)) {
3248             ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());
3249         }
3250     }
3251 
3252     /*
3253      * Checks if a client loaded in ClassLoader ccl is allowed to access the provided
3254      * classes under the current package access policy. If access is denied,
3255      * throw a SecurityException.
3256      *
3257      * NOTE: this method should only be called if a SecurityManager is active
3258      *       classes must be non-empty
3259      *       all classes provided must be loaded by the same ClassLoader
3260      * NOTE: this method does not support Proxy classes
3261      */
3262     private static void checkPackageAccessForPermittedSubclasses(@SuppressWarnings("removal") SecurityManager sm,
3263                                     final ClassLoader ccl, Class<?>[] subClasses) {
3264         final ClassLoader cl = subClasses[0].classLoader;
3265 
3266         if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
3267             Set<String> packages = new HashSet<>();
3268 
3269             for (Class<?> c : subClasses) {
3270                 if (Proxy.isProxyClass(c))
3271                     throw new InternalError("a permitted subclass should not be a proxy class: " + c);
3272                 String pkg = c.getPackageName();
3273                 if (!pkg.isEmpty()) {
3274                     packages.add(pkg);
3275                 }
3276             }
3277             for (String pkg : packages) {
3278                 sm.checkPackageAccess(pkg);
3279             }
3280         }
3281     }
3282 
3283     /**
3284      * Add a package name prefix if the name is not absolute. Remove leading "/"
3285      * if name is absolute
3286      */
3287     private String resolveName(String name) {
3288         if (!name.startsWith("/")) {
3289             String baseName = getPackageName();
3290             if (!baseName.isEmpty()) {
3291                 int len = baseName.length() + 1 + name.length();
3292                 StringBuilder sb = new StringBuilder(len);
3293                 name = sb.append(baseName.replace('.', '/'))
3294                     .append('/')
3295                     .append(name)
3296                     .toString();
3297             }
3298         } else {
3299             name = name.substring(1);
3300         }
3301         return name;
3302     }
3303 
3304     /**
3305      * Atomic operations support.
3306      */
3307     private static class Atomic {
3308         // initialize Unsafe machinery here, since we need to call Class.class instance method
3309         // and have to avoid calling it in the static initializer of the Class class...
3310         private static final Unsafe unsafe = Unsafe.getUnsafe();
3311         // offset of Class.reflectionData instance field
3312         private static final long reflectionDataOffset
3313                 = unsafe.objectFieldOffset(Class.class, "reflectionData");
3314         // offset of Class.annotationType instance field
3315         private static final long annotationTypeOffset
3316                 = unsafe.objectFieldOffset(Class.class, "annotationType");
3317         // offset of Class.annotationData instance field
3318         private static final long annotationDataOffset
3319                 = unsafe.objectFieldOffset(Class.class, "annotationData");
3320 
3321         static <T> boolean casReflectionData(Class<?> clazz,
3322                                              SoftReference<ReflectionData<T>> oldData,
3323                                              SoftReference<ReflectionData<T>> newData) {
3324             return unsafe.compareAndSetReference(clazz, reflectionDataOffset, oldData, newData);
3325         }
3326 
3327         static boolean casAnnotationType(Class<?> clazz,
3328                                          AnnotationType oldType,
3329                                          AnnotationType newType) {
3330             return unsafe.compareAndSetReference(clazz, annotationTypeOffset, oldType, newType);
3331         }
3332 
3333         static boolean casAnnotationData(Class<?> clazz,
3334                                          AnnotationData oldData,
3335                                          AnnotationData newData) {
3336             return unsafe.compareAndSetReference(clazz, annotationDataOffset, oldData, newData);
3337         }
3338     }
3339 
3340     /**
3341      * Reflection support.
3342      */
3343 
3344     // Reflection data caches various derived names and reflective members. Cached
3345     // values may be invalidated when JVM TI RedefineClasses() is called
3346     private static class ReflectionData<T> {
3347         volatile Field[] declaredFields;
3348         volatile Field[] publicFields;
3349         volatile Method[] declaredMethods;
3350         volatile Method[] publicMethods;
3351         volatile Constructor<T>[] declaredConstructors;
3352         volatile Constructor<T>[] publicConstructors;
3353         // Intermediate results for getFields and getMethods
3354         volatile Field[] declaredPublicFields;
3355         volatile Method[] declaredPublicMethods;
3356         volatile Class<?>[] interfaces;
3357 
3358         // Cached names
3359         String simpleName;
3360         String canonicalName;
3361         static final String NULL_SENTINEL = new String();
3362 
3363         // Value of classRedefinedCount when we created this ReflectionData instance
3364         final int redefinedCount;
3365 
3366         ReflectionData(int redefinedCount) {
3367             this.redefinedCount = redefinedCount;
3368         }
3369     }
3370 
3371     private transient volatile SoftReference<ReflectionData<T>> reflectionData;
3372 
3373     // Incremented by the VM on each call to JVM TI RedefineClasses()
3374     // that redefines this class or a superclass.
3375     private transient volatile int classRedefinedCount;
3376 
3377     // Lazily create and cache ReflectionData
3378     private ReflectionData<T> reflectionData() {
3379         SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
3380         int classRedefinedCount = this.classRedefinedCount;
3381         ReflectionData<T> rd;
3382         if (reflectionData != null &&
3383             (rd = reflectionData.get()) != null &&
3384             rd.redefinedCount == classRedefinedCount) {
3385             return rd;
3386         }
3387         // else no SoftReference or cleared SoftReference or stale ReflectionData
3388         // -> create and replace new instance
3389         return newReflectionData(reflectionData, classRedefinedCount);
3390     }
3391 
3392     private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
3393                                                 int classRedefinedCount) {
3394         while (true) {
3395             ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
3396             // try to CAS it...
3397             if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
3398                 return rd;
3399             }
3400             // else retry
3401             oldReflectionData = this.reflectionData;
3402             classRedefinedCount = this.classRedefinedCount;
3403             if (oldReflectionData != null &&
3404                 (rd = oldReflectionData.get()) != null &&
3405                 rd.redefinedCount == classRedefinedCount) {
3406                 return rd;
3407             }
3408         }
3409     }
3410 
3411     // Generic signature handling
3412     private native String getGenericSignature0();
3413 
3414     // Generic info repository; lazily initialized
3415     private transient volatile ClassRepository genericInfo;
3416 
3417     // accessor for factory
3418     private GenericsFactory getFactory() {
3419         // create scope and factory
3420         return CoreReflectionFactory.make(this, ClassScope.make(this));
3421     }
3422 
3423     // accessor for generic info repository;
3424     // generic info is lazily initialized
3425     private ClassRepository getGenericInfo() {
3426         ClassRepository genericInfo = this.genericInfo;
3427         if (genericInfo == null) {
3428             String signature = getGenericSignature0();
3429             if (signature == null) {
3430                 genericInfo = ClassRepository.NONE;
3431             } else {
3432                 genericInfo = ClassRepository.make(signature, getFactory());
3433             }
3434             this.genericInfo = genericInfo;
3435         }
3436         return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
3437     }
3438 
3439     // Annotations handling
3440     native byte[] getRawAnnotations();
3441     // Since 1.8
3442     native byte[] getRawTypeAnnotations();
3443     static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
3444         return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
3445     }
3446 
3447     native ConstantPool getConstantPool();
3448 
3449     //
3450     //
3451     // java.lang.reflect.Field handling
3452     //
3453     //
3454 
3455     // Returns an array of "root" fields. These Field objects must NOT
3456     // be propagated to the outside world, but must instead be copied
3457     // via ReflectionFactory.copyField.
3458     private Field[] privateGetDeclaredFields(boolean publicOnly) {
3459         Field[] res;
3460         ReflectionData<T> rd = reflectionData();
3461         if (rd != null) {
3462             res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
3463             if (res != null) return res;
3464         }
3465         // No cached value available; request value from VM
3466         res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
3467         if (rd != null) {
3468             if (publicOnly) {
3469                 rd.declaredPublicFields = res;
3470             } else {
3471                 rd.declaredFields = res;
3472             }
3473         }
3474         return res;
3475     }
3476 
3477     // Returns an array of "root" fields. These Field objects must NOT
3478     // be propagated to the outside world, but must instead be copied
3479     // via ReflectionFactory.copyField.
3480     private Field[] privateGetPublicFields() {
3481         Field[] res;
3482         ReflectionData<T> rd = reflectionData();
3483         if (rd != null) {
3484             res = rd.publicFields;
3485             if (res != null) return res;
3486         }
3487 
3488         // Use a linked hash set to ensure order is preserved and
3489         // fields from common super interfaces are not duplicated
3490         LinkedHashSet<Field> fields = new LinkedHashSet<>();
3491 
3492         // Local fields
3493         addAll(fields, privateGetDeclaredFields(true));
3494 
3495         // Direct superinterfaces, recursively
3496         for (Class<?> si : getInterfaces()) {
3497             addAll(fields, si.privateGetPublicFields());
3498         }
3499 
3500         // Direct superclass, recursively
3501         Class<?> sc = getSuperclass();
3502         if (sc != null) {
3503             addAll(fields, sc.privateGetPublicFields());
3504         }
3505 
3506         res = fields.toArray(new Field[0]);
3507         if (rd != null) {
3508             rd.publicFields = res;
3509         }
3510         return res;
3511     }
3512 
3513     private static void addAll(Collection<Field> c, Field[] o) {
3514         for (Field f : o) {
3515             c.add(f);
3516         }
3517     }
3518 
3519 
3520     //
3521     //
3522     // java.lang.reflect.Constructor handling
3523     //
3524     //
3525 
3526     // Returns an array of "root" constructors. These Constructor
3527     // objects must NOT be propagated to the outside world, but must
3528     // instead be copied via ReflectionFactory.copyConstructor.
3529     private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
3530         Constructor<T>[] res;
3531         ReflectionData<T> rd = reflectionData();
3532         if (rd != null) {
3533             res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
3534             if (res != null) return res;
3535         }
3536         // No cached value available; request value from VM
3537         if (isInterface()) {
3538             @SuppressWarnings("unchecked")
3539             Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
3540             res = temporaryRes;
3541         } else {
3542             res = getDeclaredConstructors0(publicOnly);
3543         }
3544         if (rd != null) {
3545             if (publicOnly) {
3546                 rd.publicConstructors = res;
3547             } else {
3548                 rd.declaredConstructors = res;
3549             }
3550         }
3551         return res;
3552     }
3553 
3554     //
3555     //
3556     // java.lang.reflect.Method handling
3557     //
3558     //
3559 
3560     // Returns an array of "root" methods. These Method objects must NOT
3561     // be propagated to the outside world, but must instead be copied
3562     // via ReflectionFactory.copyMethod.
3563     private Method[] privateGetDeclaredMethods(boolean publicOnly) {
3564         Method[] res;
3565         ReflectionData<T> rd = reflectionData();
3566         if (rd != null) {
3567             res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
3568             if (res != null) return res;
3569         }
3570         // No cached value available; request value from VM
3571         res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
3572         if (rd != null) {
3573             if (publicOnly) {
3574                 rd.declaredPublicMethods = res;
3575             } else {
3576                 rd.declaredMethods = res;
3577             }
3578         }
3579         return res;
3580     }
3581 
3582     // Returns an array of "root" methods. These Method objects must NOT
3583     // be propagated to the outside world, but must instead be copied
3584     // via ReflectionFactory.copyMethod.
3585     private Method[] privateGetPublicMethods() {
3586         Method[] res;
3587         ReflectionData<T> rd = reflectionData();
3588         if (rd != null) {
3589             res = rd.publicMethods;
3590             if (res != null) return res;
3591         }
3592 
3593         // No cached value available; compute value recursively.
3594         // Start by fetching public declared methods...
3595         PublicMethods pms = new PublicMethods();
3596         for (Method m : privateGetDeclaredMethods(/* publicOnly */ true)) {
3597             pms.merge(m);
3598         }
3599         // ...then recur over superclass methods...
3600         Class<?> sc = getSuperclass();
3601         if (sc != null) {
3602             for (Method m : sc.privateGetPublicMethods()) {
3603                 pms.merge(m);
3604             }
3605         }
3606         // ...and finally over direct superinterfaces.
3607         for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
3608             for (Method m : intf.privateGetPublicMethods()) {
3609                 // static interface methods are not inherited
3610                 if (!Modifier.isStatic(m.getModifiers())) {
3611                     pms.merge(m);
3612                 }
3613             }
3614         }
3615 
3616         res = pms.toArray();
3617         if (rd != null) {
3618             rd.publicMethods = res;
3619         }
3620         return res;
3621     }
3622 
3623 
3624     //
3625     // Helpers for fetchers of one field, method, or constructor
3626     //
3627 
3628     // This method does not copy the returned Field object!
3629     private static Field searchFields(Field[] fields, String name) {
3630         for (Field field : fields) {
3631             if (field.getName().equals(name)) {
3632                 return field;
3633             }
3634         }
3635         return null;
3636     }
3637 
3638     // Returns a "root" Field object. This Field object must NOT
3639     // be propagated to the outside world, but must instead be copied
3640     // via ReflectionFactory.copyField.
3641     private Field getField0(String name) {
3642         // Note: the intent is that the search algorithm this routine
3643         // uses be equivalent to the ordering imposed by
3644         // privateGetPublicFields(). It fetches only the declared
3645         // public fields for each class, however, to reduce the number
3646         // of Field objects which have to be created for the common
3647         // case where the field being requested is declared in the
3648         // class which is being queried.
3649         Field res;
3650         // Search declared public fields
3651         if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
3652             return res;
3653         }
3654         // Direct superinterfaces, recursively
3655         Class<?>[] interfaces = getInterfaces(/* cloneArray */ false);
3656         for (Class<?> c : interfaces) {
3657             if ((res = c.getField0(name)) != null) {
3658                 return res;
3659             }
3660         }
3661         // Direct superclass, recursively
3662         if (!isInterface()) {
3663             Class<?> c = getSuperclass();
3664             if (c != null) {
3665                 if ((res = c.getField0(name)) != null) {
3666                     return res;
3667                 }
3668             }
3669         }
3670         return null;
3671     }
3672 
3673     // This method does not copy the returned Method object!
3674     private static Method searchMethods(Method[] methods,
3675                                         String name,
3676                                         Class<?>[] parameterTypes)
3677     {
3678         ReflectionFactory fact = getReflectionFactory();
3679         Method res = null;
3680         for (Method m : methods) {
3681             if (m.getName().equals(name)
3682                 && arrayContentsEq(parameterTypes,
3683                                    fact.getExecutableSharedParameterTypes(m))
3684                 && (res == null
3685                     || (res.getReturnType() != m.getReturnType()
3686                         && res.getReturnType().isAssignableFrom(m.getReturnType()))))
3687                 res = m;
3688         }
3689         return res;
3690     }
3691 
3692     private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
3693 
3694     // Returns a "root" Method object. This Method object must NOT
3695     // be propagated to the outside world, but must instead be copied
3696     // via ReflectionFactory.copyMethod.
3697     private Method getMethod0(String name, Class<?>[] parameterTypes) {
3698         PublicMethods.MethodList res = getMethodsRecursive(
3699             name,
3700             parameterTypes == null ? EMPTY_CLASS_ARRAY : parameterTypes,
3701             /* includeStatic */ true);
3702         return res == null ? null : res.getMostSpecific();
3703     }
3704 
3705     // Returns a list of "root" Method objects. These Method objects must NOT
3706     // be propagated to the outside world, but must instead be copied
3707     // via ReflectionFactory.copyMethod.
3708     private PublicMethods.MethodList getMethodsRecursive(String name,
3709                                                          Class<?>[] parameterTypes,
3710                                                          boolean includeStatic) {
3711         // 1st check declared public methods
3712         Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);
3713         PublicMethods.MethodList res = PublicMethods.MethodList
3714             .filter(methods, name, parameterTypes, includeStatic);
3715         // if there is at least one match among declared methods, we need not
3716         // search any further as such match surely overrides matching methods
3717         // declared in superclass(es) or interface(s).
3718         if (res != null) {
3719             return res;
3720         }
3721 
3722         // if there was no match among declared methods,
3723         // we must consult the superclass (if any) recursively...
3724         Class<?> sc = getSuperclass();
3725         if (sc != null) {
3726             res = sc.getMethodsRecursive(name, parameterTypes, includeStatic);
3727         }
3728 
3729         // ...and coalesce the superclass methods with methods obtained
3730         // from directly implemented interfaces excluding static methods...
3731         for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
3732             res = PublicMethods.MethodList.merge(
3733                 res, intf.getMethodsRecursive(name, parameterTypes,
3734                                               /* includeStatic */ false));
3735         }
3736 
3737         return res;
3738     }
3739 
3740     // Returns a "root" Constructor object. This Constructor object must NOT
3741     // be propagated to the outside world, but must instead be copied
3742     // via ReflectionFactory.copyConstructor.
3743     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3744                                         int which) throws NoSuchMethodException
3745     {
3746         ReflectionFactory fact = getReflectionFactory();
3747         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3748         for (Constructor<T> constructor : constructors) {
3749             if (arrayContentsEq(parameterTypes,
3750                                 fact.getExecutableSharedParameterTypes(constructor))) {
3751                 return constructor;
3752             }
3753         }
3754         throw new NoSuchMethodException(methodToString("<init>", parameterTypes));
3755     }
3756 
3757     //
3758     // Other helpers and base implementation
3759     //
3760 
3761     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3762         if (a1 == null) {
3763             return a2 == null || a2.length == 0;
3764         }
3765 
3766         if (a2 == null) {
3767             return a1.length == 0;
3768         }
3769 
3770         if (a1.length != a2.length) {
3771             return false;
3772         }
3773 
3774         for (int i = 0; i < a1.length; i++) {
3775             if (a1[i] != a2[i]) {
3776                 return false;
3777             }
3778         }
3779 
3780         return true;
3781     }
3782 
3783     private static Field[] copyFields(Field[] arg) {
3784         Field[] out = new Field[arg.length];
3785         ReflectionFactory fact = getReflectionFactory();
3786         for (int i = 0; i < arg.length; i++) {
3787             out[i] = fact.copyField(arg[i]);
3788         }
3789         return out;
3790     }
3791 
3792     private static Method[] copyMethods(Method[] arg) {
3793         Method[] out = new Method[arg.length];
3794         ReflectionFactory fact = getReflectionFactory();
3795         for (int i = 0; i < arg.length; i++) {
3796             out[i] = fact.copyMethod(arg[i]);
3797         }
3798         return out;
3799     }
3800 
3801     private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
3802         Constructor<U>[] out = arg.clone();
3803         ReflectionFactory fact = getReflectionFactory();
3804         for (int i = 0; i < out.length; i++) {
3805             out[i] = fact.copyConstructor(out[i]);
3806         }
3807         return out;
3808     }
3809 
3810     private native Field[]       getDeclaredFields0(boolean publicOnly);
3811     private native Method[]      getDeclaredMethods0(boolean publicOnly);
3812     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3813     private native Class<?>[]    getDeclaredClasses0();
3814 
3815     /*
3816      * Returns an array containing the components of the Record attribute,
3817      * or null if the attribute is not present.
3818      *
3819      * Note that this method returns non-null array on a class with
3820      * the Record attribute even if this class is not a record.
3821      */
3822     private native RecordComponent[] getRecordComponents0();
3823     private native boolean       isRecord0();
3824 
3825     /**
3826      * Helper method to get the method name from arguments.
3827      */
3828     private String methodToString(String name, Class<?>[] argTypes) {
3829         return getName() + '.' + name +
3830                 ((argTypes == null || argTypes.length == 0) ?
3831                 "()" :
3832                 Arrays.stream(argTypes)
3833                         .map(c -> c == null ? "null" : c.getName())
3834                         .collect(Collectors.joining(",", "(", ")")));
3835     }
3836 
3837     /** use serialVersionUID from JDK 1.1 for interoperability */
3838     @java.io.Serial
3839     private static final long serialVersionUID = 3206093459760846163L;
3840 
3841 
3842     /**
3843      * Class Class is special cased within the Serialization Stream Protocol.
3844      *
3845      * A Class instance is written initially into an ObjectOutputStream in the
3846      * following format:
3847      * <pre>
3848      *      {@code TC_CLASS} ClassDescriptor
3849      *      A ClassDescriptor is a special cased serialization of
3850      *      a {@code java.io.ObjectStreamClass} instance.
3851      * </pre>
3852      * A new handle is generated for the initial time the class descriptor
3853      * is written into the stream. Future references to the class descriptor
3854      * are written as references to the initial class descriptor instance.
3855      *
3856      * @see java.io.ObjectStreamClass
3857      */
3858     @java.io.Serial
3859     private static final ObjectStreamField[] serialPersistentFields =
3860         new ObjectStreamField[0];
3861 
3862 
3863     /**
3864      * Returns the assertion status that would be assigned to this
3865      * class if it were to be initialized at the time this method is invoked.
3866      * If this class has had its assertion status set, the most recent
3867      * setting will be returned; otherwise, if any package default assertion
3868      * status pertains to this class, the most recent setting for the most
3869      * specific pertinent package default assertion status is returned;
3870      * otherwise, if this class is not a system class (i.e., it has a
3871      * class loader) its class loader's default assertion status is returned;
3872      * otherwise, the system class default assertion status is returned.
3873      *
3874      * @apiNote
3875      * Few programmers will have any need for this method; it is provided
3876      * for the benefit of the JDK itself.  (It allows a class to determine at
3877      * the time that it is initialized whether assertions should be enabled.)
3878      * Note that this method is not guaranteed to return the actual
3879      * assertion status that was (or will be) associated with the specified
3880      * class when it was (or will be) initialized.
3881      *
3882      * @return the desired assertion status of the specified class.
3883      * @see    java.lang.ClassLoader#setClassAssertionStatus
3884      * @see    java.lang.ClassLoader#setPackageAssertionStatus
3885      * @see    java.lang.ClassLoader#setDefaultAssertionStatus
3886      * @since  1.4
3887      */
3888     public boolean desiredAssertionStatus() {
3889         ClassLoader loader = classLoader;
3890         // If the loader is null this is a system class, so ask the VM
3891         if (loader == null)
3892             return desiredAssertionStatus0(this);
3893 
3894         // If the classloader has been initialized with the assertion
3895         // directives, ask it. Otherwise, ask the VM.
3896         synchronized(loader.assertionLock) {
3897             if (loader.classAssertionStatus != null) {
3898                 return loader.desiredAssertionStatus(getName());
3899             }
3900         }
3901         return desiredAssertionStatus0(this);
3902     }
3903 
3904     // Retrieves the desired assertion status of this class from the VM
3905     private static native boolean desiredAssertionStatus0(Class<?> clazz);
3906 
3907     /**
3908      * Returns true if and only if this class was declared as an enum in the
3909      * source code.
3910      *
3911      * Note that {@link java.lang.Enum} is not itself an enum class.
3912      *
3913      * Also note that if an enum constant is declared with a class body,
3914      * the class of that enum constant object is an anonymous class
3915      * and <em>not</em> the class of the declaring enum class. The
3916      * {@link Enum#getDeclaringClass} method of an enum constant can
3917      * be used to get the class of the enum class declaring the
3918      * constant.
3919      *
3920      * @return true if and only if this class was declared as an enum in the
3921      *     source code
3922      * @since 1.5
3923      * @jls 8.9.1 Enum Constants
3924      */
3925     public boolean isEnum() {
3926         // An enum must both directly extend java.lang.Enum and have
3927         // the ENUM bit set; classes for specialized enum constants
3928         // don't do the former.
3929         return (this.getModifiers() & ENUM) != 0 &&
3930         this.getSuperclass() == java.lang.Enum.class;
3931     }
3932 
3933     /**
3934      * Returns {@code true} if and only if this class is a record class.
3935      *
3936      * <p> The {@linkplain #getSuperclass() direct superclass} of a record
3937      * class is {@code java.lang.Record}. A record class is {@linkplain
3938      * Modifier#FINAL final}. A record class has (possibly zero) record
3939      * components; {@link #getRecordComponents()} returns a non-null but
3940      * possibly empty value for a record.
3941      *
3942      * <p> Note that class {@link Record} is not a record class and thus
3943      * invoking this method on class {@code Record} returns {@code false}.
3944      *
3945      * @return true if and only if this class is a record class, otherwise false
3946      * @jls 8.10 Record Classes
3947      * @since 16
3948      */
3949     public boolean isRecord() {
3950         // this superclass and final modifier check is not strictly necessary
3951         // they are intrinsified and serve as a fast-path check
3952         return getSuperclass() == java.lang.Record.class &&
3953                 (this.getModifiers() & Modifier.FINAL) != 0 &&
3954                 isRecord0();
3955     }
3956 
3957     // Fetches the factory for reflective objects
3958     @SuppressWarnings("removal")
3959     private static ReflectionFactory getReflectionFactory() {
3960         if (reflectionFactory == null) {
3961             reflectionFactory =
3962                 java.security.AccessController.doPrivileged
3963                     (new ReflectionFactory.GetReflectionFactoryAction());
3964         }
3965         return reflectionFactory;
3966     }
3967     private static ReflectionFactory reflectionFactory;
3968 
3969     /**
3970      * Returns the elements of this enum class or null if this
3971      * Class object does not represent an enum class.
3972      *
3973      * @return an array containing the values comprising the enum class
3974      *     represented by this {@code Class} object in the order they're
3975      *     declared, or null if this {@code Class} object does not
3976      *     represent an enum class
3977      * @since 1.5
3978      * @jls 8.9.1 Enum Constants
3979      */
3980     public T[] getEnumConstants() {
3981         T[] values = getEnumConstantsShared();
3982         return (values != null) ? values.clone() : null;
3983     }
3984 
3985     /**
3986      * Returns the elements of this enum class or null if this
3987      * Class object does not represent an enum class;
3988      * identical to getEnumConstants except that the result is
3989      * uncloned, cached, and shared by all callers.
3990      */
3991     @SuppressWarnings("removal")
3992     T[] getEnumConstantsShared() {
3993         T[] constants = enumConstants;
3994         if (constants == null) {
3995             if (!isEnum()) return null;
3996             try {
3997                 final Method values = getMethod("values");
3998                 java.security.AccessController.doPrivileged(
3999                     new java.security.PrivilegedAction<>() {
4000                         public Void run() {
4001                                 values.setAccessible(true);
4002                                 return null;
4003                             }
4004                         });
4005                 @SuppressWarnings("unchecked")
4006                 T[] temporaryConstants = (T[])values.invoke(null);
4007                 enumConstants = constants = temporaryConstants;
4008             }
4009             // These can happen when users concoct enum-like classes
4010             // that don't comply with the enum spec.
4011             catch (InvocationTargetException | NoSuchMethodException |
4012                    IllegalAccessException ex) { return null; }
4013         }
4014         return constants;
4015     }
4016     private transient volatile T[] enumConstants;
4017 
4018     /**
4019      * Returns a map from simple name to enum constant.  This package-private
4020      * method is used internally by Enum to implement
4021      * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}
4022      * efficiently.  Note that the map is returned by this method is
4023      * created lazily on first use.  Typically it won't ever get created.
4024      */
4025     Map<String, T> enumConstantDirectory() {
4026         Map<String, T> directory = enumConstantDirectory;
4027         if (directory == null) {
4028             T[] universe = getEnumConstantsShared();
4029             if (universe == null)
4030                 throw new IllegalArgumentException(
4031                     getName() + " is not an enum class");
4032             directory = new HashMap<>((int)(universe.length / 0.75f) + 1);
4033             for (T constant : universe) {
4034                 directory.put(((Enum<?>)constant).name(), constant);
4035             }
4036             enumConstantDirectory = directory;
4037         }
4038         return directory;
4039     }
4040     private transient volatile Map<String, T> enumConstantDirectory;
4041 
4042     /**
4043      * Casts an object to the class or interface represented
4044      * by this {@code Class} object.
4045      *
4046      * @param obj the object to be cast
4047      * @return the object after casting, or null if obj is null
4048      *
4049      * @throws ClassCastException if the object is not
4050      * {@code null} and is not assignable to the type T.
4051      * @throws NullPointerException if this class is an {@linkplain #isValueType()
4052      * primitive value type} and the object is {@code null}
4053      *
4054      * @since 1.5
4055      */
4056     @SuppressWarnings("unchecked")
4057     @IntrinsicCandidate
4058     public T cast(Object obj) {
4059         if (isValueType() && obj == null)
4060             throw new NullPointerException(getName() + " is a primitive value type");
4061 
4062         if (obj != null && !isInstance(obj))
4063             throw new ClassCastException(cannotCastMsg(obj));
4064         return (T) obj;
4065     }
4066 
4067     private String cannotCastMsg(Object obj) {
4068         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
4069     }
4070 
4071     /**
4072      * Casts this {@code Class} object to represent a subclass of the class
4073      * represented by the specified class object.  Checks that the cast
4074      * is valid, and throws a {@code ClassCastException} if it is not.  If
4075      * this method succeeds, it always returns a reference to this {@code Class} object.
4076      *
4077      * <p>This method is useful when a client needs to "narrow" the type of
4078      * a {@code Class} object to pass it to an API that restricts the
4079      * {@code Class} objects that it is willing to accept.  A cast would
4080      * generate a compile-time warning, as the correctness of the cast
4081      * could not be checked at runtime (because generic types are implemented
4082      * by erasure).
4083      *
4084      * @param <U> the type to cast this {@code Class} object to
4085      * @param clazz the class of the type to cast this {@code Class} object to
4086      * @return this {@code Class} object, cast to represent a subclass of
4087      *    the specified class object.
4088      * @throws ClassCastException if this {@code Class} object does not
4089      *    represent a subclass of the specified class (here "subclass" includes
4090      *    the class itself).
4091      * @since 1.5
4092      */
4093     @SuppressWarnings("unchecked")
4094     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
4095         if (clazz.isAssignableFrom(this))
4096             return (Class<? extends U>) this;
4097         else
4098             throw new ClassCastException(this.toString());
4099     }
4100 
4101     /**
4102      * {@inheritDoc}
4103      * <p>Note that any annotation returned by this method is a
4104      * declaration annotation.
4105      *
4106      * @throws NullPointerException {@inheritDoc}
4107      * @since 1.5
4108      */
4109     @Override
4110     @SuppressWarnings("unchecked")
4111     public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
4112         Objects.requireNonNull(annotationClass);
4113 
4114         return (A) annotationData().annotations.get(annotationClass);
4115     }
4116 
4117     /**
4118      * {@inheritDoc}
4119      * @throws NullPointerException {@inheritDoc}
4120      * @since 1.5
4121      */
4122     @Override
4123     public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
4124         return GenericDeclaration.super.isAnnotationPresent(annotationClass);
4125     }
4126 
4127     /**
4128      * {@inheritDoc}
4129      * <p>Note that any annotations returned by this method are
4130      * declaration annotations.
4131      *
4132      * @throws NullPointerException {@inheritDoc}
4133      * @since 1.8
4134      */
4135     @Override
4136     public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {
4137         Objects.requireNonNull(annotationClass);
4138 
4139         AnnotationData annotationData = annotationData();
4140         return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations,
4141                                                           this,
4142                                                           annotationClass);
4143     }
4144 
4145     /**
4146      * {@inheritDoc}
4147      * <p>Note that any annotations returned by this method are
4148      * declaration annotations.
4149      *
4150      * @since 1.5
4151      */
4152     @Override
4153     public Annotation[] getAnnotations() {
4154         return AnnotationParser.toArray(annotationData().annotations);
4155     }
4156 
4157     /**
4158      * {@inheritDoc}
4159      * <p>Note that any annotation returned by this method is a
4160      * declaration annotation.
4161      *
4162      * @throws NullPointerException {@inheritDoc}
4163      * @since 1.8
4164      */
4165     @Override
4166     @SuppressWarnings("unchecked")
4167     public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
4168         Objects.requireNonNull(annotationClass);
4169 
4170         return (A) annotationData().declaredAnnotations.get(annotationClass);
4171     }
4172 
4173     /**
4174      * {@inheritDoc}
4175      * <p>Note that any annotations returned by this method are
4176      * declaration annotations.
4177      *
4178      * @throws NullPointerException {@inheritDoc}
4179      * @since 1.8
4180      */
4181     @Override
4182     public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {
4183         Objects.requireNonNull(annotationClass);
4184 
4185         return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,
4186                                                                  annotationClass);
4187     }
4188 
4189     /**
4190      * {@inheritDoc}
4191      * <p>Note that any annotations returned by this method are
4192      * declaration annotations.
4193      *
4194      * @since 1.5
4195      */
4196     @Override
4197     public Annotation[] getDeclaredAnnotations()  {
4198         return AnnotationParser.toArray(annotationData().declaredAnnotations);
4199     }
4200 
4201     // annotation data that might get invalidated when JVM TI RedefineClasses() is called
4202     private static class AnnotationData {
4203         final Map<Class<? extends Annotation>, Annotation> annotations;
4204         final Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
4205 
4206         // Value of classRedefinedCount when we created this AnnotationData instance
4207         final int redefinedCount;
4208 
4209         AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations,
4210                        Map<Class<? extends Annotation>, Annotation> declaredAnnotations,
4211                        int redefinedCount) {
4212             this.annotations = annotations;
4213             this.declaredAnnotations = declaredAnnotations;
4214             this.redefinedCount = redefinedCount;
4215         }
4216     }
4217 
4218     // Annotations cache
4219     @SuppressWarnings("UnusedDeclaration")
4220     private transient volatile AnnotationData annotationData;
4221 
4222     private AnnotationData annotationData() {
4223         while (true) { // retry loop
4224             AnnotationData annotationData = this.annotationData;
4225             int classRedefinedCount = this.classRedefinedCount;
4226             if (annotationData != null &&
4227                 annotationData.redefinedCount == classRedefinedCount) {
4228                 return annotationData;
4229             }
4230             // null or stale annotationData -> optimistically create new instance
4231             AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount);
4232             // try to install it
4233             if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) {
4234                 // successfully installed new AnnotationData
4235                 return newAnnotationData;
4236             }
4237         }
4238     }
4239 
4240     private AnnotationData createAnnotationData(int classRedefinedCount) {
4241         Map<Class<? extends Annotation>, Annotation> declaredAnnotations =
4242             AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this);
4243         Class<?> superClass = getSuperclass();
4244         Map<Class<? extends Annotation>, Annotation> annotations = null;
4245         if (superClass != null) {
4246             Map<Class<? extends Annotation>, Annotation> superAnnotations =
4247                 superClass.annotationData().annotations;
4248             for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) {
4249                 Class<? extends Annotation> annotationClass = e.getKey();
4250                 if (AnnotationType.getInstance(annotationClass).isInherited()) {
4251                     if (annotations == null) { // lazy construction
4252                         annotations = new LinkedHashMap<>((Math.max(
4253                                 declaredAnnotations.size(),
4254                                 Math.min(12, declaredAnnotations.size() + superAnnotations.size())
4255                             ) * 4 + 2) / 3
4256                         );
4257                     }
4258                     annotations.put(annotationClass, e.getValue());
4259                 }
4260             }
4261         }
4262         if (annotations == null) {
4263             // no inherited annotations -> share the Map with declaredAnnotations
4264             annotations = declaredAnnotations;
4265         } else {
4266             // at least one inherited annotation -> declared may override inherited
4267             annotations.putAll(declaredAnnotations);
4268         }
4269         return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount);
4270     }
4271 
4272     // Annotation interfaces cache their internal (AnnotationType) form
4273 
4274     @SuppressWarnings("UnusedDeclaration")
4275     private transient volatile AnnotationType annotationType;
4276 
4277     boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {
4278         return Atomic.casAnnotationType(this, oldType, newType);
4279     }
4280 
4281     AnnotationType getAnnotationType() {
4282         return annotationType;
4283     }
4284 
4285     Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() {
4286         return annotationData().declaredAnnotations;
4287     }
4288 
4289     /* Backing store of user-defined values pertaining to this class.
4290      * Maintained by the ClassValue class.
4291      */
4292     transient ClassValue.ClassValueMap classValueMap;
4293 
4294     /**
4295      * Returns an {@code AnnotatedType} object that represents the use of a
4296      * type to specify the superclass of the entity represented by this {@code
4297      * Class} object. (The <em>use</em> of type Foo to specify the superclass
4298      * in '...  extends Foo' is distinct from the <em>declaration</em> of class
4299      * Foo.)
4300      *
4301      * <p> If this {@code Class} object represents a class whose declaration
4302      * does not explicitly indicate an annotated superclass, then the return
4303      * value is an {@code AnnotatedType} object representing an element with no
4304      * annotations.
4305      *
4306      * <p> If this {@code Class} represents either the {@code Object} class, an
4307      * interface type, an array type, a primitive type, or void, the return
4308      * value is {@code null}.
4309      *
4310      * @return an object representing the superclass
4311      * @since 1.8
4312      */
4313     public AnnotatedType getAnnotatedSuperclass() {
4314         if (this == Object.class ||
4315                 isInterface() ||
4316                 isArray() ||
4317                 isPrimitive() ||
4318                 this == Void.TYPE) {
4319             return null;
4320         }
4321 
4322         return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
4323     }
4324 
4325     /**
4326      * Returns an array of {@code AnnotatedType} objects that represent the use
4327      * of types to specify superinterfaces of the entity represented by this
4328      * {@code Class} object. (The <em>use</em> of type Foo to specify a
4329      * superinterface in '... implements Foo' is distinct from the
4330      * <em>declaration</em> of interface Foo.)
4331      *
4332      * <p> If this {@code Class} object represents a class, the return value is
4333      * an array containing objects representing the uses of interface types to
4334      * specify interfaces implemented by the class. The order of the objects in
4335      * the array corresponds to the order of the interface types used in the
4336      * 'implements' clause of the declaration of this {@code Class} object.
4337      *
4338      * <p> If this {@code Class} object represents an interface, the return
4339      * value is an array containing objects representing the uses of interface
4340      * types to specify interfaces directly extended by the interface. The
4341      * order of the objects in the array corresponds to the order of the
4342      * interface types used in the 'extends' clause of the declaration of this
4343      * {@code Class} object.
4344      *
4345      * <p> If this {@code Class} object represents a class or interface whose
4346      * declaration does not explicitly indicate any annotated superinterfaces,
4347      * the return value is an array of length 0.
4348      *
4349      * <p> If this {@code Class} object represents either the {@code Object}
4350      * class, an array type, a primitive type, or void, the return value is an
4351      * array of length 0.
4352      *
4353      * @return an array representing the superinterfaces
4354      * @since 1.8
4355      */
4356     public AnnotatedType[] getAnnotatedInterfaces() {
4357         return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
4358     }
4359 
4360     private native Class<?> getNestHost0();
4361 
4362     /**
4363      * Returns the nest host of the <a href=#nest>nest</a> to which the class
4364      * or interface represented by this {@code Class} object belongs.
4365      * Every class and interface belongs to exactly one nest.
4366      *
4367      * If the nest host of this class or interface has previously
4368      * been determined, then this method returns the nest host.
4369      * If the nest host of this class or interface has
4370      * not previously been determined, then this method determines the nest
4371      * host using the algorithm of JVMS 5.4.4, and returns it.
4372      *
4373      * Often, a class or interface belongs to a nest consisting only of itself,
4374      * in which case this method returns {@code this} to indicate that the class
4375      * or interface is the nest host.
4376      *
4377      * <p>If this {@code Class} object represents a primitive type, an array type,
4378      * or {@code void}, then this method returns {@code this},
4379      * indicating that the represented entity belongs to the nest consisting only of
4380      * itself, and is the nest host.
4381      *
4382      * @return the nest host of this class or interface
4383      *
4384      * @throws SecurityException
4385      *         If the returned class is not the current class, and
4386      *         if a security manager, <i>s</i>, is present and the caller's
4387      *         class loader is not the same as or an ancestor of the class
4388      *         loader for the returned class and invocation of {@link
4389      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
4390      *         denies access to the package of the returned class
4391      * @since 11
4392      * @jvms 4.7.28 The {@code NestHost} Attribute
4393      * @jvms 4.7.29 The {@code NestMembers} Attribute
4394      * @jvms 5.4.4 Access Control
4395      */
4396     @CallerSensitive
4397     public Class<?> getNestHost() {
4398         if (isPrimitive() || isArray()) {
4399             return this;
4400         }
4401 
4402         Class<?> host = getNestHost0();
4403         if (host == this) {
4404             return this;
4405         }
4406         // returning a different class requires a security check
4407         @SuppressWarnings("removal")
4408         SecurityManager sm = System.getSecurityManager();
4409         if (sm != null) {
4410             checkPackageAccess(sm,
4411                                ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
4412         }
4413         return host;
4414     }
4415 
4416     /**
4417      * Determines if the given {@code Class} is a nestmate of the
4418      * class or interface represented by this {@code Class} object.
4419      * Two classes or interfaces are nestmates
4420      * if they have the same {@linkplain #getNestHost() nest host}.
4421      *
4422      * @param c the class to check
4423      * @return {@code true} if this class and {@code c} are members of
4424      * the same nest; and {@code false} otherwise.
4425      *
4426      * @since 11
4427      */
4428     public boolean isNestmateOf(Class<?> c) {
4429         if (this == c) {
4430             return true;
4431         }
4432         if (isPrimitive() || isArray() ||
4433             c.isPrimitive() || c.isArray()) {
4434             return false;
4435         }
4436 
4437         return getNestHost() == c.getNestHost();
4438     }
4439 
4440     private native Class<?>[] getNestMembers0();
4441 
4442     /**
4443      * Returns an array containing {@code Class} objects representing all the
4444      * classes and interfaces that are members of the nest to which the class
4445      * or interface represented by this {@code Class} object belongs.
4446      *
4447      * First, this method obtains the {@linkplain #getNestHost() nest host},
4448      * {@code H}, of the nest to which the class or interface represented by
4449      * this {@code Class} object belongs. The zeroth element of the returned
4450      * array is {@code H}.
4451      *
4452      * Then, for each class or interface {@code C} which is recorded by {@code H}
4453      * as being a member of its nest, this method attempts to obtain the {@code Class}
4454      * object for {@code C} (using {@linkplain #getClassLoader() the defining class
4455      * loader} of the current {@code Class} object), and then obtains the
4456      * {@linkplain #getNestHost() nest host} of the nest to which {@code C} belongs.
4457      * The classes and interfaces which are recorded by {@code H} as being members
4458      * of its nest, and for which {@code H} can be determined as their nest host,
4459      * are indicated by subsequent elements of the returned array. The order of
4460      * such elements is unspecified. Duplicates are permitted.
4461      *
4462      * <p>If this {@code Class} object represents a primitive type, an array type,
4463      * or {@code void}, then this method returns a single-element array containing
4464      * {@code this}.
4465      *
4466      * @apiNote
4467      * The returned array includes only the nest members recorded in the {@code NestMembers}
4468      * attribute, and not any hidden classes that were added to the nest via
4469      * {@link MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
4470      * Lookup::defineHiddenClass}.
4471      *
4472      * @return an array of all classes and interfaces in the same nest as
4473      * this class or interface
4474      *
4475      * @throws SecurityException
4476      * If any returned class is not the current class, and
4477      * if a security manager, <i>s</i>, is present and the caller's
4478      * class loader is not the same as or an ancestor of the class
4479      * loader for that returned class and invocation of {@link
4480      * SecurityManager#checkPackageAccess s.checkPackageAccess()}
4481      * denies access to the package of that returned class
4482      *
4483      * @since 11
4484      * @see #getNestHost()
4485      * @jvms 4.7.28 The {@code NestHost} Attribute
4486      * @jvms 4.7.29 The {@code NestMembers} Attribute
4487      */
4488     @CallerSensitive
4489     public Class<?>[] getNestMembers() {
4490         if (isPrimitive() || isArray()) {
4491             return new Class<?>[] { this };
4492         }
4493         Class<?>[] members = getNestMembers0();
4494         // Can't actually enable this due to bootstrapping issues
4495         // assert(members.length != 1 || members[0] == this); // expected invariant from VM
4496 
4497         if (members.length > 1) {
4498             // If we return anything other than the current class we need
4499             // a security check
4500             @SuppressWarnings("removal")
4501             SecurityManager sm = System.getSecurityManager();
4502             if (sm != null) {
4503                 checkPackageAccess(sm,
4504                                    ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
4505             }
4506         }
4507         return members;
4508     }
4509 
4510     /**
4511      * Returns the descriptor string of the entity (class, interface, array class,
4512      * primitive type, or {@code void}) represented by this {@code Class} object.
4513      *
4514      * <p> If this {@code Class} object represents a class or interface,
4515      * not an array class, then:
4516      * <ul>
4517      * <li> If the class or interface is not {@linkplain Class#isHidden() hidden},
4518      *      then the result is a field descriptor (JVMS {@jvms 4.3.2})
4519      *      for the class or interface. Calling
4520      *      {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor}
4521      *      with the result descriptor string produces a {@link ClassDesc ClassDesc}
4522      *      describing this class or interface.
4523      * <li> If the class or interface is {@linkplain Class#isHidden() hidden},
4524      *      then the result is a string of the form:
4525      *      <blockquote>
4526      *      {@code "L" +} <em>N</em> {@code + "." + <suffix> + ";"}
4527      *      </blockquote>
4528      *      where <em>N</em> is the <a href="ClassLoader.html#binary-name">binary name</a>
4529      *      encoded in internal form indicated by the {@code class} file passed to
4530      *      {@link MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
4531      *      Lookup::defineHiddenClass}, and {@code <suffix>} is an unqualified name.
4532      *      A hidden class or interface has no {@linkplain ClassDesc nominal descriptor}.
4533      *      The result string is not a type descriptor.
4534      * </ul>
4535      *
4536      * <p> If this {@code Class} object represents an array class, then
4537      * the result is a string consisting of one or more '{@code [}' characters
4538      * representing the depth of the array nesting, followed by the
4539      * descriptor string of the element type.
4540      * <ul>
4541      * <li> If the element type is not a {@linkplain Class#isHidden() hidden} class
4542      * or interface, then this array class can be described nominally.
4543      * Calling {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor}
4544      * with the result descriptor string produces a {@link ClassDesc ClassDesc}
4545      * describing this array class.
4546      * <li> If the element type is a {@linkplain Class#isHidden() hidden} class or
4547      * interface, then this array class cannot be described nominally.
4548      * The result string is not a type descriptor.
4549      * </ul>
4550      *
4551      * <p> If this {@code Class} object represents a primitive type or
4552      * {@code void}, then the result is a field descriptor string which
4553      * is a one-letter code corresponding to a primitive type or {@code void}
4554      * ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}).
4555      *
4556      * @apiNote
4557      * This is not a strict inverse of {@link #forName};
4558      * distinct classes which share a common name but have different class loaders
4559      * will have identical descriptor strings.
4560      *
4561      * @return the descriptor string for this {@code Class} object
4562      * @jvms 4.3.2 Field Descriptors
4563      * @since 12
4564      */
4565     @Override
4566     public String descriptorString() {
4567         if (isPrimitive())
4568             return Wrapper.forPrimitiveType(this).basicTypeString();
4569 
4570         if (isArray()) {
4571             return "[" + componentType.descriptorString();
4572         }
4573         char typeDesc = isValueType() ? 'Q' : 'L';
4574         if (isHidden()) {
4575             String name = getName();
4576             int index = name.indexOf('/');
4577             return new StringBuilder(name.length() + 2)
4578                     .append(typeDesc)
4579                     .append(name.substring(0, index).replace('.', '/'))
4580                     .append('.')
4581                     .append(name, index + 1, name.length())
4582                     .append(';')
4583                     .toString();
4584         } else {
4585             String name = getName().replace('.', '/');
4586             return new StringBuilder(name.length() + 2)
4587                     .append(typeDesc)
4588                     .append(name)
4589                     .append(';')
4590                     .toString();
4591         }
4592     }
4593 
4594     /**
4595      * Returns the component type of this {@code Class}, if it describes
4596      * an array type, or {@code null} otherwise.
4597      *
4598      * @implSpec
4599      * Equivalent to {@link Class#getComponentType()}.
4600      *
4601      * @return a {@code Class} describing the component type, or {@code null}
4602      * if this {@code Class} does not describe an array type
4603      * @since 12
4604      */
4605     @Override
4606     public Class<?> componentType() {
4607         return isArray() ? componentType : null;
4608     }
4609 
4610     /**
4611      * Returns a {@code Class} for an array type whose component type
4612      * is described by this {@linkplain Class}.
4613      *
4614      * @return a {@code Class} describing the array type
4615      * @since 12
4616      */
4617     @Override
4618     public Class<?> arrayType() {
4619         return Array.newInstance(this, 0).getClass();
4620     }
4621 
4622     /**
4623      * Returns a nominal descriptor for this instance, if one can be
4624      * constructed, or an empty {@link Optional} if one cannot be.
4625      *
4626      * @return An {@link Optional} containing the resulting nominal descriptor,
4627      * or an empty {@link Optional} if one cannot be constructed.
4628      * @since 12
4629      */
4630     @Override
4631     public Optional<ClassDesc> describeConstable() {
4632         Class<?> c = isArray() ? elementType() : this;
4633         return c.isHidden() ? Optional.empty()
4634                             : Optional.of(ClassDesc.ofDescriptor(descriptorString()));
4635    }
4636 
4637     /**
4638      * Returns {@code true} if and only if the underlying class is a hidden class.
4639      *
4640      * @return {@code true} if and only if this class is a hidden class.
4641      *
4642      * @since 15
4643      * @see MethodHandles.Lookup#defineHiddenClass
4644      */
4645     @IntrinsicCandidate
4646     public native boolean isHidden();
4647 
4648     /**
4649      * Returns an array containing {@code Class} objects representing the
4650      * direct subinterfaces or subclasses permitted to extend or
4651      * implement this class or interface if it is sealed.  The order of such elements
4652      * is unspecified. The array is empty if this sealed class or interface has no
4653      * permitted subclass. If this {@code Class} object represents a primitive type,
4654      * {@code void}, an array type, or a class or interface that is not sealed,
4655      * that is {@link #isSealed()} returns {@code false}, then this method returns {@code null}.
4656      * Conversely, if {@link #isSealed()} returns {@code true}, then this method
4657      * returns a non-null value.
4658      *
4659      * For each class or interface {@code C} which is recorded as a permitted
4660      * direct subinterface or subclass of this class or interface,
4661      * this method attempts to obtain the {@code Class}
4662      * object for {@code C} (using {@linkplain #getClassLoader() the defining class
4663      * loader} of the current {@code Class} object).
4664      * The {@code Class} objects which can be obtained and which are direct
4665      * subinterfaces or subclasses of this class or interface,
4666      * are indicated by elements of the returned array. If a {@code Class} object
4667      * cannot be obtained, it is silently ignored, and not included in the result
4668      * array.
4669      *
4670      * @return an array of {@code Class} objects of the permitted subclasses of this class or interface,
4671      *         or {@code null} if this class or interface is not sealed.
4672      *
4673      * @throws SecurityException
4674      *         If a security manager, <i>s</i>, is present and the caller's
4675      *         class loader is not the same as or an ancestor of the class
4676      *         loader for that returned class and invocation of {@link
4677      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
4678      *         denies access to the package of any class in the returned array.
4679      *
4680      * @jls 8.1 Class Declarations
4681      * @jls 9.1 Interface Declarations
4682      * @since 17
4683      */
4684     @CallerSensitive
4685     public Class<?>[] getPermittedSubclasses() {
4686         Class<?>[] subClasses;
4687         if (isArray() || isPrimitive() || (subClasses = getPermittedSubclasses0()) == null) {
4688             return null;
4689         }
4690         if (subClasses.length > 0) {
4691             if (Arrays.stream(subClasses).anyMatch(c -> !isDirectSubType(c))) {
4692                 subClasses = Arrays.stream(subClasses)
4693                                    .filter(this::isDirectSubType)
4694                                    .toArray(s -> new Class<?>[s]);
4695             }
4696         }
4697         if (subClasses.length > 0) {
4698             // If we return some classes we need a security check:
4699             @SuppressWarnings("removal")
4700             SecurityManager sm = System.getSecurityManager();
4701             if (sm != null) {
4702                 checkPackageAccessForPermittedSubclasses(sm,
4703                                              ClassLoader.getClassLoader(Reflection.getCallerClass()),
4704                                              subClasses);
4705             }
4706         }
4707         return subClasses;
4708     }
4709 
4710     private boolean isDirectSubType(Class<?> c) {
4711         if (isInterface()) {
4712             for (Class<?> i : c.getInterfaces(/* cloneArray */ false)) {
4713                 if (i == this) {
4714                     return true;
4715                 }
4716             }
4717         } else {
4718             return c.getSuperclass() == this;
4719         }
4720         return false;
4721     }
4722 
4723     /**
4724      * Returns {@code true} if and only if this {@code Class} object represents
4725      * a sealed class or interface. If this {@code Class} object represents a
4726      * primitive type, {@code void}, or an array type, this method returns
4727      * {@code false}. A sealed class or interface has (possibly zero) permitted
4728      * subclasses; {@link #getPermittedSubclasses()} returns a non-null but
4729      * possibly empty value for a sealed class or interface.
4730      *
4731      * @return {@code true} if and only if this {@code Class} object represents
4732      * a sealed class or interface.
4733      *
4734      * @jls 8.1 Class Declarations
4735      * @jls 9.1 Interface Declarations
4736      * @since 17
4737      */
4738     public boolean isSealed() {
4739         if (isArray() || isPrimitive()) {
4740             return false;
4741         }
4742         return getPermittedSubclasses() != null;
4743     }
4744 
4745     private native Class<?>[] getPermittedSubclasses0();
4746 }
--- EOF ---