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