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