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