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