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