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