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      * parameters 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 parameters 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     /**
2254      * Returns an array containing {@code Method} objects reflecting all the
2255      * declared methods of the class or interface represented by this {@code
2256      * Class} object, including public, protected, default (package)
2257      * access, and private methods, but excluding inherited methods.
2258      *
2259      * <p> If this {@code Class} object represents a type that has multiple
2260      * declared methods with the same name and parameter types, but different
2261      * return types, then the returned array has a {@code Method} object for
2262      * each such method.
2263      *
2264      * <p> If this {@code Class} object represents a type that has a class
2265      * initialization method {@code <clinit>}, then the returned array does
2266      * <em>not</em> have a corresponding {@code Method} object.
2267      *
2268      * <p> If this {@code Class} object represents a class or interface with no
2269      * declared methods, then the returned array has length 0.
2270      *
2271      * <p> If this {@code Class} object represents an array type, a primitive
2272      * type, or void, then the returned array has length 0.
2273      *
2274      * <p> The elements in the returned array are not sorted and are not in any
2275      * particular order.
2276      *
2277      * @return  the array of {@code Method} objects representing all the
2278      *          declared methods of this class
2279      * @throws  SecurityException
2280      *          If a security manager, <i>s</i>, is present and any of the
2281      *          following conditions is met:
2282      *
2283      *          <ul>
2284      *
2285      *          <li> the caller's class loader is not the same as the
2286      *          class loader of this class and invocation of
2287      *          {@link SecurityManager#checkPermission
2288      *          s.checkPermission} method with
2289      *          {@code RuntimePermission("accessDeclaredMembers")}
2290      *          denies access to the declared methods within this class
2291      *
2292      *          <li> the caller's class loader is not the same as or an
2293      *          ancestor of the class loader for the current class and
2294      *          invocation of {@link SecurityManager#checkPackageAccess
2295      *          s.checkPackageAccess()} denies access to the package
2296      *          of this class
2297      *
2298      *          </ul>
2299      *
2300      * @jls 8.2 Class Members
2301      * @jls 8.4 Method Declarations
2302      * @since 1.1
2303      */
2304     @CallerSensitive
2305     public Method[] getDeclaredMethods() throws SecurityException {
2306         SecurityManager sm = System.getSecurityManager();
2307         if (sm != null) {
2308             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2309         }
2310         return copyMethods(privateGetDeclaredMethods(false));
2311     }
2312 
2313 
2314     /**
2315      * Returns an array of {@code Constructor} objects reflecting all the
2316      * constructors declared by the class represented by this
2317      * {@code Class} object. These are public, protected, default
2318      * (package) access, and private constructors.  The elements in the array
2319      * returned are not sorted and are not in any particular order.  If the
2320      * class has a default constructor, it is included in the returned array.
2321      * This method returns an array of length 0 if this {@code Class}
2322      * object represents an interface, a primitive type, an array class, or
2323      * void.
2324      *
2325      * <p> See <em>The Java Language Specification</em>, section 8.2.
2326      *
2327      * @return  the array of {@code Constructor} objects representing all the
2328      *          declared constructors of this class
2329      * @throws  SecurityException
2330      *          If a security manager, <i>s</i>, is present and any of the
2331      *          following conditions is met:
2332      *
2333      *          <ul>
2334      *
2335      *          <li> the caller's class loader is not the same as the
2336      *          class loader of this class and invocation of
2337      *          {@link SecurityManager#checkPermission
2338      *          s.checkPermission} method with
2339      *          {@code RuntimePermission("accessDeclaredMembers")}
2340      *          denies access to the declared constructors within this class
2341      *
2342      *          <li> the caller's class loader is not the same as or an
2343      *          ancestor of the class loader for the current class and
2344      *          invocation of {@link SecurityManager#checkPackageAccess
2345      *          s.checkPackageAccess()} denies access to the package
2346      *          of this class
2347      *
2348      *          </ul>
2349      *
2350      * @since 1.1
2351      */
2352     @CallerSensitive
2353     public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
2354         SecurityManager sm = System.getSecurityManager();
2355         if (sm != null) {
2356             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2357         }
2358         return copyConstructors(privateGetDeclaredConstructors(false));
2359     }
2360 
2361 
2362     /**
2363      * Returns a {@code Field} object that reflects the specified declared
2364      * field of the class or interface represented by this {@code Class}
2365      * object. The {@code name} parameter is a {@code String} that specifies
2366      * the simple name of the desired field.
2367      *
2368      * <p> If this {@code Class} object represents an array type, then this
2369      * method does not find the {@code length} field of the array type.
2370      *
2371      * @param name the name of the field
2372      * @return  the {@code Field} object for the specified field in this
2373      *          class
2374      * @throws  NoSuchFieldException if a field with the specified name is
2375      *          not found.
2376      * @throws  NullPointerException if {@code name} is {@code null}
2377      * @throws  SecurityException
2378      *          If a security manager, <i>s</i>, is present and any of the
2379      *          following conditions is met:
2380      *
2381      *          <ul>
2382      *
2383      *          <li> the caller's class loader is not the same as the
2384      *          class loader of this class and invocation of
2385      *          {@link SecurityManager#checkPermission
2386      *          s.checkPermission} method with
2387      *          {@code RuntimePermission("accessDeclaredMembers")}
2388      *          denies access to the declared field
2389      *
2390      *          <li> the caller's class loader is not the same as or an
2391      *          ancestor of the class loader for the current class and
2392      *          invocation of {@link SecurityManager#checkPackageAccess
2393      *          s.checkPackageAccess()} denies access to the package
2394      *          of this class
2395      *
2396      *          </ul>
2397      *
2398      * @since 1.1
2399      * @jls 8.2 Class Members
2400      * @jls 8.3 Field Declarations
2401      */
2402     @CallerSensitive
2403     public Field getDeclaredField(String name)
2404         throws NoSuchFieldException, SecurityException {
2405         Objects.requireNonNull(name);
2406         SecurityManager sm = System.getSecurityManager();
2407         if (sm != null) {
2408             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2409         }
2410         Field field = searchFields(privateGetDeclaredFields(false), name);
2411         if (field == null) {
2412             throw new NoSuchFieldException(name);
2413         }
2414         return getReflectionFactory().copyField(field);
2415     }
2416 
2417 
2418     /**
2419      * Returns a {@code Method} object that reflects the specified
2420      * declared method of the class or interface represented by this
2421      * {@code Class} object. The {@code name} parameter is a
2422      * {@code String} that specifies the simple name of the desired
2423      * method, and the {@code parameterTypes} parameter is an array of
2424      * {@code Class} objects that identify the method's formal parameter
2425      * types, in declared order.  If more than one method with the same
2426      * parameter types is declared in a class, and one of these methods has a
2427      * return type that is more specific than any of the others, that method is
2428      * returned; otherwise one of the methods is chosen arbitrarily.  If the
2429      * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
2430      * is raised.
2431      *
2432      * <p> If this {@code Class} object represents an array type, then this
2433      * method does not find the {@code clone()} method.
2434      *
2435      * @param name the name of the method
2436      * @param parameterTypes the parameter array
2437      * @return  the {@code Method} object for the method of this class
2438      *          matching the specified name and parameters
2439      * @throws  NoSuchMethodException if a matching method is not found.
2440      * @throws  NullPointerException if {@code name} is {@code null}
2441      * @throws  SecurityException
2442      *          If a security manager, <i>s</i>, is present and any of the
2443      *          following conditions is met:
2444      *
2445      *          <ul>
2446      *
2447      *          <li> the caller's class loader is not the same as the
2448      *          class loader of this class and invocation of
2449      *          {@link SecurityManager#checkPermission
2450      *          s.checkPermission} method with
2451      *          {@code RuntimePermission("accessDeclaredMembers")}
2452      *          denies access to the declared method
2453      *
2454      *          <li> the caller's class loader is not the same as or an
2455      *          ancestor of the class loader for the current class and
2456      *          invocation of {@link SecurityManager#checkPackageAccess
2457      *          s.checkPackageAccess()} denies access to the package
2458      *          of this class
2459      *
2460      *          </ul>
2461      *
2462      * @jls 8.2 Class Members
2463      * @jls 8.4 Method Declarations
2464      * @since 1.1
2465      */
2466     @CallerSensitive
2467     public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2468         throws NoSuchMethodException, SecurityException {
2469         Objects.requireNonNull(name);
2470         SecurityManager sm = System.getSecurityManager();
2471         if (sm != null) {
2472             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2473         }
2474         Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
2475         if (method == null) {
2476             throw new NoSuchMethodException(methodToString(name, parameterTypes));
2477         }
2478         return getReflectionFactory().copyMethod(method);
2479     }
2480 
2481     /**
2482      * Returns the list of {@code Method} objects for the declared public
2483      * methods of this class or interface that have the specified method name
2484      * and parameter types.
2485      *
2486      * @param name the name of the method
2487      * @param parameterTypes the parameter array
2488      * @return the list of {@code Method} objects for the public methods of
2489      *         this class matching the specified name and parameters
2490      */
2491     List<Method> getDeclaredPublicMethods(String name, Class<?>... parameterTypes) {
2492         Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);
2493         ReflectionFactory factory = getReflectionFactory();
2494         List<Method> result = new ArrayList<>();
2495         for (Method method : methods) {
2496             if (method.getName().equals(name)
2497                 && Arrays.equals(
2498                     factory.getExecutableSharedParameterTypes(method),
2499                     parameterTypes)) {
2500                 result.add(factory.copyMethod(method));
2501             }
2502         }
2503         return result;
2504     }
2505 
2506     /**
2507      * Returns a {@code Constructor} object that reflects the specified
2508      * constructor of the class or interface represented by this
2509      * {@code Class} object.  The {@code parameterTypes} parameter is
2510      * an array of {@code Class} objects that identify the constructor's
2511      * formal parameter types, in declared order.
2512      *
2513      * If this {@code Class} object represents an inner class
2514      * declared in a non-static context, the formal parameter types
2515      * include the explicit enclosing instance as the first parameter.
2516      *
2517      * @param parameterTypes the parameter array
2518      * @return  The {@code Constructor} object for the constructor with the
2519      *          specified parameter list
2520      * @throws  NoSuchMethodException if a matching method is not found.
2521      * @throws  SecurityException
2522      *          If a security manager, <i>s</i>, is present and any of the
2523      *          following conditions is met:
2524      *
2525      *          <ul>
2526      *
2527      *          <li> the caller's class loader is not the same as the
2528      *          class loader of this class and invocation of
2529      *          {@link SecurityManager#checkPermission
2530      *          s.checkPermission} method with
2531      *          {@code RuntimePermission("accessDeclaredMembers")}
2532      *          denies access to the declared constructor
2533      *
2534      *          <li> the caller's class loader is not the same as or an
2535      *          ancestor of the class loader for the current class and
2536      *          invocation of {@link SecurityManager#checkPackageAccess
2537      *          s.checkPackageAccess()} denies access to the package
2538      *          of this class
2539      *
2540      *          </ul>
2541      *
2542      * @since 1.1
2543      */
2544     @CallerSensitive
2545     public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
2546         throws NoSuchMethodException, SecurityException
2547     {
2548         SecurityManager sm = System.getSecurityManager();
2549         if (sm != null) {
2550             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2551         }
2552 
2553         return getReflectionFactory().copyConstructor(
2554             getConstructor0(parameterTypes, Member.DECLARED));
2555     }
2556 
2557     /**
2558      * Finds a resource with a given name.
2559      *
2560      * <p> If this class is in a named {@link Module Module} then this method
2561      * will attempt to find the resource in the module. This is done by
2562      * delegating to the module's class loader {@link
2563      * ClassLoader#findResource(String,String) findResource(String,String)}
2564      * method, invoking it with the module name and the absolute name of the
2565      * resource. Resources in named modules are subject to the rules for
2566      * encapsulation specified in the {@code Module} {@link
2567      * Module#getResourceAsStream getResourceAsStream} method and so this
2568      * method returns {@code null} when the resource is a
2569      * non-"{@code .class}" resource in a package that is not open to the
2570      * caller's module.
2571      *
2572      * <p> Otherwise, if this class is not in a named module then the rules for
2573      * searching resources associated with a given class are implemented by the
2574      * defining {@linkplain ClassLoader class loader} of the class.  This method
2575      * delegates to this object's class loader.  If this object was loaded by
2576      * the bootstrap class loader, the method delegates to {@link
2577      * ClassLoader#getSystemResourceAsStream}.
2578      *
2579      * <p> Before delegation, an absolute resource name is constructed from the
2580      * given resource name using this algorithm:
2581      *
2582      * <ul>
2583      *
2584      * <li> If the {@code name} begins with a {@code '/'}
2585      * (<code>'\u002f'</code>), then the absolute name of the resource is the
2586      * portion of the {@code name} following the {@code '/'}.
2587      *
2588      * <li> Otherwise, the absolute name is of the following form:
2589      *
2590      * <blockquote>
2591      *   {@code modified_package_name/name}
2592      * </blockquote>
2593      *
2594      * <p> Where the {@code modified_package_name} is the package name of this
2595      * object with {@code '/'} substituted for {@code '.'}
2596      * (<code>'\u002e'</code>).
2597      *
2598      * </ul>
2599      *
2600      * @param  name name of the desired resource
2601      * @return  A {@link java.io.InputStream} object; {@code null} if no
2602      *          resource with this name is found, the resource is in a package
2603      *          that is not {@linkplain Module#isOpen(String, Module) open} to at
2604      *          least the caller module, or access to the resource is denied
2605      *          by the security manager.
2606      * @throws  NullPointerException If {@code name} is {@code null}
2607      *
2608      * @see Module#getResourceAsStream(String)
2609      * @since  1.1
2610      * @revised 9
2611      * @spec JPMS
2612      */
2613     @CallerSensitive
2614     public InputStream getResourceAsStream(String name) {
2615         name = resolveName(name);
2616 
2617         Module thisModule = getModule();
2618         if (thisModule.isNamed()) {
2619             // check if resource can be located by caller
2620             if (Resources.canEncapsulate(name)
2621                 && !isOpenToCaller(name, Reflection.getCallerClass())) {
2622                 return null;
2623             }
2624 
2625             // resource not encapsulated or in package open to caller
2626             String mn = thisModule.getName();
2627             ClassLoader cl = getClassLoader0();
2628             try {
2629 
2630                 // special-case built-in class loaders to avoid the
2631                 // need for a URL connection
2632                 if (cl == null) {
2633                     return BootLoader.findResourceAsStream(mn, name);
2634                 } else if (cl instanceof BuiltinClassLoader) {
2635                     return ((BuiltinClassLoader) cl).findResourceAsStream(mn, name);
2636                 } else {
2637                     URL url = cl.findResource(mn, name);
2638                     return (url != null) ? url.openStream() : null;
2639                 }
2640 
2641             } catch (IOException | SecurityException e) {
2642                 return null;
2643             }
2644         }
2645 
2646         // unnamed module
2647         ClassLoader cl = getClassLoader0();
2648         if (cl == null) {
2649             return ClassLoader.getSystemResourceAsStream(name);
2650         } else {
2651             return cl.getResourceAsStream(name);
2652         }
2653     }
2654 
2655     /**
2656      * Finds a resource with a given name.
2657      *
2658      * <p> If this class is in a named {@link Module Module} then this method
2659      * will attempt to find the resource in the module. This is done by
2660      * delegating to the module's class loader {@link
2661      * ClassLoader#findResource(String,String) findResource(String,String)}
2662      * method, invoking it with the module name and the absolute name of the
2663      * resource. Resources in named modules are subject to the rules for
2664      * encapsulation specified in the {@code Module} {@link
2665      * Module#getResourceAsStream getResourceAsStream} method and so this
2666      * method returns {@code null} when the resource is a
2667      * non-"{@code .class}" resource in a package that is not open to the
2668      * caller's module.
2669      *
2670      * <p> Otherwise, if this class is not in a named module then the rules for
2671      * searching resources associated with a given class are implemented by the
2672      * defining {@linkplain ClassLoader class loader} of the class.  This method
2673      * delegates to this object's class loader. If this object was loaded by
2674      * the bootstrap class loader, the method delegates to {@link
2675      * ClassLoader#getSystemResource}.
2676      *
2677      * <p> Before delegation, an absolute resource name is constructed from the
2678      * given resource name using this algorithm:
2679      *
2680      * <ul>
2681      *
2682      * <li> If the {@code name} begins with a {@code '/'}
2683      * (<code>'\u002f'</code>), then the absolute name of the resource is the
2684      * portion of the {@code name} following the {@code '/'}.
2685      *
2686      * <li> Otherwise, the absolute name is of the following form:
2687      *
2688      * <blockquote>
2689      *   {@code modified_package_name/name}
2690      * </blockquote>
2691      *
2692      * <p> Where the {@code modified_package_name} is the package name of this
2693      * object with {@code '/'} substituted for {@code '.'}
2694      * (<code>'\u002e'</code>).
2695      *
2696      * </ul>
2697      *
2698      * @param  name name of the desired resource
2699      * @return A {@link java.net.URL} object; {@code null} if no resource with
2700      *         this name is found, the resource cannot be located by a URL, the
2701      *         resource is in a package that is not
2702      *         {@linkplain Module#isOpen(String, Module) open} to at least the caller
2703      *         module, or access to the resource is denied by the security
2704      *         manager.
2705      * @throws NullPointerException If {@code name} is {@code null}
2706      * @since  1.1
2707      * @revised 9
2708      * @spec JPMS
2709      */
2710     @CallerSensitive
2711     public URL getResource(String name) {
2712         name = resolveName(name);
2713 
2714         Module thisModule = getModule();
2715         if (thisModule.isNamed()) {
2716             // check if resource can be located by caller
2717             if (Resources.canEncapsulate(name)
2718                 && !isOpenToCaller(name, Reflection.getCallerClass())) {
2719                 return null;
2720             }
2721 
2722             // resource not encapsulated or in package open to caller
2723             String mn = thisModule.getName();
2724             ClassLoader cl = getClassLoader0();
2725             try {
2726                 if (cl == null) {
2727                     return BootLoader.findResource(mn, name);
2728                 } else {
2729                     return cl.findResource(mn, name);
2730                 }
2731             } catch (IOException ioe) {
2732                 return null;
2733             }
2734         }
2735 
2736         // unnamed module
2737         ClassLoader cl = getClassLoader0();
2738         if (cl == null) {
2739             return ClassLoader.getSystemResource(name);
2740         } else {
2741             return cl.getResource(name);
2742         }
2743     }
2744 
2745     /**
2746      * Returns true if a resource with the given name can be located by the
2747      * given caller. All resources in a module can be located by code in
2748      * the module. For other callers, then the package needs to be open to
2749      * the caller.
2750      */
2751     private boolean isOpenToCaller(String name, Class<?> caller) {
2752         // assert getModule().isNamed();
2753         Module thisModule = getModule();
2754         Module callerModule = (caller != null) ? caller.getModule() : null;
2755         if (callerModule != thisModule) {
2756             String pn = Resources.toPackageName(name);
2757             if (thisModule.getDescriptor().packages().contains(pn)) {
2758                 if (callerModule == null && !thisModule.isOpen(pn)) {
2759                     // no caller, package not open
2760                     return false;
2761                 }
2762                 if (!thisModule.isOpen(pn, callerModule)) {
2763                     // package not open to caller
2764                     return false;
2765                 }
2766             }
2767         }
2768         return true;
2769     }
2770 
2771 
2772     /** protection domain returned when the internal domain is null */
2773     private static java.security.ProtectionDomain allPermDomain;
2774 
2775     /**
2776      * Returns the {@code ProtectionDomain} of this class.  If there is a
2777      * security manager installed, this method first calls the security
2778      * manager's {@code checkPermission} method with a
2779      * {@code RuntimePermission("getProtectionDomain")} permission to
2780      * ensure it's ok to get the
2781      * {@code ProtectionDomain}.
2782      *
2783      * @return the ProtectionDomain of this class
2784      *
2785      * @throws SecurityException
2786      *        if a security manager exists and its
2787      *        {@code checkPermission} method doesn't allow
2788      *        getting the ProtectionDomain.
2789      *
2790      * @see java.security.ProtectionDomain
2791      * @see SecurityManager#checkPermission
2792      * @see java.lang.RuntimePermission
2793      * @since 1.2
2794      */
2795     public java.security.ProtectionDomain getProtectionDomain() {
2796         SecurityManager sm = System.getSecurityManager();
2797         if (sm != null) {
2798             sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
2799         }
2800         java.security.ProtectionDomain pd = getProtectionDomain0();
2801         if (pd == null) {
2802             if (allPermDomain == null) {
2803                 java.security.Permissions perms =
2804                     new java.security.Permissions();
2805                 perms.add(SecurityConstants.ALL_PERMISSION);
2806                 allPermDomain =
2807                     new java.security.ProtectionDomain(null, perms);
2808             }
2809             pd = allPermDomain;
2810         }
2811         return pd;
2812     }
2813 
2814 
2815     /**
2816      * Returns the ProtectionDomain of this class.
2817      */
2818     private native java.security.ProtectionDomain getProtectionDomain0();
2819 
2820     /*
2821      * Return the Virtual Machine's Class object for the named
2822      * primitive type.
2823      */
2824     static native Class<?> getPrimitiveClass(String name);
2825 
2826     /*
2827      * Check if client is allowed to access members.  If access is denied,
2828      * throw a SecurityException.
2829      *
2830      * This method also enforces package access.
2831      *
2832      * <p> Default policy: allow all clients access with normal Java access
2833      * control.
2834      *
2835      * <p> NOTE: should only be called if a SecurityManager is installed
2836      */
2837     private void checkMemberAccess(SecurityManager sm, int which,
2838                                    Class<?> caller, boolean checkProxyInterfaces) {
2839         /* Default policy allows access to all {@link Member#PUBLIC} members,
2840          * as well as access to classes that have the same class loader as the caller.
2841          * In all other cases, it requires RuntimePermission("accessDeclaredMembers")
2842          * permission.
2843          */
2844         final ClassLoader ccl = ClassLoader.getClassLoader(caller);
2845         if (which != Member.PUBLIC) {
2846             final ClassLoader cl = getClassLoader0();
2847             if (ccl != cl) {
2848                 sm.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
2849             }
2850         }
2851         this.checkPackageAccess(sm, ccl, checkProxyInterfaces);
2852     }
2853 
2854     /*
2855      * Checks if a client loaded in ClassLoader ccl is allowed to access this
2856      * class under the current package access policy. If access is denied,
2857      * throw a SecurityException.
2858      *
2859      * NOTE: this method should only be called if a SecurityManager is active
2860      */
2861     private void checkPackageAccess(SecurityManager sm, final ClassLoader ccl,
2862                                     boolean checkProxyInterfaces) {
2863         final ClassLoader cl = getClassLoader0();
2864 
2865         if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
2866             String pkg = this.getPackageName();
2867             if (pkg != null && !pkg.isEmpty()) {
2868                 // skip the package access check on a proxy class in default proxy package
2869                 if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {
2870                     sm.checkPackageAccess(pkg);
2871                 }
2872             }
2873         }
2874         // check package access on the proxy interfaces
2875         if (checkProxyInterfaces && Proxy.isProxyClass(this)) {
2876             ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());
2877         }
2878     }
2879 
2880     /**
2881      * Add a package name prefix if the name is not absolute Remove leading "/"
2882      * if name is absolute
2883      */
2884     private String resolveName(String name) {
2885         if (!name.startsWith("/")) {
2886             Class<?> c = this;
2887             while (c.isArray()) {
2888                 c = c.getComponentType();
2889             }
2890             String baseName = c.getPackageName();
2891             if (baseName != null && !baseName.isEmpty()) {
2892                 name = baseName.replace('.', '/') + "/" + name;
2893             }
2894         } else {
2895             name = name.substring(1);
2896         }
2897         return name;
2898     }
2899 
2900     /**
2901      * Atomic operations support.
2902      */
2903     private static class Atomic {
2904         // initialize Unsafe machinery here, since we need to call Class.class instance method
2905         // and have to avoid calling it in the static initializer of the Class class...
2906         private static final Unsafe unsafe = Unsafe.getUnsafe();
2907         // offset of Class.reflectionData instance field
2908         private static final long reflectionDataOffset
2909                 = unsafe.objectFieldOffset(Class.class, "reflectionData");
2910         // offset of Class.annotationType instance field
2911         private static final long annotationTypeOffset
2912                 = unsafe.objectFieldOffset(Class.class, "annotationType");
2913         // offset of Class.annotationData instance field
2914         private static final long annotationDataOffset
2915                 = unsafe.objectFieldOffset(Class.class, "annotationData");
2916 
2917         static <T> boolean casReflectionData(Class<?> clazz,
2918                                              SoftReference<ReflectionData<T>> oldData,
2919                                              SoftReference<ReflectionData<T>> newData) {
2920             return unsafe.compareAndSetReference(clazz, reflectionDataOffset, oldData, newData);
2921         }
2922 
2923         static <T> boolean casAnnotationType(Class<?> clazz,
2924                                              AnnotationType oldType,
2925                                              AnnotationType newType) {
2926             return unsafe.compareAndSetReference(clazz, annotationTypeOffset, oldType, newType);
2927         }
2928 
2929         static <T> boolean casAnnotationData(Class<?> clazz,
2930                                              AnnotationData oldData,
2931                                              AnnotationData newData) {
2932             return unsafe.compareAndSetReference(clazz, annotationDataOffset, oldData, newData);
2933         }
2934     }
2935 
2936     /**
2937      * Reflection support.
2938      */
2939 
2940     // Reflection data caches various derived names and reflective members. Cached
2941     // values may be invalidated when JVM TI RedefineClasses() is called
2942     private static class ReflectionData<T> {
2943         volatile Field[] declaredFields;
2944         volatile Field[] publicFields;
2945         volatile Method[] declaredMethods;
2946         volatile Method[] publicMethods;
2947         volatile Constructor<T>[] declaredConstructors;
2948         volatile Constructor<T>[] publicConstructors;
2949         // Intermediate results for getFields and getMethods
2950         volatile Field[] declaredPublicFields;
2951         volatile Method[] declaredPublicMethods;
2952         volatile Class<?>[] interfaces;
2953 
2954         // Cached names
2955         String simpleName;
2956         String canonicalName;
2957         static final String NULL_SENTINEL = new String();
2958 
2959         // Value of classRedefinedCount when we created this ReflectionData instance
2960         final int redefinedCount;
2961 
2962         ReflectionData(int redefinedCount) {
2963             this.redefinedCount = redefinedCount;
2964         }
2965     }
2966 
2967     private transient volatile SoftReference<ReflectionData<T>> reflectionData;
2968 
2969     // Incremented by the VM on each call to JVM TI RedefineClasses()
2970     // that redefines this class or a superclass.
2971     private transient volatile int classRedefinedCount;
2972 
2973     // Lazily create and cache ReflectionData
2974     private ReflectionData<T> reflectionData() {
2975         SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
2976         int classRedefinedCount = this.classRedefinedCount;
2977         ReflectionData<T> rd;
2978         if (reflectionData != null &&
2979             (rd = reflectionData.get()) != null &&
2980             rd.redefinedCount == classRedefinedCount) {
2981             return rd;
2982         }
2983         // else no SoftReference or cleared SoftReference or stale ReflectionData
2984         // -> create and replace new instance
2985         return newReflectionData(reflectionData, classRedefinedCount);
2986     }
2987 
2988     private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
2989                                                 int classRedefinedCount) {
2990         while (true) {
2991             ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
2992             // try to CAS it...
2993             if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
2994                 return rd;
2995             }
2996             // else retry
2997             oldReflectionData = this.reflectionData;
2998             classRedefinedCount = this.classRedefinedCount;
2999             if (oldReflectionData != null &&
3000                 (rd = oldReflectionData.get()) != null &&
3001                 rd.redefinedCount == classRedefinedCount) {
3002                 return rd;
3003             }
3004         }
3005     }
3006 
3007     // Generic signature handling
3008     private native String getGenericSignature0();
3009 
3010     // Generic info repository; lazily initialized
3011     private transient volatile ClassRepository genericInfo;
3012 
3013     // accessor for factory
3014     private GenericsFactory getFactory() {
3015         // create scope and factory
3016         return CoreReflectionFactory.make(this, ClassScope.make(this));
3017     }
3018 
3019     // accessor for generic info repository;
3020     // generic info is lazily initialized
3021     private ClassRepository getGenericInfo() {
3022         ClassRepository genericInfo = this.genericInfo;
3023         if (genericInfo == null) {
3024             String signature = getGenericSignature0();
3025             if (signature == null) {
3026                 genericInfo = ClassRepository.NONE;
3027             } else {
3028                 genericInfo = ClassRepository.make(signature, getFactory());
3029             }
3030             this.genericInfo = genericInfo;
3031         }
3032         return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
3033     }
3034 
3035     // Annotations handling
3036     native byte[] getRawAnnotations();
3037     // Since 1.8
3038     native byte[] getRawTypeAnnotations();
3039     static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
3040         return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
3041     }
3042 
3043     native ConstantPool getConstantPool();
3044 
3045     //
3046     //
3047     // java.lang.reflect.Field handling
3048     //
3049     //
3050 
3051     // Returns an array of "root" fields. These Field objects must NOT
3052     // be propagated to the outside world, but must instead be copied
3053     // via ReflectionFactory.copyField.
3054     private Field[] privateGetDeclaredFields(boolean publicOnly) {
3055         Field[] res;
3056         ReflectionData<T> rd = reflectionData();
3057         if (rd != null) {
3058             res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
3059             if (res != null) return res;
3060         }
3061         // No cached value available; request value from VM
3062         res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
3063         if (rd != null) {
3064             if (publicOnly) {
3065                 rd.declaredPublicFields = res;
3066             } else {
3067                 rd.declaredFields = res;
3068             }
3069         }
3070         return res;
3071     }
3072 
3073     // Returns an array of "root" fields. These Field objects must NOT
3074     // be propagated to the outside world, but must instead be copied
3075     // via ReflectionFactory.copyField.
3076     private Field[] privateGetPublicFields() {
3077         Field[] res;
3078         ReflectionData<T> rd = reflectionData();
3079         if (rd != null) {
3080             res = rd.publicFields;
3081             if (res != null) return res;
3082         }
3083 
3084         // Use a linked hash set to ensure order is preserved and
3085         // fields from common super interfaces are not duplicated
3086         LinkedHashSet<Field> fields = new LinkedHashSet<>();
3087 
3088         // Local fields
3089         addAll(fields, privateGetDeclaredFields(true));
3090 
3091         // Direct superinterfaces, recursively
3092         for (Class<?> si : getInterfaces()) {
3093             addAll(fields, si.privateGetPublicFields());
3094         }
3095 
3096         // Direct superclass, recursively
3097         Class<?> sc = getSuperclass();
3098         if (sc != null) {
3099             addAll(fields, sc.privateGetPublicFields());
3100         }
3101 
3102         res = fields.toArray(new Field[0]);
3103         if (rd != null) {
3104             rd.publicFields = res;
3105         }
3106         return res;
3107     }
3108 
3109     private static void addAll(Collection<Field> c, Field[] o) {
3110         for (Field f : o) {
3111             c.add(f);
3112         }
3113     }
3114 
3115 
3116     //
3117     //
3118     // java.lang.reflect.Constructor handling
3119     //
3120     //
3121 
3122     // Returns an array of "root" constructors. These Constructor
3123     // objects must NOT be propagated to the outside world, but must
3124     // instead be copied via ReflectionFactory.copyConstructor.
3125     private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
3126         Constructor<T>[] res;
3127         ReflectionData<T> rd = reflectionData();
3128         if (rd != null) {
3129             res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
3130             if (res != null) return res;
3131         }
3132         // No cached value available; request value from VM
3133         if (isInterface()) {
3134             @SuppressWarnings("unchecked")
3135             Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
3136             res = temporaryRes;
3137         } else {
3138             res = getDeclaredConstructors0(publicOnly);
3139         }
3140         if (rd != null) {
3141             if (publicOnly) {
3142                 rd.publicConstructors = res;
3143             } else {
3144                 rd.declaredConstructors = res;
3145             }
3146         }
3147         return res;
3148     }
3149 
3150     //
3151     //
3152     // java.lang.reflect.Method handling
3153     //
3154     //
3155 
3156     // Returns an array of "root" methods. These Method objects must NOT
3157     // be propagated to the outside world, but must instead be copied
3158     // via ReflectionFactory.copyMethod.
3159     private Method[] privateGetDeclaredMethods(boolean publicOnly) {
3160         Method[] res;
3161         ReflectionData<T> rd = reflectionData();
3162         if (rd != null) {
3163             res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
3164             if (res != null) return res;
3165         }
3166         // No cached value available; request value from VM
3167         res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
3168         if (rd != null) {
3169             if (publicOnly) {
3170                 rd.declaredPublicMethods = res;
3171             } else {
3172                 rd.declaredMethods = res;
3173             }
3174         }
3175         return res;
3176     }
3177 
3178     // Returns an array of "root" methods. These Method objects must NOT
3179     // be propagated to the outside world, but must instead be copied
3180     // via ReflectionFactory.copyMethod.
3181     private Method[] privateGetPublicMethods() {
3182         Method[] res;
3183         ReflectionData<T> rd = reflectionData();
3184         if (rd != null) {
3185             res = rd.publicMethods;
3186             if (res != null) return res;
3187         }
3188 
3189         // No cached value available; compute value recursively.
3190         // Start by fetching public declared methods...
3191         PublicMethods pms = new PublicMethods();
3192         for (Method m : privateGetDeclaredMethods(/* publicOnly */ true)) {
3193             pms.merge(m);
3194         }
3195         // ...then recur over superclass methods...
3196         Class<?> sc = getSuperclass();
3197         if (sc != null) {
3198             for (Method m : sc.privateGetPublicMethods()) {
3199                 pms.merge(m);
3200             }
3201         }
3202         // ...and finally over direct superinterfaces.
3203         for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
3204             for (Method m : intf.privateGetPublicMethods()) {
3205                 // static interface methods are not inherited
3206                 if (!Modifier.isStatic(m.getModifiers())) {
3207                     pms.merge(m);
3208                 }
3209             }
3210         }
3211 
3212         res = pms.toArray();
3213         if (rd != null) {
3214             rd.publicMethods = res;
3215         }
3216         return res;
3217     }
3218 
3219 
3220     //
3221     // Helpers for fetchers of one field, method, or constructor
3222     //
3223 
3224     // This method does not copy the returned Field object!
3225     private static Field searchFields(Field[] fields, String name) {
3226         for (Field field : fields) {
3227             if (field.getName().equals(name)) {
3228                 return field;
3229             }
3230         }
3231         return null;
3232     }
3233 
3234     // Returns a "root" Field object. This Field object must NOT
3235     // be propagated to the outside world, but must instead be copied
3236     // via ReflectionFactory.copyField.
3237     private Field getField0(String name) {
3238         // Note: the intent is that the search algorithm this routine
3239         // uses be equivalent to the ordering imposed by
3240         // privateGetPublicFields(). It fetches only the declared
3241         // public fields for each class, however, to reduce the number
3242         // of Field objects which have to be created for the common
3243         // case where the field being requested is declared in the
3244         // class which is being queried.
3245         Field res;
3246         // Search declared public fields
3247         if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
3248             return res;
3249         }
3250         // Direct superinterfaces, recursively
3251         Class<?>[] interfaces = getInterfaces(/* cloneArray */ false);
3252         for (Class<?> c : interfaces) {
3253             if ((res = c.getField0(name)) != null) {
3254                 return res;
3255             }
3256         }
3257         // Direct superclass, recursively
3258         if (!isInterface()) {
3259             Class<?> c = getSuperclass();
3260             if (c != null) {
3261                 if ((res = c.getField0(name)) != null) {
3262                     return res;
3263                 }
3264             }
3265         }
3266         return null;
3267     }
3268 
3269     // This method does not copy the returned Method object!
3270     private static Method searchMethods(Method[] methods,
3271                                         String name,
3272                                         Class<?>[] parameterTypes)
3273     {
3274         ReflectionFactory fact = getReflectionFactory();
3275         Method res = null;
3276         for (Method m : methods) {
3277             if (m.getName().equals(name)
3278                 && arrayContentsEq(parameterTypes,
3279                                    fact.getExecutableSharedParameterTypes(m))
3280                 && (res == null
3281                     || (res.getReturnType() != m.getReturnType()
3282                         && res.getReturnType().isAssignableFrom(m.getReturnType()))))
3283                 res = m;
3284         }
3285         return res;
3286     }
3287 
3288     private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
3289 
3290     // Returns a "root" Method object. This Method object must NOT
3291     // be propagated to the outside world, but must instead be copied
3292     // via ReflectionFactory.copyMethod.
3293     private Method getMethod0(String name, Class<?>[] parameterTypes) {
3294         PublicMethods.MethodList res = getMethodsRecursive(
3295             name,
3296             parameterTypes == null ? EMPTY_CLASS_ARRAY : parameterTypes,
3297             /* includeStatic */ true);
3298         return res == null ? null : res.getMostSpecific();
3299     }
3300 
3301     // Returns a list of "root" Method objects. These Method objects must NOT
3302     // be propagated to the outside world, but must instead be copied
3303     // via ReflectionFactory.copyMethod.
3304     private PublicMethods.MethodList getMethodsRecursive(String name,
3305                                                          Class<?>[] parameterTypes,
3306                                                          boolean includeStatic) {
3307         // 1st check declared public methods
3308         Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);
3309         PublicMethods.MethodList res = PublicMethods.MethodList
3310             .filter(methods, name, parameterTypes, includeStatic);
3311         // if there is at least one match among declared methods, we need not
3312         // search any further as such match surely overrides matching methods
3313         // declared in superclass(es) or interface(s).
3314         if (res != null) {
3315             return res;
3316         }
3317 
3318         // if there was no match among declared methods,
3319         // we must consult the superclass (if any) recursively...
3320         Class<?> sc = getSuperclass();
3321         if (sc != null) {
3322             res = sc.getMethodsRecursive(name, parameterTypes, includeStatic);
3323         }
3324 
3325         // ...and coalesce the superclass methods with methods obtained
3326         // from directly implemented interfaces excluding static methods...
3327         for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
3328             res = PublicMethods.MethodList.merge(
3329                 res, intf.getMethodsRecursive(name, parameterTypes,
3330                                               /* includeStatic */ false));
3331         }
3332 
3333         return res;
3334     }
3335 
3336     // Returns a "root" Constructor object. This Constructor object must NOT
3337     // be propagated to the outside world, but must instead be copied
3338     // via ReflectionFactory.copyConstructor.
3339     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3340                                         int which) throws NoSuchMethodException
3341     {
3342         ReflectionFactory fact = getReflectionFactory();
3343         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3344         for (Constructor<T> constructor : constructors) {
3345             if (arrayContentsEq(parameterTypes,
3346                                 fact.getExecutableSharedParameterTypes(constructor))) {
3347                 return constructor;
3348             }
3349         }
3350         throw new NoSuchMethodException(methodToString("<init>", parameterTypes));
3351     }
3352 
3353     //
3354     // Other helpers and base implementation
3355     //
3356 
3357     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3358         if (a1 == null) {
3359             return a2 == null || a2.length == 0;
3360         }
3361 
3362         if (a2 == null) {
3363             return a1.length == 0;
3364         }
3365 
3366         if (a1.length != a2.length) {
3367             return false;
3368         }
3369 
3370         for (int i = 0; i < a1.length; i++) {
3371             if (a1[i] != a2[i]) {
3372                 return false;
3373             }
3374         }
3375 
3376         return true;
3377     }
3378 
3379     private static Field[] copyFields(Field[] arg) {
3380         Field[] out = new Field[arg.length];
3381         ReflectionFactory fact = getReflectionFactory();
3382         for (int i = 0; i < arg.length; i++) {
3383             out[i] = fact.copyField(arg[i]);
3384         }
3385         return out;
3386     }
3387 
3388     private static Method[] copyMethods(Method[] arg) {
3389         Method[] out = new Method[arg.length];
3390         ReflectionFactory fact = getReflectionFactory();
3391         for (int i = 0; i < arg.length; i++) {
3392             out[i] = fact.copyMethod(arg[i]);
3393         }
3394         return out;
3395     }
3396 
3397     private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
3398         Constructor<U>[] out = arg.clone();
3399         ReflectionFactory fact = getReflectionFactory();
3400         for (int i = 0; i < out.length; i++) {
3401             out[i] = fact.copyConstructor(out[i]);
3402         }
3403         return out;
3404     }
3405 
3406     private native Field[]       getDeclaredFields0(boolean publicOnly);
3407     private native Method[]      getDeclaredMethods0(boolean publicOnly);
3408     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3409     private native Class<?>[]   getDeclaredClasses0();
3410 
3411     /**
3412      * Helper method to get the method name from arguments.
3413      */
3414     private String methodToString(String name, Class<?>[] argTypes) {
3415         return getName() + '.' + name +
3416                 ((argTypes == null || argTypes.length == 0) ?
3417                 "()" :
3418                 Arrays.stream(argTypes)
3419                         .map(c -> c == null ? "null" : c.getName())
3420                         .collect(Collectors.joining(",", "(", ")")));
3421     }
3422 
3423     /** use serialVersionUID from JDK 1.1 for interoperability */
3424     private static final long serialVersionUID = 3206093459760846163L;
3425 
3426 
3427     /**
3428      * Class Class is special cased within the Serialization Stream Protocol.
3429      *
3430      * A Class instance is written initially into an ObjectOutputStream in the
3431      * following format:
3432      * <pre>
3433      *      {@code TC_CLASS} ClassDescriptor
3434      *      A ClassDescriptor is a special cased serialization of
3435      *      a {@code java.io.ObjectStreamClass} instance.
3436      * </pre>
3437      * A new handle is generated for the initial time the class descriptor
3438      * is written into the stream. Future references to the class descriptor
3439      * are written as references to the initial class descriptor instance.
3440      *
3441      * @see java.io.ObjectStreamClass
3442      */
3443     private static final ObjectStreamField[] serialPersistentFields =
3444         new ObjectStreamField[0];
3445 
3446 
3447     /**
3448      * Returns the assertion status that would be assigned to this
3449      * class if it were to be initialized at the time this method is invoked.
3450      * If this class has had its assertion status set, the most recent
3451      * setting will be returned; otherwise, if any package default assertion
3452      * status pertains to this class, the most recent setting for the most
3453      * specific pertinent package default assertion status is returned;
3454      * otherwise, if this class is not a system class (i.e., it has a
3455      * class loader) its class loader's default assertion status is returned;
3456      * otherwise, the system class default assertion status is returned.
3457      * <p>
3458      * Few programmers will have any need for this method; it is provided
3459      * for the benefit of the JRE itself.  (It allows a class to determine at
3460      * the time that it is initialized whether assertions should be enabled.)
3461      * Note that this method is not guaranteed to return the actual
3462      * assertion status that was (or will be) associated with the specified
3463      * class when it was (or will be) initialized.
3464      *
3465      * @return the desired assertion status of the specified class.
3466      * @see    java.lang.ClassLoader#setClassAssertionStatus
3467      * @see    java.lang.ClassLoader#setPackageAssertionStatus
3468      * @see    java.lang.ClassLoader#setDefaultAssertionStatus
3469      * @since  1.4
3470      */
3471     public boolean desiredAssertionStatus() {
3472         ClassLoader loader = getClassLoader0();
3473         // If the loader is null this is a system class, so ask the VM
3474         if (loader == null)
3475             return desiredAssertionStatus0(this);
3476 
3477         // If the classloader has been initialized with the assertion
3478         // directives, ask it. Otherwise, ask the VM.
3479         synchronized(loader.assertionLock) {
3480             if (loader.classAssertionStatus != null) {
3481                 return loader.desiredAssertionStatus(getName());
3482             }
3483         }
3484         return desiredAssertionStatus0(this);
3485     }
3486 
3487     // Retrieves the desired assertion status of this class from the VM
3488     private static native boolean desiredAssertionStatus0(Class<?> clazz);
3489 
3490     /**
3491      * Returns true if and only if this class was declared as an enum in the
3492      * source code.
3493      *
3494      * @return true if and only if this class was declared as an enum in the
3495      *     source code
3496      * @since 1.5
3497      */
3498     public boolean isEnum() {
3499         // An enum must both directly extend java.lang.Enum and have
3500         // the ENUM bit set; classes for specialized enum constants
3501         // don't do the former.
3502         return (this.getModifiers() & ENUM) != 0 &&
3503         this.getSuperclass() == java.lang.Enum.class;
3504     }
3505 
3506     // Fetches the factory for reflective objects
3507     private static ReflectionFactory getReflectionFactory() {
3508         if (reflectionFactory == null) {
3509             reflectionFactory =
3510                 java.security.AccessController.doPrivileged
3511                     (new ReflectionFactory.GetReflectionFactoryAction());
3512         }
3513         return reflectionFactory;
3514     }
3515     private static ReflectionFactory reflectionFactory;
3516 
3517     /**
3518      * Returns the elements of this enum class or null if this
3519      * Class object does not represent an enum type.
3520      *
3521      * @return an array containing the values comprising the enum class
3522      *     represented by this Class object in the order they're
3523      *     declared, or null if this Class object does not
3524      *     represent an enum type
3525      * @since 1.5
3526      */
3527     public T[] getEnumConstants() {
3528         T[] values = getEnumConstantsShared();
3529         return (values != null) ? values.clone() : null;
3530     }
3531 
3532     /**
3533      * Returns the elements of this enum class or null if this
3534      * Class object does not represent an enum type;
3535      * identical to getEnumConstants except that the result is
3536      * uncloned, cached, and shared by all callers.
3537      */
3538     T[] getEnumConstantsShared() {
3539         T[] constants = enumConstants;
3540         if (constants == null) {
3541             if (!isEnum()) return null;
3542             try {
3543                 final Method values = getMethod("values");
3544                 java.security.AccessController.doPrivileged(
3545                     new java.security.PrivilegedAction<>() {
3546                         public Void run() {
3547                                 values.setAccessible(true);
3548                                 return null;
3549                             }
3550                         });
3551                 @SuppressWarnings("unchecked")
3552                 T[] temporaryConstants = (T[])values.invoke(null);
3553                 enumConstants = constants = temporaryConstants;
3554             }
3555             // These can happen when users concoct enum-like classes
3556             // that don't comply with the enum spec.
3557             catch (InvocationTargetException | NoSuchMethodException |
3558                    IllegalAccessException ex) { return null; }
3559         }
3560         return constants;
3561     }
3562     private transient volatile T[] enumConstants;
3563 
3564     /**
3565      * Returns a map from simple name to enum constant.  This package-private
3566      * method is used internally by Enum to implement
3567      * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}
3568      * efficiently.  Note that the map is returned by this method is
3569      * created lazily on first use.  Typically it won't ever get created.
3570      */
3571     Map<String, T> enumConstantDirectory() {
3572         Map<String, T> directory = enumConstantDirectory;
3573         if (directory == null) {
3574             T[] universe = getEnumConstantsShared();
3575             if (universe == null)
3576                 throw new IllegalArgumentException(
3577                     getName() + " is not an enum type");
3578             directory = new HashMap<>((int)(universe.length / 0.75f) + 1);
3579             for (T constant : universe) {
3580                 directory.put(((Enum<?>)constant).name(), constant);
3581             }
3582             enumConstantDirectory = directory;
3583         }
3584         return directory;
3585     }
3586     private transient volatile Map<String, T> enumConstantDirectory;
3587 
3588     /**
3589      * Casts an object to the class or interface represented
3590      * by this {@code Class} object.
3591      *
3592      * @param obj the object to be cast
3593      * @return the object after casting, or null if obj is null
3594      *
3595      * @throws ClassCastException if the object is not
3596      * null and is not assignable to the type T.
3597      *
3598      * @since 1.5
3599      */
3600     @SuppressWarnings("unchecked")
3601     @HotSpotIntrinsicCandidate
3602     public T cast(Object obj) {
3603         if (obj != null && !isInstance(obj))
3604             throw new ClassCastException(cannotCastMsg(obj));
3605         return (T) obj;
3606     }
3607 
3608     private String cannotCastMsg(Object obj) {
3609         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3610     }
3611 
3612     /**
3613      * Casts this {@code Class} object to represent a subclass of the class
3614      * represented by the specified class object.  Checks that the cast
3615      * is valid, and throws a {@code ClassCastException} if it is not.  If
3616      * this method succeeds, it always returns a reference to this class object.
3617      *
3618      * <p>This method is useful when a client needs to "narrow" the type of
3619      * a {@code Class} object to pass it to an API that restricts the
3620      * {@code Class} objects that it is willing to accept.  A cast would
3621      * generate a compile-time warning, as the correctness of the cast
3622      * could not be checked at runtime (because generic types are implemented
3623      * by erasure).
3624      *
3625      * @param <U> the type to cast this class object to
3626      * @param clazz the class of the type to cast this class object to
3627      * @return this {@code Class} object, cast to represent a subclass of
3628      *    the specified class object.
3629      * @throws ClassCastException if this {@code Class} object does not
3630      *    represent a subclass of the specified class (here "subclass" includes
3631      *    the class itself).
3632      * @since 1.5
3633      */
3634     @SuppressWarnings("unchecked")
3635     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
3636         if (clazz.isAssignableFrom(this))
3637             return (Class<? extends U>) this;
3638         else
3639             throw new ClassCastException(this.toString());
3640     }
3641 
3642     /**
3643      * @throws NullPointerException {@inheritDoc}
3644      * @since 1.5
3645      */
3646     @SuppressWarnings("unchecked")
3647     public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
3648         Objects.requireNonNull(annotationClass);
3649 
3650         return (A) annotationData().annotations.get(annotationClass);
3651     }
3652 
3653     /**
3654      * {@inheritDoc}
3655      * @throws NullPointerException {@inheritDoc}
3656      * @since 1.5
3657      */
3658     @Override
3659     public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
3660         return GenericDeclaration.super.isAnnotationPresent(annotationClass);
3661     }
3662 
3663     /**
3664      * @throws NullPointerException {@inheritDoc}
3665      * @since 1.8
3666      */
3667     @Override
3668     public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {
3669         Objects.requireNonNull(annotationClass);
3670 
3671         AnnotationData annotationData = annotationData();
3672         return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations,
3673                                                           this,
3674                                                           annotationClass);
3675     }
3676 
3677     /**
3678      * @since 1.5
3679      */
3680     public Annotation[] getAnnotations() {
3681         return AnnotationParser.toArray(annotationData().annotations);
3682     }
3683 
3684     /**
3685      * @throws NullPointerException {@inheritDoc}
3686      * @since 1.8
3687      */
3688     @Override
3689     @SuppressWarnings("unchecked")
3690     public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
3691         Objects.requireNonNull(annotationClass);
3692 
3693         return (A) annotationData().declaredAnnotations.get(annotationClass);
3694     }
3695 
3696     /**
3697      * @throws NullPointerException {@inheritDoc}
3698      * @since 1.8
3699      */
3700     @Override
3701     public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {
3702         Objects.requireNonNull(annotationClass);
3703 
3704         return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,
3705                                                                  annotationClass);
3706     }
3707 
3708     /**
3709      * @since 1.5
3710      */
3711     public Annotation[] getDeclaredAnnotations()  {
3712         return AnnotationParser.toArray(annotationData().declaredAnnotations);
3713     }
3714 
3715     // annotation data that might get invalidated when JVM TI RedefineClasses() is called
3716     private static class AnnotationData {
3717         final Map<Class<? extends Annotation>, Annotation> annotations;
3718         final Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
3719 
3720         // Value of classRedefinedCount when we created this AnnotationData instance
3721         final int redefinedCount;
3722 
3723         AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations,
3724                        Map<Class<? extends Annotation>, Annotation> declaredAnnotations,
3725                        int redefinedCount) {
3726             this.annotations = annotations;
3727             this.declaredAnnotations = declaredAnnotations;
3728             this.redefinedCount = redefinedCount;
3729         }
3730     }
3731 
3732     // Annotations cache
3733     @SuppressWarnings("UnusedDeclaration")
3734     private transient volatile AnnotationData annotationData;
3735 
3736     private AnnotationData annotationData() {
3737         while (true) { // retry loop
3738             AnnotationData annotationData = this.annotationData;
3739             int classRedefinedCount = this.classRedefinedCount;
3740             if (annotationData != null &&
3741                 annotationData.redefinedCount == classRedefinedCount) {
3742                 return annotationData;
3743             }
3744             // null or stale annotationData -> optimistically create new instance
3745             AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount);
3746             // try to install it
3747             if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) {
3748                 // successfully installed new AnnotationData
3749                 return newAnnotationData;
3750             }
3751         }
3752     }
3753 
3754     private AnnotationData createAnnotationData(int classRedefinedCount) {
3755         Map<Class<? extends Annotation>, Annotation> declaredAnnotations =
3756             AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this);
3757         Class<?> superClass = getSuperclass();
3758         Map<Class<? extends Annotation>, Annotation> annotations = null;
3759         if (superClass != null) {
3760             Map<Class<? extends Annotation>, Annotation> superAnnotations =
3761                 superClass.annotationData().annotations;
3762             for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) {
3763                 Class<? extends Annotation> annotationClass = e.getKey();
3764                 if (AnnotationType.getInstance(annotationClass).isInherited()) {
3765                     if (annotations == null) { // lazy construction
3766                         annotations = new LinkedHashMap<>((Math.max(
3767                                 declaredAnnotations.size(),
3768                                 Math.min(12, declaredAnnotations.size() + superAnnotations.size())
3769                             ) * 4 + 2) / 3
3770                         );
3771                     }
3772                     annotations.put(annotationClass, e.getValue());
3773                 }
3774             }
3775         }
3776         if (annotations == null) {
3777             // no inherited annotations -> share the Map with declaredAnnotations
3778             annotations = declaredAnnotations;
3779         } else {
3780             // at least one inherited annotation -> declared may override inherited
3781             annotations.putAll(declaredAnnotations);
3782         }
3783         return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount);
3784     }
3785 
3786     // Annotation types cache their internal (AnnotationType) form
3787 
3788     @SuppressWarnings("UnusedDeclaration")
3789     private transient volatile AnnotationType annotationType;
3790 
3791     boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {
3792         return Atomic.casAnnotationType(this, oldType, newType);
3793     }
3794 
3795     AnnotationType getAnnotationType() {
3796         return annotationType;
3797     }
3798 
3799     Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() {
3800         return annotationData().declaredAnnotations;
3801     }
3802 
3803     /* Backing store of user-defined values pertaining to this class.
3804      * Maintained by the ClassValue class.
3805      */
3806     transient ClassValue.ClassValueMap classValueMap;
3807 
3808     /**
3809      * Returns an {@code AnnotatedType} object that represents the use of a
3810      * type to specify the superclass of the entity represented by this {@code
3811      * Class} object. (The <em>use</em> of type Foo to specify the superclass
3812      * in '...  extends Foo' is distinct from the <em>declaration</em> of type
3813      * Foo.)
3814      *
3815      * <p> If this {@code Class} object represents a type whose declaration
3816      * does not explicitly indicate an annotated superclass, then the return
3817      * value is an {@code AnnotatedType} object representing an element with no
3818      * annotations.
3819      *
3820      * <p> If this {@code Class} represents either the {@code Object} class, an
3821      * interface type, an array type, a primitive type, or void, the return
3822      * value is {@code null}.
3823      *
3824      * @return an object representing the superclass
3825      * @since 1.8
3826      */
3827     public AnnotatedType getAnnotatedSuperclass() {
3828         if (this == Object.class ||
3829                 isInterface() ||
3830                 isArray() ||
3831                 isPrimitive() ||
3832                 this == Void.TYPE) {
3833             return null;
3834         }
3835 
3836         return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
3837     }
3838 
3839     /**
3840      * Returns an array of {@code AnnotatedType} objects that represent the use
3841      * of types to specify superinterfaces of the entity represented by this
3842      * {@code Class} object. (The <em>use</em> of type Foo to specify a
3843      * superinterface in '... implements Foo' is distinct from the
3844      * <em>declaration</em> of type Foo.)
3845      *
3846      * <p> If this {@code Class} object represents a class, the return value is
3847      * an array containing objects representing the uses of interface types to
3848      * specify interfaces implemented by the class. The order of the objects in
3849      * the array corresponds to the order of the interface types used in the
3850      * 'implements' clause of the declaration of this {@code Class} object.
3851      *
3852      * <p> If this {@code Class} object represents an interface, the return
3853      * value is an array containing objects representing the uses of interface
3854      * types to specify interfaces directly extended by the interface. The
3855      * order of the objects in the array corresponds to the order of the
3856      * interface types used in the 'extends' clause of the declaration of this
3857      * {@code Class} object.
3858      *
3859      * <p> If this {@code Class} object represents a class or interface whose
3860      * declaration does not explicitly indicate any annotated superinterfaces,
3861      * the return value is an array of length 0.
3862      *
3863      * <p> If this {@code Class} object represents either the {@code Object}
3864      * class, an array type, a primitive type, or void, the return value is an
3865      * array of length 0.
3866      *
3867      * @return an array representing the superinterfaces
3868      * @since 1.8
3869      */
3870     public AnnotatedType[] getAnnotatedInterfaces() {
3871          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3872     }
3873 
3874     private native Class<?> getNestHost0();
3875 
3876     /**
3877      * Returns the nest host of the <a href=#nest>nest</a> to which the class
3878      * or interface represented by this {@code Class} object belongs.
3879      * Every class and interface is a member of exactly one nest.
3880      * A class or interface that is not recorded as belonging to a nest
3881      * belongs to the nest consisting only of itself, and is the nest
3882      * host.
3883      *
3884      * <p>Each of the {@code Class} objects representing array types,
3885      * primitive types, and {@code void} returns {@code this} to indicate
3886      * that the represented entity belongs to the nest consisting only of
3887      * itself, and is the nest host.
3888      *
3889      * <p>If there is a {@linkplain LinkageError linkage error} accessing
3890      * the nest host, or if this class or interface is not enumerated as
3891      * a member of the nest by the nest host, then it is considered to belong
3892      * to its own nest and {@code this} is returned as the host.
3893      *
3894      * @apiNote A {@code class} file of version 55.0 or greater may record the
3895      * host of the nest to which it belongs by using the {@code NestHost}
3896      * attribute (JVMS 4.7.28). Alternatively, a {@code class} file of
3897      * version 55.0 or greater may act as a nest host by enumerating the nest's
3898      * other members with the
3899      * {@code NestMembers} attribute (JVMS 4.7.29).
3900      * A {@code class} file of version 54.0 or lower does not use these
3901      * attributes.
3902      *
3903      * @return the nest host of this class or interface
3904      *
3905      * @throws SecurityException
3906      *         If the returned class is not the current class, and
3907      *         if a security manager, <i>s</i>, is present and the caller's
3908      *         class loader is not the same as or an ancestor of the class
3909      *         loader for the returned class and invocation of {@link
3910      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
3911      *         denies access to the package of the returned class
3912      * @since 11
3913      * @jvms 4.7.28 The {@code NestHost} Attribute
3914      * @jvms 4.7.29 The {@code NestMembers} Attribute
3915      * @jvms 5.4.4 Access Control
3916      */
3917     @CallerSensitive
3918     public Class<?> getNestHost() {
3919         if (isPrimitive() || isArray()) {
3920             return this;
3921         }
3922         Class<?> host;
3923         try {
3924             host = getNestHost0();
3925         } catch (LinkageError e) {
3926             // if we couldn't load our nest-host then we
3927             // act as-if we have no nest-host attribute
3928             return this;
3929         }
3930         // if null then nest membership validation failed, so we
3931         // act as-if we have no nest-host attribute
3932         if (host == null || host == this) {
3933             return this;
3934         }
3935         // returning a different class requires a security check
3936         SecurityManager sm = System.getSecurityManager();
3937         if (sm != null) {
3938             checkPackageAccess(sm,
3939                                ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
3940         }
3941         return host;
3942     }
3943 
3944     /**
3945      * Determines if the given {@code Class} is a nestmate of the
3946      * class or interface represented by this {@code Class} object.
3947      * Two classes or interfaces are nestmates
3948      * if they have the same {@linkplain #getNestHost() nest host}.
3949      *
3950      * @param c the class to check
3951      * @return {@code true} if this class and {@code c} are members of
3952      * the same nest; and {@code false} otherwise.
3953      *
3954      * @since 11
3955      */
3956     public boolean isNestmateOf(Class<?> c) {
3957         if (this == c) {
3958             return true;
3959         }
3960         if (isPrimitive() || isArray() ||
3961             c.isPrimitive() || c.isArray()) {
3962             return false;
3963         }
3964         try {
3965             return getNestHost0() == c.getNestHost0();
3966         } catch (LinkageError e) {
3967             return false;
3968         }
3969     }
3970 
3971     private native Class<?>[] getNestMembers0();
3972 
3973     /**
3974      * Returns an array containing {@code Class} objects representing all the
3975      * classes and interfaces that are members of the nest to which the class
3976      * or interface represented by this {@code Class} object belongs.
3977      * The {@linkplain #getNestHost() nest host} of that nest is the zeroth
3978      * element of the array. Subsequent elements represent any classes or
3979      * interfaces that are recorded by the nest host as being members of
3980      * the nest; the order of such elements is unspecified. Duplicates are
3981      * permitted.
3982      * If the nest host of that nest does not enumerate any members, then the
3983      * array has a single element containing {@code this}.
3984      *
3985      * <p>Each of the {@code Class} objects representing array types,
3986      * primitive types, and {@code void} returns an array containing only
3987      * {@code this}.
3988      *
3989      * <p>This method validates that, for each class or interface which is
3990      * recorded as a member of the nest by the nest host, that class or
3991      * interface records itself as a member of that same nest. Any exceptions
3992      * that occur during this validation are rethrown by this method.
3993      *
3994      * @return an array of all classes and interfaces in the same nest as
3995      * this class
3996      *
3997      * @throws LinkageError
3998      *         If there is any problem loading or validating a nest member or
3999      *         its nest host
4000      * @throws SecurityException
4001      *         If any returned class is not the current class, and
4002      *         if a security manager, <i>s</i>, is present and the caller's
4003      *         class loader is not the same as or an ancestor of the class
4004      *         loader for that returned class and invocation of {@link
4005      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
4006      *         denies access to the package of that returned class
4007      *
4008      * @since 11
4009      * @see #getNestHost()
4010      */
4011     @CallerSensitive
4012     public Class<?>[] getNestMembers() {
4013         if (isPrimitive() || isArray()) {
4014             return new Class<?>[] { this };
4015         }
4016         Class<?>[] members = getNestMembers0();
4017         // Can't actually enable this due to bootstrapping issues
4018         // assert(members.length != 1 || members[0] == this); // expected invariant from VM
4019 
4020         if (members.length > 1) {
4021             // If we return anything other than the current class we need
4022             // a security check
4023             SecurityManager sm = System.getSecurityManager();
4024             if (sm != null) {
4025                 checkPackageAccess(sm,
4026                                    ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
4027             }
4028         }
4029         return members;
4030     }
4031 
4032     /**
4033      * Returns the type descriptor string for this class.
4034      * <p>
4035      * Note that this is not a strict inverse of {@link #forName};
4036      * distinct classes which share a common name but have different class loaders
4037      * will have identical descriptor strings.
4038      *
4039      * @return the type descriptor representation
4040      * @jvms 4.3.2 Field Descriptors
4041      * @since 12
4042      */
4043     @Override
4044     public String descriptorString() {
4045         if (isPrimitive())
4046             return Wrapper.forPrimitiveType(this).basicTypeString();
4047         else if (isArray()) {
4048             return "[" + componentType.descriptorString();
4049         }
4050         else {
4051             return "L" + getName().replace('.', '/') + ";";
4052         }
4053     }
4054 
4055     /**
4056      * Returns the component type of this {@code Class}, if it describes
4057      * an array type, or {@code null} otherwise.
4058      *
4059      * @implSpec
4060      * Equivalent to {@link Class#getComponentType()}.
4061      *
4062      * @return a {@code Class} describing the component type, or {@code null}
4063      * if this {@code Class} does not describe an array type
4064      * @since 12
4065      */
4066     @Override
4067     public Class<?> componentType() {
4068         return isArray() ? componentType : null;
4069     }
4070 
4071     /**
4072      * Returns a {@code Class} for an array type whose component type
4073      * is described by this {@linkplain Class}.
4074      *
4075      * @return a {@code Class} describing the array type
4076      * @since 12
4077      */
4078     @Override
4079     public Class<?> arrayType() {
4080         return Array.newInstance(this, 0).getClass();
4081     }
4082 
4083     /**
4084      * Returns a nominal descriptor for this instance, if one can be
4085      * constructed, or an empty {@link Optional} if one cannot be.
4086      *
4087      * @return An {@link Optional} containing the resulting nominal descriptor,
4088      * or an empty {@link Optional} if one cannot be constructed.
4089      * @since 12
4090      */
4091     @Override
4092     public Optional<ClassDesc> describeConstable() {
4093         return Optional.of(ClassDesc.ofDescriptor(descriptorString()));
4094     }
4095 }