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