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