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