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