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