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