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