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