1 /*
   2  * Copyright (c) 1994, 2018, 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(Stream.of(typeparms).map(Class::typeVarBounds).
 276                           collect(Collectors.joining(",", "<", ">")));
 277             }
 278 
 279             for (int i = 0; i < arrayDepth; i++)
 280                 sb.append("[]");
 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                 Stream.of(bounds).map(Type::getTypeName).
 293                 collect(Collectors.joining(" & "));
 294         }
 295     }
 296 
 297     /**
 298      * Returns the {@code Class} object associated with the class or
 299      * interface with the given string name.  Invoking this method is
 300      * equivalent to:
 301      *
 302      * <blockquote>
 303      *  {@code Class.forName(className, true, currentLoader)}
 304      * </blockquote>
 305      *
 306      * where {@code currentLoader} denotes the defining class loader of
 307      * the current class.
 308      *
 309      * <p> For example, the following code fragment returns the
 310      * runtime {@code Class} descriptor for the class named
 311      * {@code java.lang.Thread}:
 312      *
 313      * <blockquote>
 314      *   {@code Class t = Class.forName("java.lang.Thread")}
 315      * </blockquote>
 316      * <p>
 317      * A call to {@code forName("X")} causes the class named
 318      * {@code X} to be initialized.
 319      *
 320      * @param      className   the fully qualified name of the desired class.
 321      * @return     the {@code Class} object for the class with the
 322      *             specified name.
 323      * @exception LinkageError if the linkage fails
 324      * @exception ExceptionInInitializerError if the initialization provoked
 325      *            by this method fails
 326      * @exception ClassNotFoundException if the class cannot be located
 327      */
 328     @CallerSensitive
 329     public static Class<?> forName(String className)
 330                 throws ClassNotFoundException {
 331         Class<?> caller = Reflection.getCallerClass();
 332         return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
 333     }
 334 
 335 
 336     /**
 337      * Returns the {@code Class} object associated with the class or
 338      * interface with the given string name, using the given class loader.
 339      * Given the fully qualified name for a class or interface (in the same
 340      * format returned by {@code getName}) this method attempts to
 341      * locate, load, and link the class or interface.  The specified class
 342      * loader is used to load the class or interface.  If the parameter
 343      * {@code loader} is null, the class is loaded through the bootstrap
 344      * class loader.  The class is initialized only if the
 345      * {@code initialize} parameter is {@code true} and if it has
 346      * not been initialized earlier.
 347      *
 348      * <p> If {@code name} denotes a primitive type or void, an attempt
 349      * will be made to locate a user-defined class in the unnamed package whose
 350      * name is {@code name}. Therefore, this method cannot be used to
 351      * obtain any of the {@code Class} objects representing primitive
 352      * types or void.
 353      *
 354      * <p> If {@code name} denotes an array class, the component type of
 355      * the array class is loaded but not initialized.
 356      *
 357      * <p> For example, in an instance method the expression:
 358      *
 359      * <blockquote>
 360      *  {@code Class.forName("Foo")}
 361      * </blockquote>
 362      *
 363      * is equivalent to:
 364      *
 365      * <blockquote>
 366      *  {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
 367      * </blockquote>
 368      *
 369      * Note that this method throws errors related to loading, linking or
 370      * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
 371      * Java Language Specification</em>.
 372      * Note that this method does not check whether the requested class
 373      * is accessible to its caller.
 374      *
 375      * @param name       fully qualified name of the desired class
 376      * @param initialize if {@code true} the class will be initialized.
 377      *                   See Section 12.4 of <em>The Java Language Specification</em>.
 378      * @param loader     class loader from which the class must be loaded
 379      * @return           class object representing the desired class
 380      *
 381      * @exception LinkageError if the linkage fails
 382      * @exception ExceptionInInitializerError if the initialization provoked
 383      *            by this method fails
 384      * @exception ClassNotFoundException if the class cannot be located by
 385      *            the specified class loader
 386      * @exception SecurityException
 387      *            if a security manager is present, and the {@code loader} is
 388      *            {@code null}, and the caller's class loader is not
 389      *            {@code null}, and the caller does not have the
 390      *            {@link RuntimePermission}{@code ("getClassLoader")}
 391      *
 392      * @see       java.lang.Class#forName(String)
 393      * @see       java.lang.ClassLoader
 394      * @since     1.2
 395      */
 396     @CallerSensitive
 397     public static Class<?> forName(String name, boolean initialize,
 398                                    ClassLoader loader)
 399         throws ClassNotFoundException
 400     {
 401         Class<?> caller = null;
 402         SecurityManager sm = System.getSecurityManager();
 403         if (sm != null) {
 404             // Reflective call to get caller class is only needed if a security manager
 405             // is present.  Avoid the overhead of making this call otherwise.
 406             caller = Reflection.getCallerClass();
 407             if (loader == null) {
 408                 ClassLoader ccl = ClassLoader.getClassLoader(caller);
 409                 if (ccl != null) {
 410                     sm.checkPermission(
 411                         SecurityConstants.GET_CLASSLOADER_PERMISSION);
 412                 }
 413             }
 414         }
 415         return forName0(name, initialize, loader, caller);
 416     }
 417 
 418     /** Called after security check for system loader access checks have been made. */
 419     private static native Class<?> forName0(String name, boolean initialize,
 420                                             ClassLoader loader,
 421                                             Class<?> caller)
 422         throws ClassNotFoundException;
 423 
 424 
 425     /**
 426      * Returns the {@code Class} with the given <a href="ClassLoader.html#binary-name">
 427      * binary name</a> in the given module.
 428      *
 429      * <p> This method attempts to locate, load, and link the class or interface.
 430      * It does not run the class initializer.  If the class is not found, this
 431      * method returns {@code null}. </p>
 432      *
 433      * <p> If the class loader of the given module defines other modules and
 434      * the given name is a class defined in a different module, this method
 435      * returns {@code null} after the class is loaded. </p>
 436      *
 437      * <p> This method does not check whether the requested class is
 438      * accessible to its caller. </p>
 439      *
 440      * @apiNote
 441      * This method returns {@code null} on failure rather than
 442      * throwing a {@link ClassNotFoundException}, as is done by
 443      * the {@link #forName(String, boolean, ClassLoader)} method.
 444      * The security check is a stack-based permission check if the caller
 445      * loads a class in another module.
 446      *
 447      * @param  module   A module
 448      * @param  name     The <a href="ClassLoader.html#binary-name">binary name</a>
 449      *                  of the class
 450      * @return {@code Class} object of the given name defined in the given module;
 451      *         {@code null} if not found.
 452      *
 453      * @throws NullPointerException if the given module or name is {@code null}
 454      *
 455      * @throws LinkageError if the linkage fails
 456      *
 457      * @throws SecurityException
 458      *         <ul>
 459      *         <li> if the caller is not the specified module and
 460      *         {@code RuntimePermission("getClassLoader")} permission is denied; or</li>
 461      *         <li> access to the module content is denied. For example,
 462      *         permission check will be performed when a class loader calls
 463      *         {@link ModuleReader#open(String)} to read the bytes of a class file
 464      *         in a module.</li>
 465      *         </ul>
 466      *
 467      * @since 9
 468      * @spec JPMS
 469      */
 470     @CallerSensitive
 471     public static Class<?> forName(Module module, String name) {
 472         Objects.requireNonNull(module);
 473         Objects.requireNonNull(name);
 474 
 475         ClassLoader cl;
 476         SecurityManager sm = System.getSecurityManager();
 477         if (sm != null) {
 478             Class<?> caller = Reflection.getCallerClass();
 479             if (caller != null && caller.getModule() != module) {
 480                 // if caller is null, Class.forName is the last java frame on the stack.
 481                 // java.base has all permissions
 482                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 483             }
 484             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
 485             cl = AccessController.doPrivileged(pa);
 486         } else {
 487             cl = module.getClassLoader();
 488         }
 489 
 490         if (cl != null) {
 491             return cl.loadClass(module, name);
 492         } else {
 493             return BootLoader.loadClass(module, name);
 494         }
 495     }
 496 
 497     /**
 498      * Creates a new instance of the class represented by this {@code Class}
 499      * object.  The class is instantiated as if by a {@code new}
 500      * expression with an empty argument list.  The class is initialized if it
 501      * has not already been initialized.
 502      *
 503      * @deprecated This method propagates any exception thrown by the
 504      * nullary constructor, including a checked exception.  Use of
 505      * this method effectively bypasses the compile-time exception
 506      * checking that would otherwise be performed by the compiler.
 507      * The {@link
 508      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
 509      * Constructor.newInstance} method avoids this problem by wrapping
 510      * any exception thrown by the constructor in a (checked) {@link
 511      * java.lang.reflect.InvocationTargetException}.
 512      *
 513      * <p>The call
 514      *
 515      * <pre>{@code
 516      * clazz.newInstance()
 517      * }</pre>
 518      *
 519      * can be replaced by
 520      *
 521      * <pre>{@code
 522      * clazz.getDeclaredConstructor().newInstance()
 523      * }</pre>
 524      *
 525      * The latter sequence of calls is inferred to be able to throw
 526      * the additional exception types {@link
 527      * InvocationTargetException} and {@link
 528      * NoSuchMethodException}. Both of these exception types are
 529      * subclasses of {@link ReflectiveOperationException}.
 530      *
 531      * @return  a newly allocated instance of the class represented by this
 532      *          object.
 533      * @throws  IllegalAccessException  if the class or its nullary
 534      *          constructor is not accessible.
 535      * @throws  InstantiationException
 536      *          if this {@code Class} represents an abstract class,
 537      *          an interface, an array class, a primitive type, or void;
 538      *          or if the class has no nullary constructor;
 539      *          or if the instantiation fails for some other reason.
 540      * @throws  ExceptionInInitializerError if the initialization
 541      *          provoked by this method fails.
 542      * @throws  SecurityException
 543      *          If a security manager, <i>s</i>, is present and
 544      *          the caller's class loader is not the same as or an
 545      *          ancestor of the class loader for the current class and
 546      *          invocation of {@link SecurityManager#checkPackageAccess
 547      *          s.checkPackageAccess()} denies access to the package
 548      *          of this class.
 549      */
 550     @CallerSensitive
 551     @Deprecated(since="9")
 552     public T newInstance()
 553         throws InstantiationException, IllegalAccessException
 554     {
 555         SecurityManager sm = System.getSecurityManager();
 556         if (sm != null) {
 557             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false);
 558         }
 559 
 560         // Constructor lookup
 561         Constructor<T> tmpConstructor = cachedConstructor;
 562         if (tmpConstructor == null) {
 563             if (this == Class.class) {
 564                 throw new IllegalAccessException(
 565                     "Can not call newInstance() on the Class for java.lang.Class"
 566                 );
 567             }
 568             try {
 569                 Class<?>[] empty = {};
 570                 final Constructor<T> c = getReflectionFactory().copyConstructor(
 571                     getConstructor0(empty, Member.DECLARED));
 572                 // Disable accessibility checks on the constructor
 573                 // access check is done with the true caller
 574                 java.security.AccessController.doPrivileged(
 575                     new java.security.PrivilegedAction<>() {
 576                         public Void run() {
 577                                 c.setAccessible(true);
 578                                 return null;
 579                             }
 580                         });
 581                 cachedConstructor = tmpConstructor = c;
 582             } catch (NoSuchMethodException e) {
 583                 throw (InstantiationException)
 584                     new InstantiationException(getName()).initCause(e);
 585             }
 586         }
 587 
 588         try {
 589             Class<?> caller = Reflection.getCallerClass();
 590             return getReflectionFactory().newInstance(tmpConstructor, null, caller);
 591         } catch (InvocationTargetException e) {
 592             Unsafe.getUnsafe().throwException(e.getTargetException());
 593             // Not reached
 594             return null;
 595         }
 596     }
 597 
 598     private transient volatile Constructor<T> cachedConstructor;
 599 
 600     /**
 601      * Determines if the specified {@code Object} is assignment-compatible
 602      * with the object represented by this {@code Class}.  This method is
 603      * the dynamic equivalent of the Java language {@code instanceof}
 604      * operator. The method returns {@code true} if the specified
 605      * {@code Object} argument is non-null and can be cast to the
 606      * reference type represented by this {@code Class} object without
 607      * raising a {@code ClassCastException.} It returns {@code false}
 608      * otherwise.
 609      *
 610      * <p> Specifically, if this {@code Class} object represents a
 611      * declared class, this method returns {@code true} if the specified
 612      * {@code Object} argument is an instance of the represented class (or
 613      * of any of its subclasses); it returns {@code false} otherwise. If
 614      * this {@code Class} object represents an array class, this method
 615      * returns {@code true} if the specified {@code Object} argument
 616      * can be converted to an object of the array class by an identity
 617      * conversion or by a widening reference conversion; it returns
 618      * {@code false} otherwise. If this {@code Class} object
 619      * represents an interface, this method returns {@code true} if the
 620      * class or any superclass of the specified {@code Object} argument
 621      * implements this interface; it returns {@code false} otherwise. If
 622      * this {@code Class} object represents a primitive type, this method
 623      * returns {@code false}.
 624      *
 625      * @param   obj the object to check
 626      * @return  true if {@code obj} is an instance of this class
 627      *
 628      * @since 1.1
 629      */
 630     @HotSpotIntrinsicCandidate
 631     public native boolean isInstance(Object obj);
 632 
 633 
 634     /**
 635      * Determines if the class or interface represented by this
 636      * {@code Class} object is either the same as, or is a superclass or
 637      * superinterface of, the class or interface represented by the specified
 638      * {@code Class} parameter. It returns {@code true} if so;
 639      * otherwise it returns {@code false}. If this {@code Class}
 640      * object represents a primitive type, this method returns
 641      * {@code true} if the specified {@code Class} parameter is
 642      * exactly this {@code Class} object; otherwise it returns
 643      * {@code false}.
 644      *
 645      * <p> Specifically, this method tests whether the type represented by the
 646      * specified {@code Class} parameter can be converted to the type
 647      * represented by this {@code Class} object via an identity conversion
 648      * or via a widening reference conversion. See <em>The Java Language
 649      * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
 650      *
 651      * @param cls the {@code Class} object to be checked
 652      * @return the {@code boolean} value indicating whether objects of the
 653      * type {@code cls} can be assigned to objects of this class
 654      * @exception NullPointerException if the specified Class parameter is
 655      *            null.
 656      * @since 1.1
 657      */
 658     @HotSpotIntrinsicCandidate
 659     public native boolean isAssignableFrom(Class<?> cls);
 660 
 661 
 662     /**
 663      * Determines if the specified {@code Class} object represents an
 664      * interface type.
 665      *
 666      * @return  {@code true} if this object represents an interface;
 667      *          {@code false} otherwise.
 668      */
 669     @HotSpotIntrinsicCandidate
 670     public native boolean isInterface();
 671 
 672 
 673     /**
 674      * Determines if this {@code Class} object represents an array class.
 675      *
 676      * @return  {@code true} if this object represents an array class;
 677      *          {@code false} otherwise.
 678      * @since   1.1
 679      */
 680     @HotSpotIntrinsicCandidate
 681     public native boolean isArray();
 682 
 683 
 684     /**
 685      * Determines if the specified {@code Class} object represents a
 686      * primitive type.
 687      *
 688      * <p> There are nine predefined {@code Class} objects to represent
 689      * the eight primitive types and void.  These are created by the Java
 690      * Virtual Machine, and have the same names as the primitive types that
 691      * they represent, namely {@code boolean}, {@code byte},
 692      * {@code char}, {@code short}, {@code int},
 693      * {@code long}, {@code float}, and {@code double}.
 694      *
 695      * <p> These objects may only be accessed via the following public static
 696      * final variables, and are the only {@code Class} objects for which
 697      * this method returns {@code true}.
 698      *
 699      * @return true if and only if this class represents a primitive type
 700      *
 701      * @see     java.lang.Boolean#TYPE
 702      * @see     java.lang.Character#TYPE
 703      * @see     java.lang.Byte#TYPE
 704      * @see     java.lang.Short#TYPE
 705      * @see     java.lang.Integer#TYPE
 706      * @see     java.lang.Long#TYPE
 707      * @see     java.lang.Float#TYPE
 708      * @see     java.lang.Double#TYPE
 709      * @see     java.lang.Void#TYPE
 710      * @since 1.1
 711      */
 712     @HotSpotIntrinsicCandidate
 713     public native boolean isPrimitive();
 714 
 715     /**
 716      * Returns true if this {@code Class} object represents an annotation
 717      * type.  Note that if this method returns true, {@link #isInterface()}
 718      * would also return true, as all annotation types are also interfaces.
 719      *
 720      * @return {@code true} if this class object represents an annotation
 721      *      type; {@code false} otherwise
 722      * @since 1.5
 723      */
 724     public boolean isAnnotation() {
 725         return (getModifiers() & ANNOTATION) != 0;
 726     }
 727 
 728     /**
 729      * Returns {@code true} if this class is a synthetic class;
 730      * returns {@code false} otherwise.
 731      * @return {@code true} if and only if this class is a synthetic class as
 732      *         defined by the Java Language Specification.
 733      * @jls 13.1 The Form of a Binary
 734      * @since 1.5
 735      */
 736     public boolean isSynthetic() {
 737         return (getModifiers() & SYNTHETIC) != 0;
 738     }
 739 
 740     /**
 741      * Returns the  name of the entity (class, interface, array class,
 742      * primitive type, or void) represented by this {@code Class} object,
 743      * as a {@code String}.
 744      *
 745      * <p> If this class object represents a reference type that is not an
 746      * array type then the binary name of the class is returned, as specified
 747      * by
 748      * <cite>The Java&trade; Language Specification</cite>.
 749      *
 750      * <p> If this class object represents a primitive type or void, then the
 751      * name returned is a {@code String} equal to the Java language
 752      * keyword corresponding to the primitive type or void.
 753      *
 754      * <p> If this class object represents a class of arrays, then the internal
 755      * form of the name consists of the name of the element type preceded by
 756      * one or more '{@code [}' characters representing the depth of the array
 757      * nesting.  The encoding of element type names is as follows:
 758      *
 759      * <blockquote><table class="striped">
 760      * <caption style="display:none">Element types and encodings</caption>
 761      * <thead>
 762      * <tr><th scope="col"> Element Type <th scope="col"> Encoding
 763      * </thead>
 764      * <tbody style="text-align:left">
 765      * <tr><th scope="row"> boolean      <td style="text-align:center"> Z
 766      * <tr><th scope="row"> byte         <td style="text-align:center"> B
 767      * <tr><th scope="row"> char         <td style="text-align:center"> C
 768      * <tr><th scope="row"> class or interface
 769      *                                   <td style="text-align:center"> L<i>classname</i>;
 770      * <tr><th scope="row"> double       <td style="text-align:center"> D
 771      * <tr><th scope="row"> float        <td style="text-align:center"> F
 772      * <tr><th scope="row"> int          <td style="text-align:center"> I
 773      * <tr><th scope="row"> long         <td style="text-align:center"> J
 774      * <tr><th scope="row"> short        <td style="text-align:center"> S
 775      * </tbody>
 776      * </table></blockquote>
 777      *
 778      * <p> The class or interface name <i>classname</i> is the binary name of
 779      * the class specified above.
 780      *
 781      * <p> Examples:
 782      * <blockquote><pre>
 783      * String.class.getName()
 784      *     returns "java.lang.String"
 785      * byte.class.getName()
 786      *     returns "byte"
 787      * (new Object[3]).getClass().getName()
 788      *     returns "[Ljava.lang.Object;"
 789      * (new int[3][4][5][6][7][8][9]).getClass().getName()
 790      *     returns "[[[[[[[I"
 791      * </pre></blockquote>
 792      *
 793      * @return  the name of the class or interface
 794      *          represented by this object.
 795      */
 796     public String getName() {
 797         String name = this.name;
 798         if (name == null)
 799             this.name = name = getName0();
 800         return name;
 801     }
 802 
 803     // cache the name to reduce the number of calls into the VM
 804     private transient String name;
 805     private native String getName0();
 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                 StringBuilder sb = new StringBuilder();
