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