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