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