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