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