1592                 sb.append(cl.getName());
1593                 for (int i = 0; i < dimensions; i++) {
1594                     sb.append("[]");
1595                 }
1596                 return sb.toString();
1597             } catch (Throwable e) { /*FALLTHRU*/ }
1598         }
1599         return getName();
1600     }
1601 
1602     /**
1603      * Returns the canonical name of the underlying class as
1604      * defined by the Java Language Specification.  Returns null if
1605      * the underlying class does not have a canonical name (i.e., if
1606      * it is a local or anonymous class or an array whose component
1607      * type does not have a canonical name).
1608      * @return the canonical name of the underlying class if it exists, and
1609      * {@code null} otherwise.
1610      * @since 1.5
1611      */
1612     public String getCanonicalName() {
1613         ReflectionData<T> rd = reflectionData();
1614         String canonicalName = rd.canonicalName;
1615         if (canonicalName == null) {
1616             rd.canonicalName = canonicalName = getCanonicalName0();
1617         }
1618         return canonicalName == ReflectionData.NULL_SENTINEL? null : canonicalName;
1619     }
1620 
1621     private String getCanonicalName0() {
1622         if (isArray()) {
1623             String canonicalName = getComponentType().getCanonicalName();
1624             if (canonicalName != null)
1625                 return canonicalName + "[]";
1626             else
1627                 return ReflectionData.NULL_SENTINEL;
1628         }
1629         if (isLocalOrAnonymousClass())
1630             return ReflectionData.NULL_SENTINEL;
1631         Class<?> enclosingClass = getEnclosingClass();
1632         if (enclosingClass == null) { // top level class
1633             return getName();
1634         } else {
1635             String enclosingName = enclosingClass.getCanonicalName();
1636             if (enclosingName == null)
1637                 return ReflectionData.NULL_SENTINEL;
1638             return enclosingName + "." + getSimpleName();
1639         }
1640     }
1641 
1642     /**
1643      * Returns {@code true} if and only if the underlying class
1644      * is an anonymous class.
1645      *
1646      * @return {@code true} if and only if this class is an anonymous class.
1647      * @since 1.5
1648      */
1649     public boolean isAnonymousClass() {
1650         return !isArray() && isLocalOrAnonymousClass() &&
1651                 getSimpleBinaryName0() == null;
1652     }
1653 
1654     /**
1655      * Returns {@code true} if and only if the underlying class
1656      * is a local class.
1657      *
1658      * @return {@code true} if and only if this class is a local class.
1659      * @since 1.5
1660      */
1661     public boolean isLocalClass() {
1662         return isLocalOrAnonymousClass() &&
1663                 (isArray() || getSimpleBinaryName0() != null);
1664     }
1665 
1666     /**
1667      * Returns {@code true} if and only if the underlying class
1668      * is a member class.
1669      *
1670      * @return {@code true} if and only if this class is a member class.
1671      * @since 1.5
1672      */
1673     public boolean isMemberClass() {
1674         return !isLocalOrAnonymousClass() && getDeclaringClass0() != null;
1675     }
1676 
1677     /**
1678      * Returns the "simple binary name" of the underlying class, i.e.,
1679      * the binary name without the leading enclosing class name.
1680      * Returns {@code null} if the underlying class is a top level
1681      * class.
1682      */
1683     private String getSimpleBinaryName() {
1684         if (isTopLevelClass())
1685             return null;
1686         String name = getSimpleBinaryName0();
1687         if (name == null) // anonymous class
1688             return "";
1689         return name;
1690     }
1691 
1692     private native String getSimpleBinaryName0();
1693 
1694     /**
1695      * Returns {@code true} if this is a top level class.  Returns {@code false}
1696      * otherwise.
1697      */
1698     private boolean isTopLevelClass() {
1699         return !isLocalOrAnonymousClass() && getDeclaringClass0() == null;
1700     }
1701 
1702     /**
1703      * Returns {@code true} if this is a local class or an anonymous
1704      * class.  Returns {@code false} otherwise.
1705      */
1706     private boolean isLocalOrAnonymousClass() {
1707         // JVM Spec 4.7.7: A class must have an EnclosingMethod
1708         // attribute if and only if it is a local class or an
1709         // anonymous class.
1710         return hasEnclosingMethodInfo();
1711     }
1712 
1713     private boolean hasEnclosingMethodInfo() {
1714         Object[] enclosingInfo = getEnclosingMethod0();
1715         if (enclosingInfo != null) {
1716             EnclosingMethodInfo.validate(enclosingInfo);
1717             return true;
1718         }
1719         return false;
1720     }
1721 
1722     /**
1723      * Returns an array containing {@code Class} objects representing all
1724      * the public classes and interfaces that are members of the class
1725      * represented by this {@code Class} object.  This includes public
1726      * class and interface members inherited from superclasses and public class
1727      * and interface members declared by the class.  This method returns an
1728      * array of length 0 if this {@code Class} object has no public member
1729      * classes or interfaces.  This method also returns an array of length 0 if
1730      * this {@code Class} object represents a primitive type, an array
1731      * class, or void.
1732      *
1733      * @return the array of {@code Class} objects representing the public
1734      *         members of this class
1735      * @throws SecurityException
1736      *         If a security manager, <i>s</i>, is present and
1737      *         the caller's class loader is not the same as or an
1738      *         ancestor of the class loader for the current class and
1739      *         invocation of {@link SecurityManager#checkPackageAccess
1740      *         s.checkPackageAccess()} denies access to the package
1741      *         of this class.
1742      *
1743      * @since 1.1
1744      */
1745     @CallerSensitive
1746     public Class<?>[] getClasses() {
1747         SecurityManager sm = System.getSecurityManager();
1748         if (sm != null) {
1749             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false);
1750         }
1751 
1752         // Privileged so this implementation can look at DECLARED classes,
1753         // something the caller might not have privilege to do.  The code here
1754         // is allowed to look at DECLARED classes because (1) it does not hand
1755         // out anything other than public members and (2) public member access
1756         // has already been ok'd by the SecurityManager.
1757 
1758         return java.security.AccessController.doPrivileged(
1759             new java.security.PrivilegedAction<>() {
1760                 public Class<?>[] run() {
1761                     List<Class<?>> list = new ArrayList<>();
1762                     Class<?> currentClass = Class.this;
1763                     while (currentClass != null) {
1764                         for (Class<?> m : currentClass.getDeclaredClasses()) {
1765                             if (Modifier.isPublic(m.getModifiers())) {
1766                                 list.add(m);
1767                             }
1768                         }
1769                         currentClass = currentClass.getSuperclass();
1770                     }
1771                     return list.toArray(new Class<?>[0]);
1772                 }
1773             });
1774     }
1775 
1776 
1777     /**
1778      * Returns an array containing {@code Field} objects reflecting all
1779      * the accessible public fields of the class or interface represented by
1780      * this {@code Class} object.
1781      *
1782      * <p> If this {@code Class} object represents a class or interface with
1783      * no accessible public fields, then this method returns an array of length
1784      * 0.
1785      *
1786      * <p> If this {@code Class} object represents a class, then this method
1787      * returns the public fields of the class and of all its superclasses and
1788      * superinterfaces.
1789      *
1790      * <p> If this {@code Class} object represents an interface, then this
1791      * method returns the fields of the interface and of all its
1792      * superinterfaces.
1793      *
1794      * <p> If this {@code Class} object represents an array type, a primitive
1795      * type, or void, then this method returns an array of length 0.
1796      *
1797      * <p> The elements in the returned array are not sorted and are not in any
1798      * particular order.
1799      *
1800      * @return the array of {@code Field} objects representing the
1801      *         public fields
1802      * @throws SecurityException
1803      *         If a security manager, <i>s</i>, is present and
1804      *         the caller's class loader is not the same as or an
1805      *         ancestor of the class loader for the current class and
1806      *         invocation of {@link SecurityManager#checkPackageAccess
1807      *         s.checkPackageAccess()} denies access to the package
1808      *         of this class.
1809      *
1810      * @since 1.1
1811      * @jls 8.2 Class Members
1812      * @jls 8.3 Field Declarations
1813      */
1814     @CallerSensitive
1815     public Field[] getFields() throws SecurityException {
1816         SecurityManager sm = System.getSecurityManager();
1817         if (sm != null) {
1818             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
1819         }
1820         return copyFields(privateGetPublicFields());
1821     }
1822 
1823 
1824     /**
1825      * Returns an array containing {@code Method} objects reflecting all the
1826      * public methods of the class or interface represented by this {@code
1827      * Class} object, including those declared by the class or interface and
1828      * those inherited from superclasses and superinterfaces.
1829      *
1830      * <p> If this {@code Class} object represents an array type, then the
1831      * returned array has a {@code Method} object for each of the public
1832      * methods inherited by the array type from {@code Object}. It does not
1833      * contain a {@code Method} object for {@code clone()}.
1834      *
1835      * <p> If this {@code Class} object represents an interface then the
1836      * returned array does not contain any implicitly declared methods from
1837      * {@code Object}. Therefore, if no methods are explicitly declared in
1838      * this interface or any of its superinterfaces then the returned array
1839      * has length 0. (Note that a {@code Class} object which represents a class
1840      * always has public methods, inherited from {@code Object}.)
1841      *
1842      * <p> The returned array never contains methods with names "{@code <init>}"
1843      * or "{@code <clinit>}".
1844      *
1845      * <p> The elements in the returned array are not sorted and are not in any
1846      * particular order.
1847      *
1848      * <p> Generally, the result is computed as with the following 4 step algorithm.
1849      * Let C be the class or interface represented by this {@code Class} object:
1850      * <ol>
1851      * <li> A union of methods is composed of:
1852      *   <ol type="a">
1853      *   <li> C's declared public instance and static methods as returned by
1854      *        {@link #getDeclaredMethods()} and filtered to include only public
1855      *        methods.</li>
1856      *   <li> If C is a class other than {@code Object}, then include the result
1857      *        of invoking this algorithm recursively on the superclass of C.</li>
1858      *   <li> Include the results of invoking this algorithm recursively on all
1859      *        direct superinterfaces of C, but include only instance methods.</li>
1860      *   </ol></li>
1861      * <li> Union from step 1 is partitioned into subsets of methods with same
1862      *      signature (name, parameter types) and return type.</li>
1863      * <li> Within each such subset only the most specific methods are selected.
1864      *      Let method M be a method from a set of methods with same signature
1865      *      and return type. M is most specific if there is no such method
1866      *      N != M from the same set, such that N is more specific than M.
1867      *      N is more specific than M if:
1868      *   <ol type="a">
1869      *   <li> N is declared by a class and M is declared by an interface; or</li>
1870      *   <li> N and M are both declared by classes or both by interfaces and
1871      *        N's declaring type is the same as or a subtype of M's declaring type
1872      *        (clearly, if M's and N's declaring types are the same type, then
1873      *        M and N are the same method).</li>
1874      *   </ol></li>
1875      * <li> The result of this algorithm is the union of all selected methods from
1876      *      step 3.</li>
1877      * </ol>
1878      *
1879      * @apiNote There may be more than one method with a particular name
1880      * and parameter types in a class because while the Java language forbids a
1881      * class to declare multiple methods with the same signature but different
1882      * return types, the Java virtual machine does not.  This
1883      * increased flexibility in the virtual machine can be used to
1884      * implement various language features.  For example, covariant
1885      * returns can be implemented with {@linkplain
1886      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
1887      * method and the overriding method would have the same
1888      * signature but different return types.
1889      *
1890      * @return the array of {@code Method} objects representing the
1891      *         public methods of this class
1892      * @throws SecurityException
1893      *         If a security manager, <i>s</i>, is present and
1894      *         the caller's class loader is not the same as or an
1895      *         ancestor of the class loader for the current class and
1896      *         invocation of {@link SecurityManager#checkPackageAccess
1897      *         s.checkPackageAccess()} denies access to the package
1898      *         of this class.
1899      *
1900      * @jls 8.2 Class Members
1901      * @jls 8.4 Method Declarations
1902      * @since 1.1
1903      */
1904     @CallerSensitive
1905     public Method[] getMethods() throws SecurityException {
1906         SecurityManager sm = System.getSecurityManager();
1907         if (sm != null) {
1908             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
1909         }
1910         return copyMethods(privateGetPublicMethods());
1911     }
1912 
1913 
1914     /**
1915      * Returns an array containing {@code Constructor} objects reflecting
1916      * all the public constructors of the class represented by this
1917      * {@code Class} object.  An array of length 0 is returned if the
1918      * class has no public constructors, or if the class is an array class, or
1919      * if the class reflects a primitive type or void.
1920      *
1921      * Note that while this method returns an array of {@code
1922      * Constructor<T>} objects (that is an array of constructors from
1923      * this class), the return type of this method is {@code
1924      * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
1925      * might be expected.  This less informative return type is
1926      * necessary since after being returned from this method, the
1927      * array could be modified to hold {@code Constructor} objects for
1928      * different classes, which would violate the type guarantees of
1929      * {@code Constructor<T>[]}.
1930      *
1931      * @return the array of {@code Constructor} objects representing the
1932      *         public constructors of this class
1933      * @throws SecurityException
1934      *         If a security manager, <i>s</i>, is present and
1935      *         the caller's class loader is not the same as or an
1936      *         ancestor of the class loader for the current class and
1937      *         invocation of {@link SecurityManager#checkPackageAccess
1938      *         s.checkPackageAccess()} denies access to the package
1939      *         of this class.
1940      *
1941      * @since 1.1
1942      */
1943     @CallerSensitive
1944     public Constructor<?>[] getConstructors() throws SecurityException {
1945         SecurityManager sm = System.getSecurityManager();
1946         if (sm != null) {
1947             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
1948         }
1949         return copyConstructors(privateGetDeclaredConstructors(true));
1950     }
1951 
1952 
1953     /**
1954      * Returns a {@code Field} object that reflects the specified public member
1955      * field of the class or interface represented by this {@code Class}
1956      * object. The {@code name} parameter is a {@code String} specifying the
1957      * simple name of the desired field.
1958      *
1959      * <p> The field to be reflected is determined by the algorithm that
1960      * follows.  Let C be the class or interface represented by this object:
1961      *
1962      * <OL>
1963      * <LI> If C declares a public field with the name specified, that is the
1964      *      field to be reflected.</LI>
1965      * <LI> If no field was found in step 1 above, this algorithm is applied
1966      *      recursively to each direct superinterface of C. The direct
1967      *      superinterfaces are searched in the order they were declared.</LI>
1968      * <LI> If no field was found in steps 1 and 2 above, and C has a
1969      *      superclass S, then this algorithm is invoked recursively upon S.
1970      *      If C has no superclass, then a {@code NoSuchFieldException}
1971      *      is thrown.</LI>
1972      * </OL>
1973      *
1974      * <p> If this {@code Class} object represents an array type, then this
1975      * method does not find the {@code length} field of the array type.
1976      *
1977      * @param name the field name
1978      * @return the {@code Field} object of this class specified by
1979      *         {@code name}
1980      * @throws NoSuchFieldException if a field with the specified name is
1981      *         not found.
1982      * @throws NullPointerException if {@code name} is {@code null}
1983      * @throws SecurityException
1984      *         If a security manager, <i>s</i>, is present and
1985      *         the caller's class loader is not the same as or an
1986      *         ancestor of the class loader for the current class and
1987      *         invocation of {@link SecurityManager#checkPackageAccess
1988      *         s.checkPackageAccess()} denies access to the package
1989      *         of this class.
1990      *
1991      * @since 1.1
1992      * @jls 8.2 Class Members
1993      * @jls 8.3 Field Declarations
1994      */
1995     @CallerSensitive
1996     public Field getField(String name)
1997         throws NoSuchFieldException, SecurityException {
1998         Objects.requireNonNull(name);
1999         SecurityManager sm = System.getSecurityManager();
2000         if (sm != null) {
2001             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
2002         }
2003         Field field = getField0(name);
2004         if (field == null) {
2005             throw new NoSuchFieldException(name);
2006         }
2007         return getReflectionFactory().copyField(field);
2008     }
2009 
2010 
2011     /**
2012      * Returns a {@code Method} object that reflects the specified public
2013      * member method of the class or interface represented by this
2014      * {@code Class} object. The {@code name} parameter is a
2015      * {@code String} specifying the simple name of the desired method. The
2016      * {@code parameterTypes} parameter is an array of {@code Class}
2017      * objects that identify the method's formal parameter types, in declared
2018      * order. If {@code parameterTypes} is {@code null}, it is
2019      * treated as if it were an empty array.
2020      *
2021      * <p> If this {@code Class} object represents an array type, then this
2022      * method finds any public method inherited by the array type from
2023      * {@code Object} except method {@code clone()}.
2024      *
2025      * <p> If this {@code Class} object represents an interface then this
2026      * method does not find any implicitly declared method from
2027      * {@code Object}. Therefore, if no methods are explicitly declared in
2028      * this interface or any of its superinterfaces, then this method does not
2029      * find any method.
2030      *
2031      * <p> This method does not find any method with name "{@code <init>}" or
2032      * "{@code <clinit>}".
2033      *
2034      * <p> Generally, the method to be reflected is determined by the 4 step
2035      * algorithm that follows.
2036      * Let C be the class or interface represented by this {@code Class} object:
2037      * <ol>
2038      * <li> A union of methods is composed of:
2039      *   <ol type="a">
2040      *   <li> C's declared public instance and static methods as returned by
2041      *        {@link #getDeclaredMethods()} and filtered to include only public
2042      *        methods that match given {@code name} and {@code parameterTypes}</li>
2043      *   <li> If C is a class other than {@code Object}, then include the result
2044      *        of invoking this algorithm recursively on the superclass of C.</li>
2045      *   <li> Include the results of invoking this algorithm recursively on all
2046      *        direct superinterfaces of C, but include only instance methods.</li>
2047      *   </ol></li>
2048      * <li> This union is partitioned into subsets of methods with same
2049      *      return type (the selection of methods from step 1 also guarantees that
2050      *      they have the same method name and parameter types).</li>
2051      * <li> Within each such subset only the most specific methods are selected.
2052      *      Let method M be a method from a set of methods with same VM
2053      *      signature (return type, name, parameter types).
2054      *      M is most specific if there is no such method N != M from the same
2055      *      set, such that N is more specific than M. N is more specific than M
2056      *      if:
2057      *   <ol type="a">
2058      *   <li> N is declared by a class and M is declared by an interface; or</li>
2059      *   <li> N and M are both declared by classes or both by interfaces and
2060      *        N's declaring type is the same as or a subtype of M's declaring type
2061      *        (clearly, if M's and N's declaring types are the same type, then
2062      *        M and N are the same method).</li>
2063      *   </ol></li>
2064      * <li> The result of this algorithm is chosen arbitrarily from the methods
2065      *      with most specific return type among all selected methods from step 3.
2066      *      Let R be a return type of a method M from the set of all selected methods
2067      *      from step 3. M is a method with most specific return type if there is
2068      *      no such method N != M from the same set, having return type S != R,
2069      *      such that S is a subtype of R as determined by
2070      *      R.class.{@link #isAssignableFrom}(S.class).
2071      * </ol>
2072      *
2073      * @apiNote There may be more than one method with matching name and
2074      * parameter types in a class because while the Java language forbids a
2075      * class to declare multiple methods with the same signature but different
2076      * return types, the Java virtual machine does not.  This
2077      * increased flexibility in the virtual machine can be used to
2078      * implement various language features.  For example, covariant
2079      * returns can be implemented with {@linkplain
2080      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
2081      * method and the overriding method would have the same
2082      * signature but different return types. This method would return the
2083      * overriding method as it would have a more specific return type.
2084      *
2085      * @param name the name of the method
2086      * @param parameterTypes the list of parameters
2087      * @return the {@code Method} object that matches the specified
2088      *         {@code name} and {@code parameterTypes}
2089      * @throws NoSuchMethodException if a matching method is not found
2090      *         or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
2091      * @throws NullPointerException if {@code name} is {@code null}
2092      * @throws SecurityException
2093      *         If a security manager, <i>s</i>, is present and
2094      *         the caller's class loader is not the same as or an
2095      *         ancestor of the class loader for the current class and
2096      *         invocation of {@link SecurityManager#checkPackageAccess
2097      *         s.checkPackageAccess()} denies access to the package
2098      *         of this class.
2099      *
2100      * @jls 8.2 Class Members
2101      * @jls 8.4 Method Declarations
2102      * @since 1.1
2103      */
2104     @CallerSensitive
2105     public Method getMethod(String name, Class<?>... parameterTypes)
2106         throws NoSuchMethodException, SecurityException {
2107         Objects.requireNonNull(name);
2108         SecurityManager sm = System.getSecurityManager();
2109         if (sm != null) {
2110             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
2111         }
2112         Method method = getMethod0(name, parameterTypes);
2113         if (method == null) {
2114             throw new NoSuchMethodException(methodToString(name, parameterTypes));
2115         }
2116         return getReflectionFactory().copyMethod(method);
2117     }
2118 
2119     /**
2120      * Returns a {@code Constructor} object that reflects the specified
2121      * public constructor of the class represented by this {@code Class}
2122      * object. The {@code parameterTypes} parameter is an array of
2123      * {@code Class} objects that identify the constructor's formal
2124      * parameter types, in declared order.
2125      *
2126      * If this {@code Class} object represents an inner class
2127      * declared in a non-static context, the formal parameter types
2128      * include the explicit enclosing instance as the first parameter.
2129      *
2130      * <p> The constructor to reflect is the public constructor of the class
2131      * represented by this {@code Class} object whose formal parameter
2132      * types match those specified by {@code parameterTypes}.
2133      *
2134      * @param parameterTypes the parameter array
2135      * @return the {@code Constructor} object of the public constructor that
2136      *         matches the specified {@code parameterTypes}
2137      * @throws NoSuchMethodException if a matching method is not found.
2138      * @throws SecurityException
2139      *         If a security manager, <i>s</i>, is present and
2140      *         the caller's class loader is not the same as or an
2141      *         ancestor of the class loader for the current class and
2142      *         invocation of {@link SecurityManager#checkPackageAccess
2143      *         s.checkPackageAccess()} denies access to the package
2144      *         of this class.
2145      *
2146      * @since 1.1
2147      */
2148     @CallerSensitive
2149     public Constructor<T> getConstructor(Class<?>... parameterTypes)
2150         throws NoSuchMethodException, SecurityException
2151     {
2152         SecurityManager sm = System.getSecurityManager();
2153         if (sm != null) {
2154             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
2155         }
2156         return getReflectionFactory().copyConstructor(
2157             getConstructor0(parameterTypes, Member.PUBLIC));
2158     }
2159 
2160 
2161     /**
2162      * Returns an array of {@code Class} objects reflecting all the
2163      * classes and interfaces declared as members of the class represented by
2164      * this {@code Class} object. This includes public, protected, default
2165      * (package) access, and private classes and interfaces declared by the
2166      * class, but excludes inherited classes and interfaces.  This method
2167      * returns an array of length 0 if the class declares no classes or
2168      * interfaces as members, or if this {@code Class} object represents a
2169      * primitive type, an array class, or void.
2170      *
2171      * @return the array of {@code Class} objects representing all the
2172      *         declared members of this class
2173      * @throws SecurityException
2174      *         If a security manager, <i>s</i>, is present and any of the
2175      *         following conditions is met:
2176      *
2177      *         <ul>
2178      *
2179      *         <li> the caller's class loader is not the same as the
2180      *         class loader of this class and invocation of
2181      *         {@link SecurityManager#checkPermission
2182      *         s.checkPermission} method with
2183      *         {@code RuntimePermission("accessDeclaredMembers")}
2184      *         denies access to the declared classes within this class
2185      *
2186      *         <li> the caller's class loader is not the same as or an
2187      *         ancestor of the class loader for the current class and
2188      *         invocation of {@link SecurityManager#checkPackageAccess
2189      *         s.checkPackageAccess()} denies access to the package
2190      *         of this class
2191      *
2192      *         </ul>
2193      *
2194      * @since 1.1
2195      */
2196     @CallerSensitive
2197     public Class<?>[] getDeclaredClasses() throws SecurityException {
2198         SecurityManager sm = System.getSecurityManager();
2199         if (sm != null) {
2200             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), false);
2201         }
2202         return getDeclaredClasses0();
2203     }
2204 
2205 
2206     /**
2207      * Returns an array of {@code Field} objects reflecting all the fields
2208      * declared by the class or interface represented by this
2209      * {@code Class} object. This includes public, protected, default
2210      * (package) access, and private fields, but excludes inherited fields.
2211      *
2212      * <p> If this {@code Class} object represents a class or interface with no
2213      * declared fields, then this method returns an array of length 0.
2214      *
2215      * <p> If this {@code Class} object represents an array type, a primitive
2216      * type, or void, then this method returns an array of length 0.
2217      *
2218      * <p> The elements in the returned array are not sorted and are not in any
2219      * particular order.
2220      *
2221      * @return  the array of {@code Field} objects representing all the
2222      *          declared fields of this class
2223      * @throws  SecurityException
2224      *          If a security manager, <i>s</i>, is present and any of the
2225      *          following conditions is met:
2226      *
2227      *          <ul>
2228      *
2229      *          <li> the caller's class loader is not the same as the
2230      *          class loader of this class and invocation of
2231      *          {@link SecurityManager#checkPermission
2232      *          s.checkPermission} method with
2233      *          {@code RuntimePermission("accessDeclaredMembers")}
2234      *          denies access to the declared fields within this class
2235      *
2236      *          <li> the caller's class loader is not the same as or an
2237      *          ancestor of the class loader for the current class and
2238      *          invocation of {@link SecurityManager#checkPackageAccess
2239      *          s.checkPackageAccess()} denies access to the package
2240      *          of this class
2241      *
2242      *          </ul>
2243      *
2244      * @since 1.1
2245      * @jls 8.2 Class Members
2246      * @jls 8.3 Field Declarations
2247      */
2248     @CallerSensitive
2249     public Field[] getDeclaredFields() throws SecurityException {
2250         SecurityManager sm = System.getSecurityManager();
2251         if (sm != null) {
2252             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2253         }
2254         return copyFields(privateGetDeclaredFields(false));
2255     }
2256 
2257 
2258     /**
2259      * Returns an array containing {@code Method} objects reflecting all the
2260      * declared methods of the class or interface represented by this {@code
2261      * Class} object, including public, protected, default (package)
2262      * access, and private methods, but excluding inherited methods.
2263      *
2264      * <p> If this {@code Class} object represents a type that has multiple
2265      * declared methods with the same name and parameter types, but different
2266      * return types, then the returned array has a {@code Method} object for
2267      * each such method.
2268      *
2269      * <p> If this {@code Class} object represents a type that has a class
2270      * initialization method {@code <clinit>}, then the returned array does
2271      * <em>not</em> have a corresponding {@code Method} object.
2272      *
2273      * <p> If this {@code Class} object represents a class or interface with no
2274      * declared methods, then the returned array has length 0.
2275      *
2276      * <p> If this {@code Class} object represents an array type, a primitive
2277      * type, or void, then the returned array has length 0.
2278      *
2279      * <p> The elements in the returned array are not sorted and are not in any
2280      * particular order.
2281      *
2282      * @return  the array of {@code Method} objects representing all the
2283      *          declared methods of this class
2284      * @throws  SecurityException
2285      *          If a security manager, <i>s</i>, is present and any of the
2286      *          following conditions is met:
2287      *
2288      *          <ul>
2289      *
2290      *          <li> the caller's class loader is not the same as the
2291      *          class loader of this class and invocation of
2292      *          {@link SecurityManager#checkPermission
2293      *          s.checkPermission} method with
2294      *          {@code RuntimePermission("accessDeclaredMembers")}
2295      *          denies access to the declared methods within this class
2296      *
2297      *          <li> the caller's class loader is not the same as or an
2298      *          ancestor of the class loader for the current class and
2299      *          invocation of {@link SecurityManager#checkPackageAccess
2300      *          s.checkPackageAccess()} denies access to the package
2301      *          of this class
2302      *
2303      *          </ul>
2304      *
2305      * @jls 8.2 Class Members
2306      * @jls 8.4 Method Declarations
2307      * @since 1.1
2308      */
2309     @CallerSensitive
2310     public Method[] getDeclaredMethods() throws SecurityException {
2311         SecurityManager sm = System.getSecurityManager();
2312         if (sm != null) {
2313             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2314         }
2315         return copyMethods(privateGetDeclaredMethods(false));
2316     }
2317 
2318 
2319     /**
2320      * Returns an array of {@code Constructor} objects reflecting all the
2321      * constructors declared by the class represented by this
2322      * {@code Class} object. These are public, protected, default
2323      * (package) access, and private constructors.  The elements in the array
2324      * returned are not sorted and are not in any particular order.  If the
2325      * class has a default constructor, it is included in the returned array.
2326      * This method returns an array of length 0 if this {@code Class}
2327      * object represents an interface, a primitive type, an array class, or
2328      * void.
2329      *
2330      * <p> See <em>The Java Language Specification</em>, section 8.2.
2331      *
2332      * @return  the array of {@code Constructor} objects representing all the
2333      *          declared constructors of this class
2334      * @throws  SecurityException
2335      *          If a security manager, <i>s</i>, is present and any of the
2336      *          following conditions is met:
2337      *
2338      *          <ul>
2339      *
2340      *          <li> the caller's class loader is not the same as the
2341      *          class loader of this class and invocation of
2342      *          {@link SecurityManager#checkPermission
2343      *          s.checkPermission} method with
2344      *          {@code RuntimePermission("accessDeclaredMembers")}
2345      *          denies access to the declared constructors within this class
2346      *
2347      *          <li> the caller's class loader is not the same as or an
2348      *          ancestor of the class loader for the current class and
2349      *          invocation of {@link SecurityManager#checkPackageAccess
2350      *          s.checkPackageAccess()} denies access to the package
2351      *          of this class
2352      *
2353      *          </ul>
2354      *
2355      * @since 1.1
2356      */
2357     @CallerSensitive
2358     public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
2359         SecurityManager sm = System.getSecurityManager();
2360         if (sm != null) {
2361             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2362         }
2363         return copyConstructors(privateGetDeclaredConstructors(false));
2364     }
2365 
2366 
2367     /**
2368      * Returns a {@code Field} object that reflects the specified declared
2369      * field of the class or interface represented by this {@code Class}
2370      * object. The {@code name} parameter is a {@code String} that specifies
2371      * the simple name of the desired field.
2372      *
2373      * <p> If this {@code Class} object represents an array type, then this
2374      * method does not find the {@code length} field of the array type.
2375      *
2376      * @param name the name of the field
2377      * @return  the {@code Field} object for the specified field in this
2378      *          class
2379      * @throws  NoSuchFieldException if a field with the specified name is
2380      *          not found.
2381      * @throws  NullPointerException if {@code name} is {@code null}
2382      * @throws  SecurityException
2383      *          If a security manager, <i>s</i>, is present and any of the
2384      *          following conditions is met:
2385      *
2386      *          <ul>
2387      *
2388      *          <li> the caller's class loader is not the same as the
2389      *          class loader of this class and invocation of
2390      *          {@link SecurityManager#checkPermission
2391      *          s.checkPermission} method with
2392      *          {@code RuntimePermission("accessDeclaredMembers")}
2393      *          denies access to the declared field
2394      *
2395      *          <li> the caller's class loader is not the same as or an
2396      *          ancestor of the class loader for the current class and
2397      *          invocation of {@link SecurityManager#checkPackageAccess
2398      *          s.checkPackageAccess()} denies access to the package
2399      *          of this class
2400      *
2401      *          </ul>
2402      *
2403      * @since 1.1
2404      * @jls 8.2 Class Members
2405      * @jls 8.3 Field Declarations
2406      */
2407     @CallerSensitive
2408     public Field getDeclaredField(String name)
2409         throws NoSuchFieldException, SecurityException {
2410         Objects.requireNonNull(name);
2411         SecurityManager sm = System.getSecurityManager();
2412         if (sm != null) {
2413             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2414         }
2415         Field field = searchFields(privateGetDeclaredFields(false), name);
2416         if (field == null) {
2417             throw new NoSuchFieldException(name);
2418         }
2419         return getReflectionFactory().copyField(field);
2420     }
2421 
2422 
2423     /**
2424      * Returns a {@code Method} object that reflects the specified
2425      * declared method of the class or interface represented by this
2426      * {@code Class} object. The {@code name} parameter is a
2427      * {@code String} that specifies the simple name of the desired
2428      * method, and the {@code parameterTypes} parameter is an array of
2429      * {@code Class} objects that identify the method's formal parameter
2430      * types, in declared order.  If more than one method with the same
2431      * parameter types is declared in a class, and one of these methods has a
2432      * return type that is more specific than any of the others, that method is
2433      * returned; otherwise one of the methods is chosen arbitrarily.  If the
2434      * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
2435      * is raised.
2436      *
2437      * <p> If this {@code Class} object represents an array type, then this
2438      * method does not find the {@code clone()} method.
2439      *
2440      * @param name the name of the method
2441      * @param parameterTypes the parameter array
2442      * @return  the {@code Method} object for the method of this class
2443      *          matching the specified name and parameters
2444      * @throws  NoSuchMethodException if a matching method is not found.
2445      * @throws  NullPointerException if {@code name} is {@code null}
2446      * @throws  SecurityException
2447      *          If a security manager, <i>s</i>, is present and any of the
2448      *          following conditions is met:
2449      *
2450      *          <ul>
2451      *
2452      *          <li> the caller's class loader is not the same as the
2453      *          class loader of this class and invocation of
2454      *          {@link SecurityManager#checkPermission
2455      *          s.checkPermission} method with
2456      *          {@code RuntimePermission("accessDeclaredMembers")}
2457      *          denies access to the declared method
2458      *
2459      *          <li> the caller's class loader is not the same as or an
2460      *          ancestor of the class loader for the current class and
2461      *          invocation of {@link SecurityManager#checkPackageAccess
2462      *          s.checkPackageAccess()} denies access to the package
2463      *          of this class
2464      *
2465      *          </ul>
2466      *
2467      * @jls 8.2 Class Members
2468      * @jls 8.4 Method Declarations
2469      * @since 1.1
2470      */
2471     @CallerSensitive
2472     public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2473         throws NoSuchMethodException, SecurityException {
2474         Objects.requireNonNull(name);
2475         SecurityManager sm = System.getSecurityManager();
2476         if (sm != null) {
2477             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2478         }
2479         Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
2480         if (method == null) {
2481             throw new NoSuchMethodException(methodToString(name, parameterTypes));
2482         }
2483         return getReflectionFactory().copyMethod(method);
2484     }
2485 
2486     /**
2487      * Returns the list of {@code Method} objects for the declared public
2488      * methods of this class or interface that have the specified method name
2489      * and parameter types.
2490      *
2491      * @param name the name of the method
2492      * @param parameterTypes the parameter array
2493      * @return the list of {@code Method} objects for the public methods of
2494      *         this class matching the specified name and parameters
2495      */
2496     List<Method> getDeclaredPublicMethods(String name, Class<?>... parameterTypes) {
2497         Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);
2498         ReflectionFactory factory = getReflectionFactory();
2499         List<Method> result = new ArrayList<>();
2500         for (Method method : methods) {
2501             if (method.getName().equals(name)
2502                 && Arrays.equals(
2503                     factory.getExecutableSharedParameterTypes(method),
2504                     parameterTypes)) {
2505                 result.add(factory.copyMethod(method));
2506             }
2507         }
2508         return result;
2509     }
2510 
2511     /**
2512      * Returns a {@code Constructor} object that reflects the specified
2513      * constructor of the class or interface represented by this
2514      * {@code Class} object.  The {@code parameterTypes} parameter is
2515      * an array of {@code Class} objects that identify the constructor's
2516      * formal parameter types, in declared order.
2517      *
2518      * If this {@code Class} object represents an inner class
2519      * declared in a non-static context, the formal parameter types
2520      * include the explicit enclosing instance as the first parameter.
2521      *
2522      * @param parameterTypes the parameter array
2523      * @return  The {@code Constructor} object for the constructor with the
2524      *          specified parameter list
2525      * @throws  NoSuchMethodException if a matching method is not found.
2526      * @throws  SecurityException
2527      *          If a security manager, <i>s</i>, is present and any of the
2528      *          following conditions is met:
2529      *
2530      *          <ul>
2531      *
2532      *          <li> the caller's class loader is not the same as the
2533      *          class loader of this class and invocation of
2534      *          {@link SecurityManager#checkPermission
2535      *          s.checkPermission} method with
2536      *          {@code RuntimePermission("accessDeclaredMembers")}
2537      *          denies access to the declared constructor
2538      *
2539      *          <li> the caller's class loader is not the same as or an
2540      *          ancestor of the class loader for the current class and
2541      *          invocation of {@link SecurityManager#checkPackageAccess
2542      *          s.checkPackageAccess()} denies access to the package
2543      *          of this class
2544      *
2545      *          </ul>
2546      *
2547      * @since 1.1
2548      */
2549     @CallerSensitive
2550     public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
2551         throws NoSuchMethodException, SecurityException
2552     {
2553         SecurityManager sm = System.getSecurityManager();
2554         if (sm != null) {
2555             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2556         }
2557 
2558         return getReflectionFactory().copyConstructor(
2559             getConstructor0(parameterTypes, Member.DECLARED));
2560     }
2561 
2562     /**
2563      * Finds a resource with a given name.
2564      *
2565      * <p> If this class is in a named {@link Module Module} then this method
2566      * will attempt to find the resource in the module. This is done by
2567      * delegating to the module's class loader {@link
2568      * ClassLoader#findResource(String,String) findResource(String,String)}
2569      * method, invoking it with the module name and the absolute name of the
2570      * resource. Resources in named modules are subject to the rules for
2571      * encapsulation specified in the {@code Module} {@link
2572      * Module#getResourceAsStream getResourceAsStream} method and so this
2573      * method returns {@code null} when the resource is a
2574      * non-"{@code .class}" resource in a package that is not open to the
2575      * caller's module.
2576      *
2577      * <p> Otherwise, if this class is not in a named module then the rules for
2578      * searching resources associated with a given class are implemented by the
2579      * defining {@linkplain ClassLoader class loader} of the class.  This method
2580      * delegates to this object's class loader.  If this object was loaded by
2581      * the bootstrap class loader, the method delegates to {@link
2582      * ClassLoader#getSystemResourceAsStream}.
2583      *
2584      * <p> Before delegation, an absolute resource name is constructed from the
2585      * given resource name using this algorithm:
2586      *
2587      * <ul>
2588      *
2589      * <li> If the {@code name} begins with a {@code '/'}
2590      * (<code>'\u002f'</code>), then the absolute name of the resource is the
2591      * portion of the {@code name} following the {@code '/'}.
2592      *
2593      * <li> Otherwise, the absolute name is of the following form:
2594      *
2595      * <blockquote>
2596      *   {@code modified_package_name/name}
2597      * </blockquote>
2598      *
2599      * <p> Where the {@code modified_package_name} is the package name of this
2600      * object with {@code '/'} substituted for {@code '.'}
2601      * (<code>'\u002e'</code>).
2602      *
2603      * </ul>
2604      *
2605      * @param  name name of the desired resource
2606      * @return  A {@link java.io.InputStream} object; {@code null} if no
2607      *          resource with this name is found, the resource is in a package
2608      *          that is not {@linkplain Module#isOpen(String, Module) open} to at
2609      *          least the caller module, or access to the resource is denied
2610      *          by the security manager.
2611      * @throws  NullPointerException If {@code name} is {@code null}
2612      *
2613      * @see Module#getResourceAsStream(String)
2614      * @since  1.1
2615      * @revised 9
2616      * @spec JPMS
2617      */
2618     @CallerSensitive
2619     public InputStream getResourceAsStream(String name) {
2620         name = resolveName(name);
2621 
2622         Module thisModule = getModule();
2623         if (thisModule.isNamed()) {
2624             // check if resource can be located by caller
2625             if (Resources.canEncapsulate(name)
2626                 && !isOpenToCaller(name, Reflection.getCallerClass())) {
2627                 return null;
2628             }
2629 
2630             // resource not encapsulated or in package open to caller
2631             String mn = thisModule.getName();
2632             ClassLoader cl = getClassLoader0();
2633             try {
2634 
2635                 // special-case built-in class loaders to avoid the
2636                 // need for a URL connection
2637                 if (cl == null) {
2638                     return BootLoader.findResourceAsStream(mn, name);
2639                 } else if (cl instanceof BuiltinClassLoader) {
2640                     return ((BuiltinClassLoader) cl).findResourceAsStream(mn, name);
2641                 } else {
2642                     URL url = cl.findResource(mn, name);
2643                     return (url != null) ? url.openStream() : null;
2644                 }
2645 
2646             } catch (IOException | SecurityException e) {
2647                 return null;
2648             }
2649         }
2650 
2651         // unnamed module
2652         ClassLoader cl = getClassLoader0();
2653         if (cl == null) {
2654             return ClassLoader.getSystemResourceAsStream(name);
2655         } else {
2656             return cl.getResourceAsStream(name);
2657         }
2658     }
2659 
2660     /**
2661      * Finds a resource with a given name.
2662      *
2663      * <p> If this class is in a named {@link Module Module} then this method
2664      * will attempt to find the resource in the module. This is done by
2665      * delegating to the module's class loader {@link
2666      * ClassLoader#findResource(String,String) findResource(String,String)}
2667      * method, invoking it with the module name and the absolute name of the
2668      * resource. Resources in named modules are subject to the rules for
2669      * encapsulation specified in the {@code Module} {@link
2670      * Module#getResourceAsStream getResourceAsStream} method and so this
2671      * method returns {@code null} when the resource is a
2672      * non-"{@code .class}" resource in a package that is not open to the
2673      * caller's module.
2674      *
2675      * <p> Otherwise, if this class is not in a named module then the rules for
2676      * searching resources associated with a given class are implemented by the
2677      * defining {@linkplain ClassLoader class loader} of the class.  This method
2678      * delegates to this object's class loader. If this object was loaded by
2679      * the bootstrap class loader, the method delegates to {@link
2680      * ClassLoader#getSystemResource}.
2681      *
2682      * <p> Before delegation, an absolute resource name is constructed from the
2683      * given resource name using this algorithm:
2684      *
2685      * <ul>
2686      *
2687      * <li> If the {@code name} begins with a {@code '/'}
2688      * (<code>'\u002f'</code>), then the absolute name of the resource is the
2689      * portion of the {@code name} following the {@code '/'}.
2690      *
2691      * <li> Otherwise, the absolute name is of the following form:
2692      *
2693      * <blockquote>
2694      *   {@code modified_package_name/name}
2695      * </blockquote>
2696      *
2697      * <p> Where the {@code modified_package_name} is the package name of this
2698      * object with {@code '/'} substituted for {@code '.'}
2699      * (<code>'\u002e'</code>).
2700      *
2701      * </ul>
2702      *
2703      * @param  name name of the desired resource
2704      * @return A {@link java.net.URL} object; {@code null} if no resource with
2705      *         this name is found, the resource cannot be located by a URL, the
2706      *         resource is in a package that is not
2707      *         {@linkplain Module#isOpen(String, Module) open} to at least the caller
2708      *         module, or access to the resource is denied by the security
2709      *         manager.
2710      * @throws NullPointerException If {@code name} is {@code null}
2711      * @since  1.1
2712      * @revised 9
2713      * @spec JPMS
2714      */
2715     @CallerSensitive
2716     public URL getResource(String name) {
2717         name = resolveName(name);
2718 
2719         Module thisModule = getModule();
2720         if (thisModule.isNamed()) {
2721             // check if resource can be located by caller
2722             if (Resources.canEncapsulate(name)
2723                 && !isOpenToCaller(name, Reflection.getCallerClass())) {
2724                 return null;
2725             }
2726 
2727             // resource not encapsulated or in package open to caller
2728             String mn = thisModule.getName();
2729             ClassLoader cl = getClassLoader0();
2730             try {
2731                 if (cl == null) {
2732                     return BootLoader.findResource(mn, name);
2733                 } else {
2734                     return cl.findResource(mn, name);
2735                 }
2736             } catch (IOException ioe) {
2737                 return null;
2738             }
2739         }
2740 
2741         // unnamed module
2742         ClassLoader cl = getClassLoader0();
2743         if (cl == null) {
2744             return ClassLoader.getSystemResource(name);
2745         } else {
2746             return cl.getResource(name);
2747         }
2748     }
2749 
2750     /**
2751      * Returns true if a resource with the given name can be located by the
2752      * given caller. All resources in a module can be located by code in
2753      * the module. For other callers, then the package needs to be open to
2754      * the caller.
2755      */
2756     private boolean isOpenToCaller(String name, Class<?> caller) {
2757         // assert getModule().isNamed();
2758         Module thisModule = getModule();
2759         Module callerModule = (caller != null) ? caller.getModule() : null;
2760         if (callerModule != thisModule) {
2761             String pn = Resources.toPackageName(name);
2762             if (thisModule.getDescriptor().packages().contains(pn)) {
2763                 if (callerModule == null && !thisModule.isOpen(pn)) {
2764                     // no caller, package not open
2765                     return false;
2766                 }
2767                 if (!thisModule.isOpen(pn, callerModule)) {
2768                     // package not open to caller
2769                     return false;
2770                 }
2771             }
2772         }
2773         return true;
2774     }
2775 
2776 
2777     /** protection domain returned when the internal domain is null */
2778     private static java.security.ProtectionDomain allPermDomain;
2779 
2780     /**
2781      * Returns the {@code ProtectionDomain} of this class.  If there is a
2782      * security manager installed, this method first calls the security
2783      * manager's {@code checkPermission} method with a
2784      * {@code RuntimePermission("getProtectionDomain")} permission to
2785      * ensure it's ok to get the
2786      * {@code ProtectionDomain}.
2787      *
2788      * @return the ProtectionDomain of this class
2789      *
2790      * @throws SecurityException
2791      *        if a security manager exists and its
2792      *        {@code checkPermission} method doesn't allow
2793      *        getting the ProtectionDomain.
2794      *
2795      * @see java.security.ProtectionDomain
2796      * @see SecurityManager#checkPermission
2797      * @see java.lang.RuntimePermission
2798      * @since 1.2
2799      */
2800     public java.security.ProtectionDomain getProtectionDomain() {
2801         SecurityManager sm = System.getSecurityManager();
2802         if (sm != null) {
2803             sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
2804         }
2805         java.security.ProtectionDomain pd = getProtectionDomain0();
2806         if (pd == null) {
2807             if (allPermDomain == null) {
2808                 java.security.Permissions perms =
2809                     new java.security.Permissions();
2810                 perms.add(SecurityConstants.ALL_PERMISSION);
2811                 allPermDomain =
2812                     new java.security.ProtectionDomain(null, perms);
2813             }
2814             pd = allPermDomain;
2815         }
2816         return pd;
2817     }
2818 
2819 
2820     /**
2821      * Returns the ProtectionDomain of this class.
2822      */
2823     private native java.security.ProtectionDomain getProtectionDomain0();
2824 
2825     /*
2826      * Return the Virtual Machine's Class object for the named
2827      * primitive type.
2828      */
2829     static native Class<?> getPrimitiveClass(String name);
2830 
2831     /*
2832      * Check if client is allowed to access members.  If access is denied,
2833      * throw a SecurityException.
2834      *
2835      * This method also enforces package access.
2836      *
2837      * <p> Default policy: allow all clients access with normal Java access
2838      * control.
2839      *
2840      * <p> NOTE: should only be called if a SecurityManager is installed
2841      */
2842     private void checkMemberAccess(SecurityManager sm, int which,
2843                                    Class<?> caller, boolean checkProxyInterfaces) {
2844         /* Default policy allows access to all {@link Member#PUBLIC} members,
2845          * as well as access to classes that have the same class loader as the caller.
2846          * In all other cases, it requires RuntimePermission("accessDeclaredMembers")
2847          * permission.
2848          */
2849         final ClassLoader ccl = ClassLoader.getClassLoader(caller);
2850         if (which != Member.PUBLIC) {
2851             final ClassLoader cl = getClassLoader0();
2852             if (ccl != cl) {
2853                 sm.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
2854             }
2855         }
2856         this.checkPackageAccess(sm, ccl, checkProxyInterfaces);
2857     }
2858 
2859     /*
2860      * Checks if a client loaded in ClassLoader ccl is allowed to access this
2861      * class under the current package access policy. If access is denied,
2862      * throw a SecurityException.
2863      *
2864      * NOTE: this method should only be called if a SecurityManager is active
2865      */
2866     private void checkPackageAccess(SecurityManager sm, final ClassLoader ccl,
2867                                     boolean checkProxyInterfaces) {
2868         final ClassLoader cl = getClassLoader0();
2869 
2870         if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
2871             String pkg = this.getPackageName();
2872             if (pkg != null && !pkg.isEmpty()) {
2873                 // skip the package access check on a proxy class in default proxy package
2874                 if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {
2875                     sm.checkPackageAccess(pkg);
2876                 }
2877             }
2878         }
2879         // check package access on the proxy interfaces
2880         if (checkProxyInterfaces && Proxy.isProxyClass(this)) {
2881             ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());
2882         }
2883     }
2884 
2885     /**
2886      * Add a package name prefix if the name is not absolute Remove leading "/"
2887      * if name is absolute
2888      */
2889     private String resolveName(String name) {
2890         if (!name.startsWith("/")) {
2891             Class<?> c = this;
2892             while (c.isArray()) {
2893                 c = c.getComponentType();
2894             }
2895             String baseName = c.getPackageName();
2896             if (baseName != null && !baseName.isEmpty()) {
2897                 name = baseName.replace('.', '/') + "/" + name;
2898             }
2899         } else {
2900             name = name.substring(1);
2901         }
2902         return name;
2903     }
2904 
2905     /**
2906      * Atomic operations support.
2907      */
2908     private static class Atomic {
2909         // initialize Unsafe machinery here, since we need to call Class.class instance method
2910         // and have to avoid calling it in the static initializer of the Class class...
2911         private static final Unsafe unsafe = Unsafe.getUnsafe();
2912         // offset of Class.reflectionData instance field
2913         private static final long reflectionDataOffset
2914                 = unsafe.objectFieldOffset(Class.class, "reflectionData");
2915         // offset of Class.annotationType instance field
2916         private static final long annotationTypeOffset
2917                 = unsafe.objectFieldOffset(Class.class, "annotationType");
2918         // offset of Class.annotationData instance field
2919         private static final long annotationDataOffset
2920                 = unsafe.objectFieldOffset(Class.class, "annotationData");
2921 
2922         static <T> boolean casReflectionData(Class<?> clazz,
2923                                              SoftReference<ReflectionData<T>> oldData,
2924                                              SoftReference<ReflectionData<T>> newData) {
2925             return unsafe.compareAndSetReference(clazz, reflectionDataOffset, oldData, newData);
2926         }
2927 
2928         static <T> boolean casAnnotationType(Class<?> clazz,
2929                                              AnnotationType oldType,
2930                                              AnnotationType newType) {
2931             return unsafe.compareAndSetReference(clazz, annotationTypeOffset, oldType, newType);
2932         }
2933 
2934         static <T> boolean casAnnotationData(Class<?> clazz,
2935                                              AnnotationData oldData,
2936                                              AnnotationData newData) {
2937             return unsafe.compareAndSetReference(clazz, annotationDataOffset, oldData, newData);
2938         }
2939     }
2940 
2941     /**
2942      * Reflection support.
2943      */
2944 
2945     // Reflection data caches various derived names and reflective members. Cached
2946     // values may be invalidated when JVM TI RedefineClasses() is called
2947     private static class ReflectionData<T> {
2948         volatile Field[] declaredFields;
2949         volatile Field[] publicFields;
2950         volatile Method[] declaredMethods;
2951         volatile Method[] publicMethods;
2952         volatile Constructor<T>[] declaredConstructors;
2953         volatile Constructor<T>[] publicConstructors;
2954         // Intermediate results for getFields and getMethods
2955         volatile Field[] declaredPublicFields;
2956         volatile Method[] declaredPublicMethods;
2957         volatile Class<?>[] interfaces;
2958 
2959         // Cached names
2960         String simpleName;
2961         String canonicalName;
2962         static final String NULL_SENTINEL = new String();
2963 
2964         // Value of classRedefinedCount when we created this ReflectionData instance
2965         final int redefinedCount;
2966 
2967         ReflectionData(int redefinedCount) {
2968             this.redefinedCount = redefinedCount;
2969         }
2970     }
2971 
2972     private transient volatile SoftReference<ReflectionData<T>> reflectionData;
2973 
2974     // Incremented by the VM on each call to JVM TI RedefineClasses()
2975     // that redefines this class or a superclass.
2976     private transient volatile int classRedefinedCount;
2977 
2978     // Lazily create and cache ReflectionData
2979     private ReflectionData<T> reflectionData() {
2980         SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
2981         int classRedefinedCount = this.classRedefinedCount;
2982         ReflectionData<T> rd;
2983         if (reflectionData != null &&
2984             (rd = reflectionData.get()) != null &&
2985             rd.redefinedCount == classRedefinedCount) {
2986             return rd;
2987         }
2988         // else no SoftReference or cleared SoftReference or stale ReflectionData
2989         // -> create and replace new instance
2990         return newReflectionData(reflectionData, classRedefinedCount);
2991     }
2992 
2993     private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
2994                                                 int classRedefinedCount) {
2995         while (true) {
2996             ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
2997             // try to CAS it...
2998             if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
2999                 return rd;
3000             }
3001             // else retry
3002             oldReflectionData = this.reflectionData;
3003             classRedefinedCount = this.classRedefinedCount;
3004             if (oldReflectionData != null &&
3005                 (rd = oldReflectionData.get()) != null &&
3006                 rd.redefinedCount == classRedefinedCount) {
3007                 return rd;
3008             }
3009         }
3010     }
3011 
3012     // Generic signature handling
3013     private native String getGenericSignature0();
3014 
3015     // Generic info repository; lazily initialized
3016     private transient volatile ClassRepository genericInfo;
3017 
3018     // accessor for factory
3019     private GenericsFactory getFactory() {
3020         // create scope and factory
3021         return CoreReflectionFactory.make(this, ClassScope.make(this));
3022     }
3023 
3024     // accessor for generic info repository;
3025     // generic info is lazily initialized
3026     private ClassRepository getGenericInfo() {
3027         ClassRepository genericInfo = this.genericInfo;
3028         if (genericInfo == null) {
3029             String signature = getGenericSignature0();
3030             if (signature == null) {
3031                 genericInfo = ClassRepository.NONE;
3032             } else {
3033                 genericInfo = ClassRepository.make(signature, getFactory());
3034             }
3035             this.genericInfo = genericInfo;
3036         }
3037         return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
3038     }
3039 
3040     // Annotations handling
3041     native byte[] getRawAnnotations();
3042     // Since 1.8
3043     native byte[] getRawTypeAnnotations();
3044     static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
3045         return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
3046     }
3047 
3048     native ConstantPool getConstantPool();
3049 
3050     //
3051     //
3052     // java.lang.reflect.Field handling
3053     //
3054     //
3055 
3056     // Returns an array of "root" fields. These Field objects must NOT
3057     // be propagated to the outside world, but must instead be copied
3058     // via ReflectionFactory.copyField.
3059     private Field[] privateGetDeclaredFields(boolean publicOnly) {
3060         Field[] res;
3061         ReflectionData<T> rd = reflectionData();
3062         if (rd != null) {
3063             res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
3064             if (res != null) return res;
3065         }
3066         // No cached value available; request value from VM
3067         res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
3068         if (rd != null) {
3069             if (publicOnly) {
3070                 rd.declaredPublicFields = res;
3071             } else {
3072                 rd.declaredFields = res;
3073             }
3074         }
3075         return res;
3076     }
3077 
3078     // Returns an array of "root" fields. These Field objects must NOT
3079     // be propagated to the outside world, but must instead be copied
3080     // via ReflectionFactory.copyField.
3081     private Field[] privateGetPublicFields() {
3082         Field[] res;
3083         ReflectionData<T> rd = reflectionData();
3084         if (rd != null) {
3085             res = rd.publicFields;
3086             if (res != null) return res;
3087         }
3088 
3089         // Use a linked hash set to ensure order is preserved and
3090         // fields from common super interfaces are not duplicated
3091         LinkedHashSet<Field> fields = new LinkedHashSet<>();
3092 
3093         // Local fields
3094         addAll(fields, privateGetDeclaredFields(true));
3095 
3096         // Direct superinterfaces, recursively
3097         for (Class<?> si : getInterfaces()) {
3098             addAll(fields, si.privateGetPublicFields());
3099         }
3100 
3101         // Direct superclass, recursively
3102         Class<?> sc = getSuperclass();
3103         if (sc != null) {
3104             addAll(fields, sc.privateGetPublicFields());
3105         }
3106 
3107         res = fields.toArray(new Field[0]);
3108         if (rd != null) {
3109             rd.publicFields = res;
3110         }
3111         return res;
3112     }
3113 
3114     private static void addAll(Collection<Field> c, Field[] o) {
3115         for (Field f : o) {
3116             c.add(f);
3117         }
3118     }
3119 
3120 
3121     //
3122     //
3123     // java.lang.reflect.Constructor handling
3124     //
3125     //
3126 
3127     // Returns an array of "root" constructors. These Constructor
3128     // objects must NOT be propagated to the outside world, but must
3129     // instead be copied via ReflectionFactory.copyConstructor.
3130     private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
3131         Constructor<T>[] res;
3132         ReflectionData<T> rd = reflectionData();
3133         if (rd != null) {
3134             res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
3135             if (res != null) return res;
3136         }
3137         // No cached value available; request value from VM
3138         if (isInterface()) {
3139             @SuppressWarnings("unchecked")
3140             Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
3141             res = temporaryRes;
3142         } else {
3143             res = getDeclaredConstructors0(publicOnly);
3144         }
3145         if (rd != null) {
3146             if (publicOnly) {
3147                 rd.publicConstructors = res;
3148             } else {
3149                 rd.declaredConstructors = res;
3150             }
3151         }
3152         return res;
3153     }
3154 
3155     //
3156     //
3157     // java.lang.reflect.Method handling
3158     //
3159     //
3160 
3161     // Returns an array of "root" methods. These Method objects must NOT
3162     // be propagated to the outside world, but must instead be copied
3163     // via ReflectionFactory.copyMethod.
3164     private Method[] privateGetDeclaredMethods(boolean publicOnly) {
3165         Method[] res;
3166         ReflectionData<T> rd = reflectionData();
3167         if (rd != null) {
3168             res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
3169             if (res != null) return res;
3170         }
3171         // No cached value available; request value from VM
3172         res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
3173         if (rd != null) {
3174             if (publicOnly) {
3175                 rd.declaredPublicMethods = res;
3176             } else {
3177                 rd.declaredMethods = res;
3178             }
3179         }
3180         return res;
3181     }
3182 
3183     // Returns an array of "root" methods. These Method objects must NOT
3184     // be propagated to the outside world, but must instead be copied
3185     // via ReflectionFactory.copyMethod.
3186     private Method[] privateGetPublicMethods() {
3187         Method[] res;
3188         ReflectionData<T> rd = reflectionData();
3189         if (rd != null) {
3190             res = rd.publicMethods;
3191             if (res != null) return res;
3192         }
3193 
3194         // No cached value available; compute value recursively.
3195         // Start by fetching public declared methods...
3196         PublicMethods pms = new PublicMethods();
3197         for (Method m : privateGetDeclaredMethods(/* publicOnly */ true)) {
3198             pms.merge(m);
3199         }
3200         // ...then recur over superclass methods...
3201         Class<?> sc = getSuperclass();
3202         if (sc != null) {
3203             for (Method m : sc.privateGetPublicMethods()) {
3204                 pms.merge(m);
3205             }
3206         }
3207         // ...and finally over direct superinterfaces.
3208         for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
3209             for (Method m : intf.privateGetPublicMethods()) {
3210                 // static interface methods are not inherited
3211                 if (!Modifier.isStatic(m.getModifiers())) {
3212                     pms.merge(m);
3213                 }
3214             }
3215         }
3216 
3217         res = pms.toArray();
3218         if (rd != null) {
3219             rd.publicMethods = res;
3220         }
3221         return res;
3222     }
3223 
3224 
3225     //
3226     // Helpers for fetchers of one field, method, or constructor
3227     //
3228 
3229     // This method does not copy the returned Field object!
3230     private static Field searchFields(Field[] fields, String name) {
3231         for (Field field : fields) {
3232             if (field.getName().equals(name)) {
3233                 return field;
3234             }
3235         }
3236         return null;
3237     }
3238 
3239     // Returns a "root" Field object. This Field object must NOT
3240     // be propagated to the outside world, but must instead be copied
3241     // via ReflectionFactory.copyField.
3242     private Field getField0(String name) {
3243         // Note: the intent is that the search algorithm this routine
3244         // uses be equivalent to the ordering imposed by
3245         // privateGetPublicFields(). It fetches only the declared
3246         // public fields for each class, however, to reduce the number
3247         // of Field objects which have to be created for the common
3248         // case where the field being requested is declared in the
3249         // class which is being queried.
3250         Field res;
3251         // Search declared public fields
3252         if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
3253             return res;
3254         }
3255         // Direct superinterfaces, recursively
3256         Class<?>[] interfaces = getInterfaces(/* cloneArray */ false);
3257         for (Class<?> c : interfaces) {
3258             if ((res = c.getField0(name)) != null) {
3259                 return res;
3260             }
3261         }
3262         // Direct superclass, recursively
3263         if (!isInterface()) {
3264             Class<?> c = getSuperclass();
3265             if (c != null) {
3266                 if ((res = c.getField0(name)) != null) {
3267                     return res;
3268                 }
3269             }
3270         }
3271         return null;
3272     }
3273 
3274     // This method does not copy the returned Method object!
3275     private static Method searchMethods(Method[] methods,
3276                                         String name,
3277                                         Class<?>[] parameterTypes)
3278     {
3279         ReflectionFactory fact = getReflectionFactory();
3280         Method res = null;
3281         for (Method m : methods) {
3282             if (m.getName().equals(name)
3283                 && arrayContentsEq(parameterTypes,
3284                                    fact.getExecutableSharedParameterTypes(m))
3285                 && (res == null
3286                     || (res.getReturnType() != m.getReturnType()
3287                         && res.getReturnType().isAssignableFrom(m.getReturnType()))))
3288                 res = m;
3289         }
3290         return res;
3291     }
3292 
3293     private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
3294 
3295     // Returns a "root" Method object. This Method object must NOT
3296     // be propagated to the outside world, but must instead be copied
3297     // via ReflectionFactory.copyMethod.
3298     private Method getMethod0(String name, Class<?>[] parameterTypes) {
3299         PublicMethods.MethodList res = getMethodsRecursive(
3300             name,
3301             parameterTypes == null ? EMPTY_CLASS_ARRAY : parameterTypes,
3302             /* includeStatic */ true);
3303         return res == null ? null : res.getMostSpecific();
3304     }
3305 
3306     // Returns a list of "root" Method objects. These Method objects must NOT
3307     // be propagated to the outside world, but must instead be copied
3308     // via ReflectionFactory.copyMethod.
3309     private PublicMethods.MethodList getMethodsRecursive(String name,
3310                                                          Class<?>[] parameterTypes,
3311                                                          boolean includeStatic) {
3312         // 1st check declared public methods
3313         Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);
3314         PublicMethods.MethodList res = PublicMethods.MethodList
3315             .filter(methods, name, parameterTypes, includeStatic);
3316         // if there is at least one match among declared methods, we need not
3317         // search any further as such match surely overrides matching methods
3318         // declared in superclass(es) or interface(s).
3319         if (res != null) {
3320             return res;
3321         }
3322 
3323         // if there was no match among declared methods,
3324         // we must consult the superclass (if any) recursively...
3325         Class<?> sc = getSuperclass();
3326         if (sc != null) {
3327             res = sc.getMethodsRecursive(name, parameterTypes, includeStatic);
3328         }
3329 
3330         // ...and coalesce the superclass methods with methods obtained
3331         // from directly implemented interfaces excluding static methods...
3332         for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
3333             res = PublicMethods.MethodList.merge(
3334                 res, intf.getMethodsRecursive(name, parameterTypes,
3335                                               /* includeStatic */ false));
3336         }
3337 
3338         return res;
3339     }
3340 
3341     // Returns a "root" Constructor object. This Constructor object must NOT
3342     // be propagated to the outside world, but must instead be copied
3343     // via ReflectionFactory.copyConstructor.
3344     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3345                                         int which) throws NoSuchMethodException
3346     {
3347         ReflectionFactory fact = getReflectionFactory();
3348         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3349         for (Constructor<T> constructor : constructors) {
3350             if (arrayContentsEq(parameterTypes,
3351                                 fact.getExecutableSharedParameterTypes(constructor))) {
3352                 return constructor;
3353             }
3354         }
3355         throw new NoSuchMethodException(methodToString("<init>", parameterTypes));
3356     }
3357 
3358     //
3359     // Other helpers and base implementation
3360     //
3361 
3362     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3363         if (a1 == null) {
3364             return a2 == null || a2.length == 0;
3365         }
3366 
3367         if (a2 == null) {
3368             return a1.length == 0;
3369         }
3370 
3371         if (a1.length != a2.length) {
3372             return false;
3373         }
3374 
3375         for (int i = 0; i < a1.length; i++) {
3376             if (a1[i] != a2[i]) {
3377                 return false;
3378             }
3379         }
3380 
3381         return true;
3382     }
3383 
3384     private static Field[] copyFields(Field[] arg) {
3385         Field[] out = new Field[arg.length];
3386         ReflectionFactory fact = getReflectionFactory();
3387         for (int i = 0; i < arg.length; i++) {
3388             out[i] = fact.copyField(arg[i]);
3389         }
3390         return out;
3391     }
3392 
3393     private static Method[] copyMethods(Method[] arg) {
3394         Method[] out = new Method[arg.length];
3395         ReflectionFactory fact = getReflectionFactory();
3396         for (int i = 0; i < arg.length; i++) {
3397             out[i] = fact.copyMethod(arg[i]);
3398         }
3399         return out;
3400     }
3401 
3402     private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
3403         Constructor<U>[] out = arg.clone();
3404         ReflectionFactory fact = getReflectionFactory();
3405         for (int i = 0; i < out.length; i++) {
3406             out[i] = fact.copyConstructor(out[i]);
3407         }
3408         return out;
3409     }
3410 
3411     private native Field[]       getDeclaredFields0(boolean publicOnly);
3412     private native Method[]      getDeclaredMethods0(boolean publicOnly);
3413     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3414     private native Class<?>[]   getDeclaredClasses0();
3415 
3416     /**
3417      * Helper method to get the method name from arguments.
3418      */
3419     private String methodToString(String name, Class<?>[] argTypes) {
3420         StringBuilder sb = new StringBuilder();
3421         sb.append(getName() + "." + name + "(");
3422         if (argTypes != null) {
3423             Stream.of(argTypes).map(c -> {return (c == null) ? "null" : c.getName();}).
3424                 collect(Collectors.joining(","));
3425         }
3426         sb.append(")");
3427         return sb.toString();
3428     }
3429 
3430     /** use serialVersionUID from JDK 1.1 for interoperability */
3431     private static final long serialVersionUID = 3206093459760846163L;
3432 
3433 
3434     /**
3435      * Class Class is special cased within the Serialization Stream Protocol.
3436      *
3437      * A Class instance is written initially into an ObjectOutputStream in the
3438      * following format:
3439      * <pre>
3440      *      {@code TC_CLASS} ClassDescriptor
3441      *      A ClassDescriptor is a special cased serialization of
3442      *      a {@code java.io.ObjectStreamClass} instance.
3443      * </pre>
3444      * A new handle is generated for the initial time the class descriptor
3445      * is written into the stream. Future references to the class descriptor
3446      * are written as references to the initial class descriptor instance.
3447      *
3448      * @see java.io.ObjectStreamClass
3449      */
3450     private static final ObjectStreamField[] serialPersistentFields =
3451         new ObjectStreamField[0];
3452 
3453 
3454     /**
3455      * Returns the assertion status that would be assigned to this
3456      * class if it were to be initialized at the time this method is invoked.
3457      * If this class has had its assertion status set, the most recent
3458      * setting will be returned; otherwise, if any package default assertion
3459      * status pertains to this class, the most recent setting for the most
3460      * specific pertinent package default assertion status is returned;
3461      * otherwise, if this class is not a system class (i.e., it has a
3462      * class loader) its class loader's default assertion status is returned;
3463      * otherwise, the system class default assertion status is returned.
3464      * <p>
3465      * Few programmers will have any need for this method; it is provided
3466      * for the benefit of the JRE itself.  (It allows a class to determine at
3467      * the time that it is initialized whether assertions should be enabled.)
3468      * Note that this method is not guaranteed to return the actual
3469      * assertion status that was (or will be) associated with the specified
3470      * class when it was (or will be) initialized.
3471      *
3472      * @return the desired assertion status of the specified class.
3473      * @see    java.lang.ClassLoader#setClassAssertionStatus
3474      * @see    java.lang.ClassLoader#setPackageAssertionStatus
3475      * @see    java.lang.ClassLoader#setDefaultAssertionStatus
3476      * @since  1.4
3477      */
3478     public boolean desiredAssertionStatus() {
3479         ClassLoader loader = getClassLoader0();
3480         // If the loader is null this is a system class, so ask the VM
3481         if (loader == null)
3482             return desiredAssertionStatus0(this);
3483 
3484         // If the classloader has been initialized with the assertion
3485         // directives, ask it. Otherwise, ask the VM.
3486         synchronized(loader.assertionLock) {
3487             if (loader.classAssertionStatus != null) {
3488                 return loader.desiredAssertionStatus(getName());
3489             }
3490         }
3491         return desiredAssertionStatus0(this);
3492     }
3493 
3494     // Retrieves the desired assertion status of this class from the VM
3495     private static native boolean desiredAssertionStatus0(Class<?> clazz);
3496 
3497     /**
3498      * Returns true if and only if this class was declared as an enum in the
3499      * source code.
3500      *
3501      * @return true if and only if this class was declared as an enum in the
3502      *     source code
3503      * @since 1.5
3504      */
3505     public boolean isEnum() {
3506         // An enum must both directly extend java.lang.Enum and have
3507         // the ENUM bit set; classes for specialized enum constants
3508         // don't do the former.
3509         return (this.getModifiers() & ENUM) != 0 &&
3510         this.getSuperclass() == java.lang.Enum.class;
3511     }
3512 
3513     // Fetches the factory for reflective objects
3514     private static ReflectionFactory getReflectionFactory() {
3515         if (reflectionFactory == null) {
3516             reflectionFactory =
3517                 java.security.AccessController.doPrivileged
3518                     (new ReflectionFactory.GetReflectionFactoryAction());
3519         }
3520         return reflectionFactory;
3521     }
3522     private static ReflectionFactory reflectionFactory;
3523 
3524     /**
3525      * Returns the elements of this enum class or null if this
3526      * Class object does not represent an enum type.
3527      *
3528      * @return an array containing the values comprising the enum class
3529      *     represented by this Class object in the order they're
3530      *     declared, or null if this Class object does not
3531      *     represent an enum type
3532      * @since 1.5
3533      */
3534     public T[] getEnumConstants() {
3535         T[] values = getEnumConstantsShared();
3536         return (values != null) ? values.clone() : null;
3537     }
3538 
3539     /**
3540      * Returns the elements of this enum class or null if this
3541      * Class object does not represent an enum type;
3542      * identical to getEnumConstants except that the result is
3543      * uncloned, cached, and shared by all callers.
3544      */
3545     T[] getEnumConstantsShared() {
3546         T[] constants = enumConstants;
3547         if (constants == null) {
3548             if (!isEnum()) return null;
3549             try {
3550                 final Method values = getMethod("values");
3551                 java.security.AccessController.doPrivileged(
3552                     new java.security.PrivilegedAction<>() {
3553                         public Void run() {
3554                                 values.setAccessible(true);
3555                                 return null;
3556                             }
3557                         });
3558                 @SuppressWarnings("unchecked")
3559                 T[] temporaryConstants = (T[])values.invoke(null);
3560                 enumConstants = constants = temporaryConstants;
3561             }
3562             // These can happen when users concoct enum-like classes
3563             // that don't comply with the enum spec.
3564             catch (InvocationTargetException | NoSuchMethodException |
3565                    IllegalAccessException ex) { return null; }
3566         }
3567         return constants;
3568     }
3569     private transient volatile T[] enumConstants;
3570 
3571     /**
3572      * Returns a map from simple name to enum constant.  This package-private
3573      * method is used internally by Enum to implement
3574      * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}
3575      * efficiently.  Note that the map is returned by this method is
3576      * created lazily on first use.  Typically it won't ever get created.
3577      */
3578     Map<String, T> enumConstantDirectory() {
3579         Map<String, T> directory = enumConstantDirectory;
3580         if (directory == null) {
3581             T[] universe = getEnumConstantsShared();
3582             if (universe == null)
3583                 throw new IllegalArgumentException(
3584                     getName() + " is not an enum type");
3585             directory = new HashMap<>((int)(universe.length / 0.75f) + 1);
3586             for (T constant : universe) {
3587                 directory.put(((Enum<?>)constant).name(), constant);
3588             }
3589             enumConstantDirectory = directory;
3590         }
3591         return directory;
3592     }
3593     private transient volatile Map<String, T> enumConstantDirectory;
3594 
3595     /**
3596      * Casts an object to the class or interface represented
3597      * by this {@code Class} object.
3598      *
3599      * @param obj the object to be cast
3600      * @return the object after casting, or null if obj is null
3601      *
3602      * @throws ClassCastException if the object is not
3603      * null and is not assignable to the type T.
3604      *
3605      * @since 1.5
3606      */
3607     @SuppressWarnings("unchecked")
3608     @HotSpotIntrinsicCandidate
3609     public T cast(Object obj) {
3610         if (obj != null && !isInstance(obj))
3611             throw new ClassCastException(cannotCastMsg(obj));
3612         return (T) obj;
3613     }
3614 
3615     private String cannotCastMsg(Object obj) {
3616         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3617     }
3618 
3619     /**
3620      * Casts this {@code Class} object to represent a subclass of the class
3621      * represented by the specified class object.  Checks that the cast
3622      * is valid, and throws a {@code ClassCastException} if it is not.  If
3623      * this method succeeds, it always returns a reference to this class object.
3624      *
3625      * <p>This method is useful when a client needs to "narrow" the type of
3626      * a {@code Class} object to pass it to an API that restricts the
3627      * {@code Class} objects that it is willing to accept.  A cast would
3628      * generate a compile-time warning, as the correctness of the cast
3629      * could not be checked at runtime (because generic types are implemented
3630      * by erasure).
3631      *
3632      * @param <U> the type to cast this class object to
3633      * @param clazz the class of the type to cast this class object to
3634      * @return this {@code Class} object, cast to represent a subclass of
3635      *    the specified class object.
3636      * @throws ClassCastException if this {@code Class} object does not
3637      *    represent a subclass of the specified class (here "subclass" includes
3638      *    the class itself).
3639      * @since 1.5
3640      */
3641     @SuppressWarnings("unchecked")
3642     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
3643         if (clazz.isAssignableFrom(this))
3644             return (Class<? extends U>) this;
3645         else
3646             throw new ClassCastException(this.toString());
3647     }
3648 
3649     /**
3650      * @throws NullPointerException {@inheritDoc}
3651      * @since 1.5
3652      */
3653     @SuppressWarnings("unchecked")
3654     public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
3655         Objects.requireNonNull(annotationClass);
3656 
3657         return (A) annotationData().annotations.get(annotationClass);
3658     }
3659 
3660     /**
3661      * {@inheritDoc}
3662      * @throws NullPointerException {@inheritDoc}
3663      * @since 1.5
3664      */
3665     @Override
3666     public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
3667         return GenericDeclaration.super.isAnnotationPresent(annotationClass);
3668     }
3669 
3670     /**
3671      * @throws NullPointerException {@inheritDoc}
3672      * @since 1.8
3673      */
3674     @Override
3675     public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {
3676         Objects.requireNonNull(annotationClass);
3677 
3678         AnnotationData annotationData = annotationData();
3679         return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations,
3680                                                           this,
3681                                                           annotationClass);
3682     }
3683 
3684     /**
3685      * @since 1.5
3686      */
3687     public Annotation[] getAnnotations() {
3688         return AnnotationParser.toArray(annotationData().annotations);
3689     }
3690 
3691     /**
3692      * @throws NullPointerException {@inheritDoc}
3693      * @since 1.8
3694      */
3695     @Override
3696     @SuppressWarnings("unchecked")
3697     public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
3698         Objects.requireNonNull(annotationClass);
3699 
3700         return (A) annotationData().declaredAnnotations.get(annotationClass);
3701     }
3702 
3703     /**
3704      * @throws NullPointerException {@inheritDoc}
3705      * @since 1.8
3706      */
3707     @Override
3708     public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {
3709         Objects.requireNonNull(annotationClass);
3710 
3711         return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,
3712                                                                  annotationClass);
3713     }
3714 
3715     /**
3716      * @since 1.5
3717      */
3718     public Annotation[] getDeclaredAnnotations()  {
3719         return AnnotationParser.toArray(annotationData().declaredAnnotations);
3720     }
3721 
3722     // annotation data that might get invalidated when JVM TI RedefineClasses() is called
3723     private static class AnnotationData {
3724         final Map<Class<? extends Annotation>, Annotation> annotations;
3725         final Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
3726 
3727         // Value of classRedefinedCount when we created this AnnotationData instance
3728         final int redefinedCount;
3729 
3730         AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations,
3731                        Map<Class<? extends Annotation>, Annotation> declaredAnnotations,
3732                        int redefinedCount) {
3733             this.annotations = annotations;
3734             this.declaredAnnotations = declaredAnnotations;
3735             this.redefinedCount = redefinedCount;
3736         }
3737     }
3738 
3739     // Annotations cache
3740     @SuppressWarnings("UnusedDeclaration")
3741     private transient volatile AnnotationData annotationData;
3742 
3743     private AnnotationData annotationData() {
3744         while (true) { // retry loop
3745             AnnotationData annotationData = this.annotationData;
3746             int classRedefinedCount = this.classRedefinedCount;
3747             if (annotationData != null &&
3748                 annotationData.redefinedCount == classRedefinedCount) {
3749                 return annotationData;
3750             }
3751             // null or stale annotationData -> optimistically create new instance
3752             AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount);
3753             // try to install it
3754             if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) {
3755                 // successfully installed new AnnotationData
3756                 return newAnnotationData;
3757             }
3758         }
3759     }
3760 
3761     private AnnotationData createAnnotationData(int classRedefinedCount) {
3762         Map<Class<? extends Annotation>, Annotation> declaredAnnotations =
3763             AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this);
3764         Class<?> superClass = getSuperclass();
3765         Map<Class<? extends Annotation>, Annotation> annotations = null;
3766         if (superClass != null) {
3767             Map<Class<? extends Annotation>, Annotation> superAnnotations =
3768                 superClass.annotationData().annotations;
3769             for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) {
3770                 Class<? extends Annotation> annotationClass = e.getKey();
3771                 if (AnnotationType.getInstance(annotationClass).isInherited()) {
3772                     if (annotations == null) { // lazy construction
3773                         annotations = new LinkedHashMap<>((Math.max(
3774                                 declaredAnnotations.size(),
3775                                 Math.min(12, declaredAnnotations.size() + superAnnotations.size())
3776                             ) * 4 + 2) / 3
3777                         );
3778                     }
3779                     annotations.put(annotationClass, e.getValue());
3780                 }
3781             }
3782         }
3783         if (annotations == null) {
3784             // no inherited annotations -> share the Map with declaredAnnotations
3785             annotations = declaredAnnotations;
3786         } else {
3787             // at least one inherited annotation -> declared may override inherited
3788             annotations.putAll(declaredAnnotations);
3789         }
3790         return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount);
3791     }
3792 
3793     // Annotation types cache their internal (AnnotationType) form
3794 
3795     @SuppressWarnings("UnusedDeclaration")
3796     private transient volatile AnnotationType annotationType;
3797 
3798     boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {
3799         return Atomic.casAnnotationType(this, oldType, newType);
3800     }
3801 
3802     AnnotationType getAnnotationType() {
3803         return annotationType;
3804     }
3805 
3806     Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() {
3807         return annotationData().declaredAnnotations;
3808     }
3809 
3810     /* Backing store of user-defined values pertaining to this class.
3811      * Maintained by the ClassValue class.
3812      */
3813     transient ClassValue.ClassValueMap classValueMap;
3814 
3815     /**
3816      * Returns an {@code AnnotatedType} object that represents the use of a
3817      * type to specify the superclass of the entity represented by this {@code
3818      * Class} object. (The <em>use</em> of type Foo to specify the superclass
3819      * in '...  extends Foo' is distinct from the <em>declaration</em> of type
3820      * Foo.)
3821      *
3822      * <p> If this {@code Class} object represents a type whose declaration
3823      * does not explicitly indicate an annotated superclass, then the return
3824      * value is an {@code AnnotatedType} object representing an element with no
3825      * annotations.
3826      *
3827      * <p> If this {@code Class} represents either the {@code Object} class, an
3828      * interface type, an array type, a primitive type, or void, the return
3829      * value is {@code null}.
3830      *
3831      * @return an object representing the superclass
3832      * @since 1.8
3833      */
3834     public AnnotatedType getAnnotatedSuperclass() {
3835         if (this == Object.class ||
3836                 isInterface() ||
3837                 isArray() ||
3838                 isPrimitive() ||
3839                 this == Void.TYPE) {
3840             return null;
3841         }
3842 
3843         return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
3844     }
3845 
3846     /**
3847      * Returns an array of {@code AnnotatedType} objects that represent the use
3848      * of types to specify superinterfaces of the entity represented by this
3849      * {@code Class} object. (The <em>use</em> of type Foo to specify a
3850      * superinterface in '... implements Foo' is distinct from the
3851      * <em>declaration</em> of type Foo.)
3852      *
3853      * <p> If this {@code Class} object represents a class, the return value is
3854      * an array containing objects representing the uses of interface types to
3855      * specify interfaces implemented by the class. The order of the objects in
3856      * the array corresponds to the order of the interface types used in the
3857      * 'implements' clause of the declaration of this {@code Class} object.
3858      *
3859      * <p> If this {@code Class} object represents an interface, the return
3860      * value is an array containing objects representing the uses of interface
3861      * types to specify interfaces directly extended by the interface. The
3862      * order of the objects in the array corresponds to the order of the
3863      * interface types used in the 'extends' clause of the declaration of this
3864      * {@code Class} object.
3865      *
3866      * <p> If this {@code Class} object represents a class or interface whose
3867      * declaration does not explicitly indicate any annotated superinterfaces,
3868      * the return value is an array of length 0.
3869      *
3870      * <p> If this {@code Class} object represents either the {@code Object}
3871      * class, an array type, a primitive type, or void, the return value is an
3872      * array of length 0.
3873      *
3874      * @return an array representing the superinterfaces
3875      * @since 1.8
3876      */
3877     public AnnotatedType[] getAnnotatedInterfaces() {
3878          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3879     }
3880 
3881     private native Class<?> getNestHost0();
3882 
3883     /**
3884      * Returns the nest host of the <a href=#nest>nest</a> to which the class
3885      * or interface represented by this {@code Class} object belongs.
3886      * Every class and interface is a member of exactly one nest.
3887      * A class or interface that is not recorded as belonging to a nest
3888      * belongs to the nest consisting only of itself, and is the nest
3889      * host.
3890      *
3891      * <p>Each of the {@code Class} objects representing array types,
3892      * primitive types, and {@code void} returns {@code this} to indicate
3893      * that the represented entity belongs to the nest consisting only of
3894      * itself, and is the nest host.
3895      *
3896      * <p>If there is a {@linkplain LinkageError linkage error} accessing
3897      * the nest host, or if this class or interface is not enumerated as
3898      * a member of the nest by the nest host, then it is considered to belong
3899      * to its own nest and {@code this} is returned as the host.
3900      *
3901      * @apiNote A {@code class} file of version 55.0 or greater may record the
3902      * host of the nest to which it belongs by using the {@code NestHost}
3903      * attribute (JVMS 4.7.28). Alternatively, a {@code class} file of
3904      * version 55.0 or greater may act as a nest host by enumerating the nest's
3905      * other members with the
3906      * {@code NestMembers} attribute (JVMS 4.7.29).
3907      * A {@code class} file of version 54.0 or lower does not use these
3908      * attributes.
3909      *
3910      * @return the nest host of this class or interface
3911      *
3912      * @throws SecurityException
3913      *         If the returned class is not the current class, and
3914      *         if a security manager, <i>s</i>, is present and the caller's
3915      *         class loader is not the same as or an ancestor of the class
3916      *         loader for the returned class and invocation of {@link
3917      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
3918      *         denies access to the package of the returned class
3919      * @since 11
3920      * @jvms 4.7.28 and 4.7.29 NestHost and NestMembers attributes
3921      * @jvms 5.4.4 Access Control
3922      */
3923     @CallerSensitive
3924     public Class<?> getNestHost() {
3925         if (isPrimitive() || isArray()) {
3926             return this;
3927         }
3928         Class<?> host;
3929         try {
3930             host = getNestHost0();
3931         } catch (LinkageError e) {
3932             // if we couldn't load our nest-host then we
3933             // act as-if we have no nest-host attribute
3934             return this;
3935         }
3936         // if null then nest membership validation failed, so we
3937         // act as-if we have no nest-host attribute
3938         if (host == null || host == this) {
3939             return this;
3940         }
3941         // returning a different class requires a security check
3942         SecurityManager sm = System.getSecurityManager();
3943         if (sm != null) {
3944             checkPackageAccess(sm,
3945                                ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
3946         }
3947         return host;
3948     }
3949 
3950     /**
3951      * Determines if the given {@code Class} is a nestmate of the
3952      * class or interface represented by this {@code Class} object.
3953      * Two classes or interfaces are nestmates
3954      * if they have the same {@linkplain #getNestHost() nest host}.
3955      *
3956      * @param c the class to check
3957      * @return {@code true} if this class and {@code c} are members of
3958      * the same nest; and {@code false} otherwise.
3959      *
3960      * @since 11
3961      */
3962     public boolean isNestmateOf(Class<?> c) {
3963         if (this == c) {
3964             return true;
3965         }
3966         if (isPrimitive() || isArray() ||
3967             c.isPrimitive() || c.isArray()) {
3968             return false;
3969         }
3970         try {
3971             return getNestHost0() == c.getNestHost0();
3972         } catch (LinkageError e) {
3973             return false;
3974         }
3975     }
3976 
3977     private native Class<?>[] getNestMembers0();
3978 
3979     /**
3980      * Returns an array containing {@code Class} objects representing all the
3981      * classes and interfaces that are members of the nest to which the class
3982      * or interface represented by this {@code Class} object belongs.
3983      * The {@linkplain #getNestHost() nest host} of that nest is the zeroth
3984      * element of the array. Subsequent elements represent any classes or
3985      * interfaces that are recorded by the nest host as being members of
3986      * the nest; the order of such elements is unspecified. Duplicates are
3987      * permitted.
3988      * If the nest host of that nest does not enumerate any members, then the
3989      * array has a single element containing {@code this}.
3990      *
3991      * <p>Each of the {@code Class} objects representing array types,
3992      * primitive types, and {@code void} returns an array containing only
3993      * {@code this}.
3994      *
3995      * <p>This method validates that, for each class or interface which is
3996      * recorded as a member of the nest by the nest host, that class or
3997      * interface records itself as a member of that same nest. Any exceptions
3998      * that occur during this validation are rethrown by this method.
3999      *
4000      * @return an array of all classes and interfaces in the same nest as
4001      * this class
4002      *
4003      * @throws LinkageError
4004      *         If there is any problem loading or validating a nest member or
4005      *         its nest host
4006      * @throws SecurityException
4007      *         If any returned class is not the current class, and
4008      *         if a security manager, <i>s</i>, is present and the caller's
4009      *         class loader is not the same as or an ancestor of the class
4010      *         loader for that returned class and invocation of {@link
4011      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
4012      *         denies access to the package of that returned class
4013      *
4014      * @since 11
4015      * @see #getNestHost()
4016      */
4017     @CallerSensitive
4018     public Class<?>[] getNestMembers() {
4019         if (isPrimitive() || isArray()) {
4020             return new Class<?>[] { this };
4021         }
4022         Class<?>[] members = getNestMembers0();
4023         // Can't actually enable this due to bootstrapping issues
4024         // assert(members.length != 1 || members[0] == this); // expected invariant from VM
4025 
4026         if (members.length > 1) {
4027             // If we return anything other than the current class we need
4028             // a security check
4029             SecurityManager sm = System.getSecurityManager();
4030             if (sm != null) {
4031                 checkPackageAccess(sm,
4032                                    ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
4033             }
4034         }
4035         return members;
4036     }
4037 
4038     /**
4039      * Returns the type descriptor string for this class.
4040      * <p>
4041      * Note that this is not a strict inverse of {@link #forName};
4042      * distinct classes which share a common name but have different class loaders
4043      * will have identical descriptor strings.
4044      *
4045      * @return the type descriptor representation
4046      * @jvms 4.3.2 Field Descriptors
4047      * @since 12
4048      */
4049     @Override
4050     public String descriptorString() {
4051         if (isPrimitive())
4052             return Wrapper.forPrimitiveType(this).basicTypeString();
4053         else if (isArray()) {
4054             return "[" + componentType.descriptorString();
4055         }
4056         else {
4057             return "L" + getName().replace('.', '/') + ";";
4058         }
4059     }
4060 
4061     /**
4062      * Returns the component type of this {@code Class}, if it describes
4063      * an array type, or {@code null} otherwise.  Equivalent to
4064      * {@link Class#getComponentType()}.
4065      *
4066      * @return a {@code Class} describing the component type, or {@code null}
4067      * if this {@code Class} does not describe an array type
4068      * @since 12
4069      */
4070     @Override
4071     public Class<?> componentType() {
4072         return isArray() ? componentType : null;
4073     }
4074 
4075     /**
4076      * Returns a {@code Class} for an array type whose component type
4077      * is described by this {@linkplain Class}.
4078      *
4079      * @return a {@code Class} describing the array type
4080      * @since 12
4081      */
4082     @Override
4083     public Class<?> arrayType() {
4084         return Array.newInstance(this, 0).getClass();
4085     }
4086 
4087     /**
4088      * Returns a nominal descriptor for this instance, if one can be
4089      * constructed, or an empty {@link Optional} if one cannot be.
4090      *
4091      * @return An {@link Optional} containing the resulting nominal descriptor,
4092      * or an empty {@link Optional} if one cannot be constructed.
4093      * @since 12
4094      */
4095     @Override
4096     public Optional<ClassDesc> describeConstable() {
4097         return Optional.of(ClassDesc.ofDescriptor(descriptorString()));
4098     }
4099 }