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