1 /*
   2  * Copyright (c) 1994, 2013, 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.reflect.AnnotatedElement;
  29 import java.lang.reflect.Array;
  30 import java.lang.reflect.GenericArrayType;
  31 import java.lang.reflect.GenericDeclaration;
  32 import java.lang.reflect.Member;
  33 import java.lang.reflect.Field;
  34 import java.lang.reflect.Executable;
  35 import java.lang.reflect.Method;
  36 import java.lang.reflect.Constructor;
  37 import java.lang.reflect.Modifier;
  38 import java.lang.reflect.Type;
  39 import java.lang.reflect.TypeVariable;
  40 import java.lang.reflect.InvocationTargetException;
  41 import java.lang.reflect.AnnotatedType;
  42 import java.lang.ref.SoftReference;
  43 import java.io.InputStream;
  44 import java.io.ObjectStreamField;
  45 import java.security.AccessController;
  46 import java.security.PrivilegedAction;
  47 import java.util.ArrayList;
  48 import java.util.Arrays;
  49 import java.util.Collection;
  50 import java.util.HashSet;
  51 import java.util.List;
  52 import java.util.Set;
  53 import java.util.Map;
  54 import java.util.HashMap;
  55 import java.util.Objects;
  56 import sun.misc.Unsafe;
  57 import sun.reflect.CallerSensitive;
  58 import sun.reflect.ConstantPool;
  59 import sun.reflect.Reflection;
  60 import sun.reflect.ReflectionFactory;
  61 import sun.reflect.generics.factory.CoreReflectionFactory;
  62 import sun.reflect.generics.factory.GenericsFactory;
  63 import sun.reflect.generics.repository.ClassRepository;
  64 import sun.reflect.generics.repository.MethodRepository;
  65 import sun.reflect.generics.repository.ConstructorRepository;
  66 import sun.reflect.generics.scope.ClassScope;
  67 import sun.security.util.SecurityConstants;
  68 import java.lang.annotation.Annotation;
  69 import java.lang.reflect.Proxy;
  70 import sun.reflect.annotation.*;
  71 import sun.reflect.misc.ReflectUtil;
  72 
  73 /**
  74  * Instances of the class {@code Class} represent classes and
  75  * interfaces in a running Java application.  An enum is a kind of
  76  * class and an annotation is a kind of interface.  Every array also
  77  * belongs to a class that is reflected as a {@code Class} object
  78  * that is shared by all arrays with the same element type and number
  79  * of dimensions.  The primitive Java types ({@code boolean},
  80  * {@code byte}, {@code char}, {@code short},
  81  * {@code int}, {@code long}, {@code float}, and
  82  * {@code double}), and the keyword {@code void} are also
  83  * represented as {@code Class} objects.
  84  *
  85  * <p> {@code Class} has no public constructor. Instead {@code Class}
  86  * objects are constructed automatically by the Java Virtual Machine as classes
  87  * are loaded and by calls to the {@code defineClass} method in the class
  88  * loader.
  89  *
  90  * <p> The following example uses a {@code Class} object to print the
  91  * class name of an object:
  92  *
  93  * <p> <blockquote><pre>
  94  *     void printClassName(Object obj) {
  95  *         System.out.println("The class of " + obj +
  96  *                            " is " + obj.getClass().getName());
  97  *     }
  98  * </pre></blockquote>
  99  *
 100  * <p> It is also possible to get the {@code Class} object for a named
 101  * type (or for void) using a class literal.  See Section 15.8.2 of
 102  * <cite>The Java&trade; Language Specification</cite>.
 103  * For example:
 104  *
 105  * <p> <blockquote>
 106  *     {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
 107  * </blockquote>
 108  *
 109  * @param <T> the type of the class modeled by this {@code Class}
 110  * object.  For example, the type of {@code String.class} is {@code
 111  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
 112  * unknown.
 113  *
 114  * @author  unascribed
 115  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
 116  * @since   JDK1.0
 117  */
 118 public final class Class<T> implements java.io.Serializable,
 119                               GenericDeclaration,
 120                               Type,
 121                               AnnotatedElement {
 122     private static final int ANNOTATION= 0x00002000;
 123     private static final int ENUM      = 0x00004000;
 124     private static final int SYNTHETIC = 0x00001000;
 125 
 126     private static native void registerNatives();
 127     static {
 128         registerNatives();
 129     }
 130 
 131     /*
 132      * Constructor. Only the Java Virtual Machine creates Class
 133      * objects.
 134      */
 135     private Class() {}
 136 
 137 
 138     /**
 139      * Converts the object to a string. The string representation is the
 140      * string "class" or "interface", followed by a space, and then by the
 141      * fully qualified name of the class in the format returned by
 142      * {@code getName}.  If this {@code Class} object represents a
 143      * primitive type, this method returns the name of the primitive type.  If
 144      * this {@code Class} object represents void this method returns
 145      * "void".
 146      *
 147      * @return a string representation of this class object.
 148      */
 149     public String toString() {
 150         return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
 151             + getName();
 152     }
 153 
 154     /**
 155      * Returns a string describing this {@code Class}, including
 156      * information about modifiers and type parameters.
 157      *
 158      * The string is formatted as a list of type modifiers, if any,
 159      * followed by the kind of type (empty string for primitive types
 160      * and {@code class}, {@code enum}, {@code interface}, or
 161      * <code>&#64;</code>{@code interface}, as appropriate), followed
 162      * by the type's name, followed by an angle-bracketed
 163      * comma-separated list of the type's type parameters, if any.
 164      *
 165      * A space is used to separate modifiers from one another and to
 166      * separate any modifiers from the kind of type. The modifiers
 167      * occur in canonical order. If there are no type parameters, the
 168      * type parameter list is elided.
 169      *
 170      * <p>Note that since information about the runtime representation
 171      * of a type is being generated, modifiers not present on the
 172      * originating source code or illegal on the originating source
 173      * code may be present.
 174      *
 175      * @return a string describing this {@code Class}, including
 176      * information about modifiers and type parameters
 177      *
 178      * @since 1.8
 179      */
 180     public String toGenericString() {
 181         if (isPrimitive()) {
 182             return toString();
 183         } else {
 184             StringBuilder sb = new StringBuilder();
 185 
 186             // Class modifiers are a superset of interface modifiers
 187             int modifiers = getModifiers() & Modifier.classModifiers();
 188             if (modifiers != 0) {
 189                 sb.append(Modifier.toString(modifiers));
 190                 sb.append(' ');
 191             }
 192 
 193             if (isAnnotation()) {
 194                 sb.append('@');
 195             }
 196             if (isInterface()) { // Note: all annotation types are interfaces
 197                 sb.append("interface");
 198             } else {
 199                 if (isEnum())
 200                     sb.append("enum");
 201                 else
 202                     sb.append("class");
 203             }
 204             sb.append(' ');
 205             sb.append(getName());
 206 
 207             TypeVariable<?>[] typeparms = getTypeParameters();
 208             if (typeparms.length > 0) {
 209                 boolean first = true;
 210                 sb.append('<');
 211                 for(TypeVariable<?> typeparm: typeparms) {
 212                     if (!first)
 213                         sb.append(',');
 214                     sb.append(typeparm.getTypeName());
 215                     first = false;
 216                 }
 217                 sb.append('>');
 218             }
 219 
 220             return sb.toString();
 221         }
 222     }
 223 
 224     /**
 225      * Returns the {@code Class} object associated with the class or
 226      * interface with the given string name.  Invoking this method is
 227      * equivalent to:
 228      *
 229      * <blockquote>
 230      *  {@code Class.forName(className, true, currentLoader)}
 231      * </blockquote>
 232      *
 233      * where {@code currentLoader} denotes the defining class loader of
 234      * the current class.
 235      *
 236      * <p> For example, the following code fragment returns the
 237      * runtime {@code Class} descriptor for the class named
 238      * {@code java.lang.Thread}:
 239      *
 240      * <blockquote>
 241      *   {@code Class t = Class.forName("java.lang.Thread")}
 242      * </blockquote>
 243      * <p>
 244      * A call to {@code forName("X")} causes the class named
 245      * {@code X} to be initialized.
 246      *
 247      * @param      className   the fully qualified name of the desired class.
 248      * @return     the {@code Class} object for the class with the
 249      *             specified name.
 250      * @exception LinkageError if the linkage fails
 251      * @exception ExceptionInInitializerError if the initialization provoked
 252      *            by this method fails
 253      * @exception ClassNotFoundException if the class cannot be located
 254      */
 255     @CallerSensitive
 256     public static Class<?> forName(String className)
 257                 throws ClassNotFoundException {
 258         return forName0(className, true,
 259                         ClassLoader.getClassLoader(Reflection.getCallerClass()));
 260     }
 261 
 262 
 263     /**
 264      * Returns the {@code Class} object associated with the class or
 265      * interface with the given string name, using the given class loader.
 266      * Given the fully qualified name for a class or interface (in the same
 267      * format returned by {@code getName}) this method attempts to
 268      * locate, load, and link the class or interface.  The specified class
 269      * loader is used to load the class or interface.  If the parameter
 270      * {@code loader} is null, the class is loaded through the bootstrap
 271      * class loader.  The class is initialized only if the
 272      * {@code initialize} parameter is {@code true} and if it has
 273      * not been initialized earlier.
 274      *
 275      * <p> If {@code name} denotes a primitive type or void, an attempt
 276      * will be made to locate a user-defined class in the unnamed package whose
 277      * name is {@code name}. Therefore, this method cannot be used to
 278      * obtain any of the {@code Class} objects representing primitive
 279      * types or void.
 280      *
 281      * <p> If {@code name} denotes an array class, the component type of
 282      * the array class is loaded but not initialized.
 283      *
 284      * <p> For example, in an instance method the expression:
 285      *
 286      * <blockquote>
 287      *  {@code Class.forName("Foo")}
 288      * </blockquote>
 289      *
 290      * is equivalent to:
 291      *
 292      * <blockquote>
 293      *  {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
 294      * </blockquote>
 295      *
 296      * Note that this method throws errors related to loading, linking or
 297      * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
 298      * Java Language Specification</em>.
 299      * Note that this method does not check whether the requested class
 300      * is accessible to its caller.
 301      *
 302      * <p> If the {@code loader} is {@code null}, and a security
 303      * manager is present, and the caller's class loader is not null, then this
 304      * method calls the security manager's {@code checkPermission} method
 305      * with a {@code RuntimePermission("getClassLoader")} permission to
 306      * ensure it's ok to access the bootstrap class loader.
 307      *
 308      * @param name       fully qualified name of the desired class
 309      * @param initialize if {@code true} the class will be initialized.
 310      *                   See Section 12.4 of <em>The Java Language Specification</em>.
 311      * @param loader     class loader from which the class must be loaded
 312      * @return           class object representing the desired class
 313      *
 314      * @exception LinkageError if the linkage fails
 315      * @exception ExceptionInInitializerError if the initialization provoked
 316      *            by this method fails
 317      * @exception ClassNotFoundException if the class cannot be located by
 318      *            the specified class loader
 319      *
 320      * @see       java.lang.Class#forName(String)
 321      * @see       java.lang.ClassLoader
 322      * @since     1.2
 323      */
 324     @CallerSensitive
 325     public static Class<?> forName(String name, boolean initialize,
 326                                    ClassLoader loader)
 327         throws ClassNotFoundException
 328     {
 329         if (sun.misc.VM.isSystemDomainLoader(loader)) {
 330             SecurityManager sm = System.getSecurityManager();
 331             if (sm != null) {
 332                 ClassLoader ccl = ClassLoader.getClassLoader(Reflection.getCallerClass());
 333                 if (!sun.misc.VM.isSystemDomainLoader(ccl)) {
 334                     sm.checkPermission(
 335                         SecurityConstants.GET_CLASSLOADER_PERMISSION);
 336                 }
 337             }
 338         }
 339         return forName0(name, initialize, loader);
 340     }
 341 
 342     /** Called after security checks have been made. */
 343     private static native Class<?> forName0(String name, boolean initialize,
 344                                             ClassLoader loader)
 345         throws ClassNotFoundException;
 346 
 347     /**
 348      * Creates a new instance of the class represented by this {@code Class}
 349      * object.  The class is instantiated as if by a {@code new}
 350      * expression with an empty argument list.  The class is initialized if it
 351      * has not already been initialized.
 352      *
 353      * <p>Note that this method propagates any exception thrown by the
 354      * nullary constructor, including a checked exception.  Use of
 355      * this method effectively bypasses the compile-time exception
 356      * checking that would otherwise be performed by the compiler.
 357      * The {@link
 358      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
 359      * Constructor.newInstance} method avoids this problem by wrapping
 360      * any exception thrown by the constructor in a (checked) {@link
 361      * java.lang.reflect.InvocationTargetException}.
 362      *
 363      * @return  a newly allocated instance of the class represented by this
 364      *          object.
 365      * @throws  IllegalAccessException  if the class or its nullary
 366      *          constructor is not accessible.
 367      * @throws  InstantiationException
 368      *          if this {@code Class} represents an abstract class,
 369      *          an interface, an array class, a primitive type, or void;
 370      *          or if the class has no nullary constructor;
 371      *          or if the instantiation fails for some other reason.
 372      * @throws  ExceptionInInitializerError if the initialization
 373      *          provoked by this method fails.
 374      * @throws  SecurityException
 375      *          If a security manager, <i>s</i>, is present and
 376      *          the caller's class loader is not the same as or an
 377      *          ancestor of the class loader for the current class and
 378      *          invocation of {@link SecurityManager#checkPackageAccess
 379      *          s.checkPackageAccess()} denies access to the package
 380      *          of this class.
 381      */
 382     @CallerSensitive
 383     public T newInstance()
 384         throws InstantiationException, IllegalAccessException
 385     {
 386         if (System.getSecurityManager() != null) {
 387             checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
 388         }
 389 
 390         // NOTE: the following code may not be strictly correct under
 391         // the current Java memory model.
 392 
 393         // Constructor lookup
 394         if (cachedConstructor == null) {
 395             if (this == Class.class) {
 396                 throw new IllegalAccessException(
 397                     "Can not call newInstance() on the Class for java.lang.Class"
 398                 );
 399             }
 400             try {
 401                 Class<?>[] empty = {};
 402                 final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
 403                 // Disable accessibility checks on the constructor
 404                 // since we have to do the security check here anyway
 405                 // (the stack depth is wrong for the Constructor's
 406                 // security check to work)
 407                 java.security.AccessController.doPrivileged(
 408                     new java.security.PrivilegedAction<Void>() {
 409                         public Void run() {
 410                                 c.setAccessible(true);
 411                                 return null;
 412                             }
 413                         });
 414                 cachedConstructor = c;
 415             } catch (NoSuchMethodException e) {
 416                 throw (InstantiationException)
 417                     new InstantiationException(getName()).initCause(e);
 418             }
 419         }
 420         Constructor<T> tmpConstructor = cachedConstructor;
 421         // Security check (same as in java.lang.reflect.Constructor)
 422         int modifiers = tmpConstructor.getModifiers();
 423         if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
 424             Class<?> caller = Reflection.getCallerClass();
 425             if (newInstanceCallerCache != caller) {
 426                 Reflection.ensureMemberAccess(caller, this, null, modifiers);
 427                 newInstanceCallerCache = caller;
 428             }
 429         }
 430         // Run constructor
 431         try {
 432             return tmpConstructor.newInstance((Object[])null);
 433         } catch (InvocationTargetException e) {
 434             Unsafe.getUnsafe().throwException(e.getTargetException());
 435             // Not reached
 436             return null;
 437         }
 438     }
 439     private volatile transient Constructor<T> cachedConstructor;
 440     private volatile transient Class<?>       newInstanceCallerCache;
 441 
 442 
 443     /**
 444      * Determines if the specified {@code Object} is assignment-compatible
 445      * with the object represented by this {@code Class}.  This method is
 446      * the dynamic equivalent of the Java language {@code instanceof}
 447      * operator. The method returns {@code true} if the specified
 448      * {@code Object} argument is non-null and can be cast to the
 449      * reference type represented by this {@code Class} object without
 450      * raising a {@code ClassCastException.} It returns {@code false}
 451      * otherwise.
 452      *
 453      * <p> Specifically, if this {@code Class} object represents a
 454      * declared class, this method returns {@code true} if the specified
 455      * {@code Object} argument is an instance of the represented class (or
 456      * of any of its subclasses); it returns {@code false} otherwise. If
 457      * this {@code Class} object represents an array class, this method
 458      * returns {@code true} if the specified {@code Object} argument
 459      * can be converted to an object of the array class by an identity
 460      * conversion or by a widening reference conversion; it returns
 461      * {@code false} otherwise. If this {@code Class} object
 462      * represents an interface, this method returns {@code true} if the
 463      * class or any superclass of the specified {@code Object} argument
 464      * implements this interface; it returns {@code false} otherwise. If
 465      * this {@code Class} object represents a primitive type, this method
 466      * returns {@code false}.
 467      *
 468      * @param   obj the object to check
 469      * @return  true if {@code obj} is an instance of this class
 470      *
 471      * @since JDK1.1
 472      */
 473     public native boolean isInstance(Object obj);
 474 
 475 
 476     /**
 477      * Determines if the class or interface represented by this
 478      * {@code Class} object is either the same as, or is a superclass or
 479      * superinterface of, the class or interface represented by the specified
 480      * {@code Class} parameter. It returns {@code true} if so;
 481      * otherwise it returns {@code false}. If this {@code Class}
 482      * object represents a primitive type, this method returns
 483      * {@code true} if the specified {@code Class} parameter is
 484      * exactly this {@code Class} object; otherwise it returns
 485      * {@code false}.
 486      *
 487      * <p> Specifically, this method tests whether the type represented by the
 488      * specified {@code Class} parameter can be converted to the type
 489      * represented by this {@code Class} object via an identity conversion
 490      * or via a widening reference conversion. See <em>The Java Language
 491      * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
 492      *
 493      * @param cls the {@code Class} object to be checked
 494      * @return the {@code boolean} value indicating whether objects of the
 495      * type {@code cls} can be assigned to objects of this class
 496      * @exception NullPointerException if the specified Class parameter is
 497      *            null.
 498      * @since JDK1.1
 499      */
 500     public native boolean isAssignableFrom(Class<?> cls);
 501 
 502 
 503     /**
 504      * Determines if the specified {@code Class} object represents an
 505      * interface type.
 506      *
 507      * @return  {@code true} if this object represents an interface;
 508      *          {@code false} otherwise.
 509      */
 510     public native boolean isInterface();
 511 
 512 
 513     /**
 514      * Determines if this {@code Class} object represents an array class.
 515      *
 516      * @return  {@code true} if this object represents an array class;
 517      *          {@code false} otherwise.
 518      * @since   JDK1.1
 519      */
 520     public native boolean isArray();
 521 
 522 
 523     /**
 524      * Determines if the specified {@code Class} object represents a
 525      * primitive type.
 526      *
 527      * <p> There are nine predefined {@code Class} objects to represent
 528      * the eight primitive types and void.  These are created by the Java
 529      * Virtual Machine, and have the same names as the primitive types that
 530      * they represent, namely {@code boolean}, {@code byte},
 531      * {@code char}, {@code short}, {@code int},
 532      * {@code long}, {@code float}, and {@code double}.
 533      *
 534      * <p> These objects may only be accessed via the following public static
 535      * final variables, and are the only {@code Class} objects for which
 536      * this method returns {@code true}.
 537      *
 538      * @return true if and only if this class represents a primitive type
 539      *
 540      * @see     java.lang.Boolean#TYPE
 541      * @see     java.lang.Character#TYPE
 542      * @see     java.lang.Byte#TYPE
 543      * @see     java.lang.Short#TYPE
 544      * @see     java.lang.Integer#TYPE
 545      * @see     java.lang.Long#TYPE
 546      * @see     java.lang.Float#TYPE
 547      * @see     java.lang.Double#TYPE
 548      * @see     java.lang.Void#TYPE
 549      * @since JDK1.1
 550      */
 551     public native boolean isPrimitive();
 552 
 553     /**
 554      * Returns true if this {@code Class} object represents an annotation
 555      * type.  Note that if this method returns true, {@link #isInterface()}
 556      * would also return true, as all annotation types are also interfaces.
 557      *
 558      * @return {@code true} if this class object represents an annotation
 559      *      type; {@code false} otherwise
 560      * @since 1.5
 561      */
 562     public boolean isAnnotation() {
 563         return (getModifiers() & ANNOTATION) != 0;
 564     }
 565 
 566     /**
 567      * Returns {@code true} if this class is a synthetic class;
 568      * returns {@code false} otherwise.
 569      * @return {@code true} if and only if this class is a synthetic class as
 570      *         defined by the Java Language Specification.
 571      * @jls 13.1 The Form of a Binary
 572      * @since 1.5
 573      */
 574     public boolean isSynthetic() {
 575         return (getModifiers() & SYNTHETIC) != 0;
 576     }
 577 
 578     /**
 579      * Returns the  name of the entity (class, interface, array class,
 580      * primitive type, or void) represented by this {@code Class} object,
 581      * as a {@code String}.
 582      *
 583      * <p> If this class object represents a reference type that is not an
 584      * array type then the binary name of the class is returned, as specified
 585      * by
 586      * <cite>The Java&trade; Language Specification</cite>.
 587      *
 588      * <p> If this class object represents a primitive type or void, then the
 589      * name returned is a {@code String} equal to the Java language
 590      * keyword corresponding to the primitive type or void.
 591      *
 592      * <p> If this class object represents a class of arrays, then the internal
 593      * form of the name consists of the name of the element type preceded by
 594      * one or more '{@code [}' characters representing the depth of the array
 595      * nesting.  The encoding of element type names is as follows:
 596      *
 597      * <blockquote><table summary="Element types and encodings">
 598      * <tr><th> Element Type <th> &nbsp;&nbsp;&nbsp; <th> Encoding
 599      * <tr><td> boolean      <td> &nbsp;&nbsp;&nbsp; <td align=center> Z
 600      * <tr><td> byte         <td> &nbsp;&nbsp;&nbsp; <td align=center> B
 601      * <tr><td> char         <td> &nbsp;&nbsp;&nbsp; <td align=center> C
 602      * <tr><td> class or interface
 603      *                       <td> &nbsp;&nbsp;&nbsp; <td align=center> L<i>classname</i>;
 604      * <tr><td> double       <td> &nbsp;&nbsp;&nbsp; <td align=center> D
 605      * <tr><td> float        <td> &nbsp;&nbsp;&nbsp; <td align=center> F
 606      * <tr><td> int          <td> &nbsp;&nbsp;&nbsp; <td align=center> I
 607      * <tr><td> long         <td> &nbsp;&nbsp;&nbsp; <td align=center> J
 608      * <tr><td> short        <td> &nbsp;&nbsp;&nbsp; <td align=center> S
 609      * </table></blockquote>
 610      *
 611      * <p> The class or interface name <i>classname</i> is the binary name of
 612      * the class specified above.
 613      *
 614      * <p> Examples:
 615      * <blockquote><pre>
 616      * String.class.getName()
 617      *     returns "java.lang.String"
 618      * byte.class.getName()
 619      *     returns "byte"
 620      * (new Object[3]).getClass().getName()
 621      *     returns "[Ljava.lang.Object;"
 622      * (new int[3][4][5][6][7][8][9]).getClass().getName()
 623      *     returns "[[[[[[[I"
 624      * </pre></blockquote>
 625      *
 626      * @return  the name of the class or interface
 627      *          represented by this object.
 628      */
 629     public String getName() {
 630         String name = this.name;
 631         if (name == null)
 632             this.name = name = getName0();
 633         return name;
 634     }
 635 
 636     // cache the name to reduce the number of calls into the VM
 637     private transient String name;
 638     private native String getName0();
 639 
 640     /**
 641      * Returns the class loader for the class.  Some implementations may use
 642      * null to represent the bootstrap class loader. This method will return
 643      * null in such implementations if this class was loaded by the bootstrap
 644      * class loader.
 645      *
 646      * <p> If a security manager is present, and the caller's class loader is
 647      * not null and the caller's class loader is not the same as or an ancestor of
 648      * the class loader for the class whose class loader is requested, then
 649      * this method calls the security manager's {@code checkPermission}
 650      * method with a {@code RuntimePermission("getClassLoader")}
 651      * permission to ensure it's ok to access the class loader for the class.
 652      *
 653      * <p>If this object
 654      * represents a primitive type or void, null is returned.
 655      *
 656      * @return  the class loader that loaded the class or interface
 657      *          represented by this object.
 658      * @throws SecurityException
 659      *    if a security manager exists and its
 660      *    {@code checkPermission} method denies
 661      *    access to the class loader for the class.
 662      * @see java.lang.ClassLoader
 663      * @see SecurityManager#checkPermission
 664      * @see java.lang.RuntimePermission
 665      */
 666     @CallerSensitive
 667     public ClassLoader getClassLoader() {
 668         ClassLoader cl = getClassLoader0();
 669         if (cl == null)
 670             return null;
 671         SecurityManager sm = System.getSecurityManager();
 672         if (sm != null) {
 673             ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass());
 674         }
 675         return cl;
 676     }
 677 
 678     // Package-private to allow ClassLoader access
 679     native ClassLoader getClassLoader0();
 680 
 681 
 682     /**
 683      * Returns an array of {@code TypeVariable} objects that represent the
 684      * type variables declared by the generic declaration represented by this
 685      * {@code GenericDeclaration} object, in declaration order.  Returns an
 686      * array of length 0 if the underlying generic declaration declares no type
 687      * variables.
 688      *
 689      * @return an array of {@code TypeVariable} objects that represent
 690      *     the type variables declared by this generic declaration
 691      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
 692      *     signature of this generic declaration does not conform to
 693      *     the format specified in
 694      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 695      * @since 1.5
 696      */
 697     @SuppressWarnings("unchecked")
 698     public TypeVariable<Class<T>>[] getTypeParameters() {
 699         ClassRepository info = getGenericInfo();
 700         if (info != null)
 701             return (TypeVariable<Class<T>>[])info.getTypeParameters();
 702         else
 703             return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];
 704     }
 705 
 706 
 707     /**
 708      * Returns the {@code Class} representing the superclass of the entity
 709      * (class, interface, primitive type or void) represented by this
 710      * {@code Class}.  If this {@code Class} represents either the
 711      * {@code Object} class, an interface, a primitive type, or void, then
 712      * null is returned.  If this object represents an array class then the
 713      * {@code Class} object representing the {@code Object} class is
 714      * returned.
 715      *
 716      * @return the superclass of the class represented by this object.
 717      */
 718     public native Class<? super T> getSuperclass();
 719 
 720 
 721     /**
 722      * Returns the {@code Type} representing the direct superclass of
 723      * the entity (class, interface, primitive type or void) represented by
 724      * this {@code Class}.
 725      *
 726      * <p>If the superclass is a parameterized type, the {@code Type}
 727      * object returned must accurately reflect the actual type
 728      * parameters used in the source code. The parameterized type
 729      * representing the superclass is created if it had not been
 730      * created before. See the declaration of {@link
 731      * java.lang.reflect.ParameterizedType ParameterizedType} for the
 732      * semantics of the creation process for parameterized types.  If
 733      * this {@code Class} represents either the {@code Object}
 734      * class, an interface, a primitive type, or void, then null is
 735      * returned.  If this object represents an array class then the
 736      * {@code Class} object representing the {@code Object} class is
 737      * returned.
 738      *
 739      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
 740      *     class signature does not conform to the format specified in
 741      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 742      * @throws TypeNotPresentException if the generic superclass
 743      *     refers to a non-existent type declaration
 744      * @throws java.lang.reflect.MalformedParameterizedTypeException if the
 745      *     generic superclass refers to a parameterized type that cannot be
 746      *     instantiated  for any reason
 747      * @return the superclass of the class represented by this object
 748      * @since 1.5
 749      */
 750     public Type getGenericSuperclass() {
 751         ClassRepository info = getGenericInfo();
 752         if (info == null) {
 753             return getSuperclass();
 754         }
 755 
 756         // Historical irregularity:
 757         // Generic signature marks interfaces with superclass = Object
 758         // but this API returns null for interfaces
 759         if (isInterface()) {
 760             return null;
 761         }
 762 
 763         return info.getSuperclass();
 764     }
 765 
 766     /**
 767      * Gets the package for this class.  The class loader of this class is used
 768      * to find the package.  If the class was loaded by the bootstrap class
 769      * loader the set of packages loaded from CLASSPATH is searched to find the
 770      * package of the class. Null is returned if no package object was created
 771      * by the class loader of this class.
 772      *
 773      * <p> Packages have attributes for versions and specifications only if the
 774      * information was defined in the manifests that accompany the classes, and
 775      * if the class loader created the package instance with the attributes
 776      * from the manifest.
 777      *
 778      * @return the package of the class, or null if no package
 779      *         information is available from the archive or codebase.
 780      */
 781     public Package getPackage() {
 782         return Package.getPackage(this);
 783     }
 784 
 785 
 786     /**
 787      * Determines the interfaces implemented by the class or interface
 788      * represented by this object.
 789      *
 790      * <p> If this object represents a class, the return value is an array
 791      * containing objects representing all interfaces implemented by the
 792      * class. The order of the interface objects in the array corresponds to
 793      * the order of the interface names in the {@code implements} clause
 794      * of the declaration of the class represented by this object. For
 795      * example, given the declaration:
 796      * <blockquote>
 797      * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
 798      * </blockquote>
 799      * suppose the value of {@code s} is an instance of
 800      * {@code Shimmer}; the value of the expression:
 801      * <blockquote>
 802      * {@code s.getClass().getInterfaces()[0]}
 803      * </blockquote>
 804      * is the {@code Class} object that represents interface
 805      * {@code FloorWax}; and the value of:
 806      * <blockquote>
 807      * {@code s.getClass().getInterfaces()[1]}
 808      * </blockquote>
 809      * is the {@code Class} object that represents interface
 810      * {@code DessertTopping}.
 811      *
 812      * <p> If this object represents an interface, the array contains objects
 813      * representing all interfaces extended by the interface. The order of the
 814      * interface objects in the array corresponds to the order of the interface
 815      * names in the {@code extends} clause of the declaration of the
 816      * interface represented by this object.
 817      *
 818      * <p> If this object represents a class or interface that implements no
 819      * interfaces, the method returns an array of length 0.
 820      *
 821      * <p> If this object represents a primitive type or void, the method
 822      * returns an array of length 0.
 823      *
 824      * @return an array of interfaces implemented by this class.
 825      */
 826     public Class<?>[] getInterfaces() {
 827         ReflectionData<T> rd = reflectionData();
 828         if (rd == null) {
 829             // no cloning required
 830             return getInterfaces0();
 831         } else {
 832             Class<?>[] interfaces = rd.interfaces;
 833             if (interfaces == null) {
 834                 interfaces = getInterfaces0();
 835                 rd.interfaces = interfaces;
 836             }
 837             // defensively copy before handing over to user code
 838             return interfaces.clone();
 839         }
 840     }
 841 
 842     private native Class<?>[] getInterfaces0();
 843 
 844     /**
 845      * Returns the {@code Type}s representing the interfaces
 846      * directly implemented by the class or interface represented by
 847      * this object.
 848      *
 849      * <p>If a superinterface is a parameterized type, the
 850      * {@code Type} object returned for it must accurately reflect
 851      * the actual type parameters used in the source code. The
 852      * parameterized type representing each superinterface is created
 853      * if it had not been created before. See the declaration of
 854      * {@link java.lang.reflect.ParameterizedType ParameterizedType}
 855      * for the semantics of the creation process for parameterized
 856      * types.
 857      *
 858      * <p> If this object represents a class, the return value is an
 859      * array containing objects representing all interfaces
 860      * implemented by the class. The order of the interface objects in
 861      * the array corresponds to the order of the interface names in
 862      * the {@code implements} clause of the declaration of the class
 863      * represented by this object.  In the case of an array class, the
 864      * interfaces {@code Cloneable} and {@code Serializable} are
 865      * returned in that order.
 866      *
 867      * <p>If this object represents an interface, the array contains
 868      * objects representing all interfaces directly extended by the
 869      * interface.  The order of the interface objects in the array
 870      * corresponds to the order of the interface names in the
 871      * {@code extends} clause of the declaration of the interface
 872      * represented by this object.
 873      *
 874      * <p>If this object represents a class or interface that
 875      * implements no interfaces, the method returns an array of length
 876      * 0.
 877      *
 878      * <p>If this object represents a primitive type or void, the
 879      * method returns an array of length 0.
 880      *
 881      * @throws java.lang.reflect.GenericSignatureFormatError
 882      *     if the generic class signature does not conform to the format
 883      *     specified in
 884      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 885      * @throws TypeNotPresentException if any of the generic
 886      *     superinterfaces refers to a non-existent type declaration
 887      * @throws java.lang.reflect.MalformedParameterizedTypeException
 888      *     if any of the generic superinterfaces refer to a parameterized
 889      *     type that cannot be instantiated for any reason
 890      * @return an array of interfaces implemented by this class
 891      * @since 1.5
 892      */
 893     public Type[] getGenericInterfaces() {
 894         ClassRepository info = getGenericInfo();
 895         return (info == null) ?  getInterfaces() : info.getSuperInterfaces();
 896     }
 897 
 898 
 899     /**
 900      * Returns the {@code Class} representing the component type of an
 901      * array.  If this class does not represent an array class this method
 902      * returns null.
 903      *
 904      * @return the {@code Class} representing the component type of this
 905      * class if this class is an array
 906      * @see     java.lang.reflect.Array
 907      * @since JDK1.1
 908      */
 909     public native Class<?> getComponentType();
 910 
 911 
 912     /**
 913      * Returns the Java language modifiers for this class or interface, encoded
 914      * in an integer. The modifiers consist of the Java Virtual Machine's
 915      * constants for {@code public}, {@code protected},
 916      * {@code private}, {@code final}, {@code static},
 917      * {@code abstract} and {@code interface}; they should be decoded
 918      * using the methods of class {@code Modifier}.
 919      *
 920      * <p> If the underlying class is an array class, then its
 921      * {@code public}, {@code private} and {@code protected}
 922      * modifiers are the same as those of its component type.  If this
 923      * {@code Class} represents a primitive type or void, its
 924      * {@code public} modifier is always {@code true}, and its
 925      * {@code protected} and {@code private} modifiers are always
 926      * {@code false}. If this object represents an array class, a
 927      * primitive type or void, then its {@code final} modifier is always
 928      * {@code true} and its interface modifier is always
 929      * {@code false}. The values of its other modifiers are not determined
 930      * by this specification.
 931      *
 932      * <p> The modifier encodings are defined in <em>The Java Virtual Machine
 933      * Specification</em>, table 4.1.
 934      *
 935      * @return the {@code int} representing the modifiers for this class
 936      * @see     java.lang.reflect.Modifier
 937      * @since JDK1.1
 938      */
 939     public native int getModifiers();
 940 
 941 
 942     /**
 943      * Gets the signers of this class.
 944      *
 945      * @return  the signers of this class, or null if there are no signers.  In
 946      *          particular, this method returns null if this object represents
 947      *          a primitive type or void.
 948      * @since   JDK1.1
 949      */
 950     public native Object[] getSigners();
 951 
 952 
 953     /**
 954      * Set the signers of this class.
 955      */
 956     native void setSigners(Object[] signers);
 957 
 958 
 959     /**
 960      * If this {@code Class} object represents a local or anonymous
 961      * class within a method, returns a {@link
 962      * java.lang.reflect.Method Method} object representing the
 963      * immediately enclosing method of the underlying class. Returns
 964      * {@code null} otherwise.
 965      *
 966      * In particular, this method returns {@code null} if the underlying
 967      * class is a local or anonymous class immediately enclosed by a type
 968      * declaration, instance initializer or static initializer.
 969      *
 970      * @return the immediately enclosing method of the underlying class, if
 971      *     that class is a local or anonymous class; otherwise {@code null}.
 972      *
 973      * @throws SecurityException
 974      *         If a security manager, <i>s</i>, is present and any of the
 975      *         following conditions is met:
 976      *
 977      *         <ul>
 978      *
 979      *         <li> the caller's class loader is not the same as the
 980      *         class loader of the enclosing class and invocation of
 981      *         {@link SecurityManager#checkPermission
 982      *         s.checkPermission} method with
 983      *         {@code RuntimePermission("accessDeclaredMembers")}
 984      *         denies access to the methods within the enclosing class
 985      *
 986      *         <li> the caller's class loader is not the same as or an
 987      *         ancestor of the class loader for the enclosing class and
 988      *         invocation of {@link SecurityManager#checkPackageAccess
 989      *         s.checkPackageAccess()} denies access to the package
 990      *         of the enclosing class
 991      *
 992      *         </ul>
 993      * @since 1.5
 994      */
 995     @CallerSensitive
 996     public Method getEnclosingMethod() throws SecurityException {
 997         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
 998 
 999         if (enclosingInfo == null)
1000             return null;
1001         else {
1002             if (!enclosingInfo.isMethod())
1003                 return null;
1004 
1005             MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
1006                                                               getFactory());
1007             Class<?>   returnType       = toClass(typeInfo.getReturnType());
1008             Type []    parameterTypes   = typeInfo.getParameterTypes();
1009             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1010 
1011             // Convert Types to Classes; returned types *should*
1012             // be class objects since the methodDescriptor's used
1013             // don't have generics information
1014             for(int i = 0; i < parameterClasses.length; i++)
1015                 parameterClasses[i] = toClass(parameterTypes[i]);
1016 
1017             // Perform access check
1018             Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1019             enclosingCandidate.checkMemberAccess(Member.DECLARED,
1020                                                  Reflection.getCallerClass(), true);
1021             /*
1022              * Loop over all declared methods; match method name,
1023              * number of and type of parameters, *and* return
1024              * type.  Matching return type is also necessary
1025              * because of covariant returns, etc.
1026              */
1027             for(Method m: enclosingCandidate.getDeclaredMethods()) {
1028                 if (m.getName().equals(enclosingInfo.getName()) ) {
1029                     Class<?>[] candidateParamClasses = m.getParameterTypes();
1030                     if (candidateParamClasses.length == parameterClasses.length) {
1031                         boolean matches = true;
1032                         for(int i = 0; i < candidateParamClasses.length; i++) {
1033                             if (!candidateParamClasses[i].equals(parameterClasses[i])) {
1034                                 matches = false;
1035                                 break;
1036                             }
1037                         }
1038 
1039                         if (matches) { // finally, check return type
1040                             if (m.getReturnType().equals(returnType) )
1041                                 return m;
1042                         }
1043                     }
1044                 }
1045             }
1046 
1047             throw new InternalError("Enclosing method not found");
1048         }
1049     }
1050 
1051     private native Object[] getEnclosingMethod0();
1052 
1053     private EnclosingMethodInfo getEnclosingMethodInfo() {
1054         Object[] enclosingInfo = getEnclosingMethod0();
1055         if (enclosingInfo == null)
1056             return null;
1057         else {
1058             return new EnclosingMethodInfo(enclosingInfo);
1059         }
1060     }
1061 
1062     private final static class EnclosingMethodInfo {
1063         private Class<?> enclosingClass;
1064         private String name;
1065         private String descriptor;
1066 
1067         private EnclosingMethodInfo(Object[] enclosingInfo) {
1068             if (enclosingInfo.length != 3)
1069                 throw new InternalError("Malformed enclosing method information");
1070             try {
1071                 // The array is expected to have three elements:
1072 
1073                 // the immediately enclosing class
1074                 enclosingClass = (Class<?>) enclosingInfo[0];
1075                 assert(enclosingClass != null);
1076 
1077                 // the immediately enclosing method or constructor's
1078                 // name (can be null).
1079                 name            = (String)   enclosingInfo[1];
1080 
1081                 // the immediately enclosing method or constructor's
1082                 // descriptor (null iff name is).
1083                 descriptor      = (String)   enclosingInfo[2];
1084                 assert((name != null && descriptor != null) || name == descriptor);
1085             } catch (ClassCastException cce) {
1086                 throw new InternalError("Invalid type in enclosing method information", cce);
1087             }
1088         }
1089 
1090         boolean isPartial() {
1091             return enclosingClass == null || name == null || descriptor == null;
1092         }
1093 
1094         boolean isConstructor() { return !isPartial() && "<init>".equals(name); }
1095 
1096         boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }
1097 
1098         Class<?> getEnclosingClass() { return enclosingClass; }
1099 
1100         String getName() { return name; }
1101 
1102         String getDescriptor() { return descriptor; }
1103 
1104     }
1105 
1106     private static Class<?> toClass(Type o) {
1107         if (o instanceof GenericArrayType)
1108             return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
1109                                      0)
1110                 .getClass();
1111         return (Class<?>)o;
1112      }
1113 
1114     /**
1115      * If this {@code Class} object represents a local or anonymous
1116      * class within a constructor, returns a {@link
1117      * java.lang.reflect.Constructor Constructor} object representing
1118      * the immediately enclosing constructor of the underlying
1119      * class. Returns {@code null} otherwise.  In particular, this
1120      * method returns {@code null} if the underlying class is a local
1121      * or anonymous class immediately enclosed by a type declaration,
1122      * instance initializer or static initializer.
1123      *
1124      * @return the immediately enclosing constructor of the underlying class, if
1125      *     that class is a local or anonymous class; otherwise {@code null}.
1126      * @throws SecurityException
1127      *         If a security manager, <i>s</i>, is present and any of the
1128      *         following conditions is met:
1129      *
1130      *         <ul>
1131      *
1132      *         <li> the caller's class loader is not the same as the
1133      *         class loader of the enclosing class and invocation of
1134      *         {@link SecurityManager#checkPermission
1135      *         s.checkPermission} method with
1136      *         {@code RuntimePermission("accessDeclaredMembers")}
1137      *         denies access to the constructors within the enclosing class
1138      *
1139      *         <li> the caller's class loader is not the same as or an
1140      *         ancestor of the class loader for the enclosing class and
1141      *         invocation of {@link SecurityManager#checkPackageAccess
1142      *         s.checkPackageAccess()} denies access to the package
1143      *         of the enclosing class
1144      *
1145      *         </ul>
1146      * @since 1.5
1147      */
1148     @CallerSensitive
1149     public Constructor<?> getEnclosingConstructor() throws SecurityException {
1150         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1151 
1152         if (enclosingInfo == null)
1153             return null;
1154         else {
1155             if (!enclosingInfo.isConstructor())
1156                 return null;
1157 
1158             ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
1159                                                                         getFactory());
1160             Type []    parameterTypes   = typeInfo.getParameterTypes();
1161             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1162 
1163             // Convert Types to Classes; returned types *should*
1164             // be class objects since the methodDescriptor's used
1165             // don't have generics information
1166             for(int i = 0; i < parameterClasses.length; i++)
1167                 parameterClasses[i] = toClass(parameterTypes[i]);
1168 
1169             // Perform access check
1170             Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1171             enclosingCandidate.checkMemberAccess(Member.DECLARED,
1172                                                  Reflection.getCallerClass(), true);
1173             /*
1174              * Loop over all declared constructors; match number
1175              * of and type of parameters.
1176              */
1177             for(Constructor<?> c: enclosingCandidate.getDeclaredConstructors()) {
1178                 Class<?>[] candidateParamClasses = c.getParameterTypes();
1179                 if (candidateParamClasses.length == parameterClasses.length) {
1180                     boolean matches = true;
1181                     for(int i = 0; i < candidateParamClasses.length; i++) {
1182                         if (!candidateParamClasses[i].equals(parameterClasses[i])) {
1183                             matches = false;
1184                             break;
1185                         }
1186                     }
1187 
1188                     if (matches)
1189                         return c;
1190                 }
1191             }
1192 
1193             throw new InternalError("Enclosing constructor not found");
1194         }
1195     }
1196 
1197 
1198     /**
1199      * If the class or interface represented by this {@code Class} object
1200      * is a member of another class, returns the {@code Class} object
1201      * representing the class in which it was declared.  This method returns
1202      * null if this class or interface is not a member of any other class.  If
1203      * this {@code Class} object represents an array class, a primitive
1204      * type, or void,then this method returns null.
1205      *
1206      * @return the declaring class for this class
1207      * @since JDK1.1
1208      */
1209     public native Class<?> getDeclaringClass();
1210 
1211 
1212     /**
1213      * Returns the immediately enclosing class of the underlying
1214      * class.  If the underlying class is a top level class this
1215      * method returns {@code null}.
1216      * @return the immediately enclosing class of the underlying class
1217      * @exception  SecurityException
1218      *             If a security manager, <i>s</i>, is present and the caller's
1219      *             class loader is not the same as or an ancestor of the class
1220      *             loader for the enclosing class and invocation of {@link
1221      *             SecurityManager#checkPackageAccess s.checkPackageAccess()}
1222      *             denies access to the package of the enclosing class
1223      * @since 1.5
1224      */
1225     @CallerSensitive
1226     public Class<?> getEnclosingClass() throws SecurityException {
1227         // There are five kinds of classes (or interfaces):
1228         // a) Top level classes
1229         // b) Nested classes (static member classes)
1230         // c) Inner classes (non-static member classes)
1231         // d) Local classes (named classes declared within a method)
1232         // e) Anonymous classes
1233 
1234 
1235         // JVM Spec 4.8.6: A class must have an EnclosingMethod
1236         // attribute if and only if it is a local class or an
1237         // anonymous class.
1238         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1239         Class<?> enclosingCandidate;
1240 
1241         if (enclosingInfo == null) {
1242             // This is a top level or a nested class or an inner class (a, b, or c)
1243             enclosingCandidate = getDeclaringClass();
1244         } else {
1245             Class<?> enclosingClass = enclosingInfo.getEnclosingClass();
1246             // This is a local class or an anonymous class (d or e)
1247             if (enclosingClass == this || enclosingClass == null)
1248                 throw new InternalError("Malformed enclosing method information");
1249             else
1250                 enclosingCandidate = enclosingClass;
1251         }
1252 
1253         if (enclosingCandidate != null)
1254             enclosingCandidate.checkPackageAccess(
1255                     ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
1256         return enclosingCandidate;
1257     }
1258 
1259     /**
1260      * Returns the simple name of the underlying class as given in the
1261      * source code. Returns an empty string if the underlying class is
1262      * anonymous.
1263      *
1264      * <p>The simple name of an array is the simple name of the
1265      * component type with "[]" appended.  In particular the simple
1266      * name of an array whose component type is anonymous is "[]".
1267      *
1268      * @return the simple name of the underlying class
1269      * @since 1.5
1270      */
1271     public String getSimpleName() {
1272         if (isArray())
1273             return getComponentType().getSimpleName()+"[]";
1274 
1275         String simpleName = getSimpleBinaryName();
1276         if (simpleName == null) { // top level class
1277             simpleName = getName();
1278             return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
1279         }
1280         // According to JLS3 "Binary Compatibility" (13.1) the binary
1281         // name of non-package classes (not top level) is the binary
1282         // name of the immediately enclosing class followed by a '$' followed by:
1283         // (for nested and inner classes): the simple name.
1284         // (for local classes): 1 or more digits followed by the simple name.
1285         // (for anonymous classes): 1 or more digits.
1286 
1287         // Since getSimpleBinaryName() will strip the binary name of
1288         // the immediatly enclosing class, we are now looking at a
1289         // string that matches the regular expression "\$[0-9]*"
1290         // followed by a simple name (considering the simple of an
1291         // anonymous class to be the empty string).
1292 
1293         // Remove leading "\$[0-9]*" from the name
1294         int length = simpleName.length();
1295         if (length < 1 || simpleName.charAt(0) != '$')
1296             throw new InternalError("Malformed class name");
1297         int index = 1;
1298         while (index < length && isAsciiDigit(simpleName.charAt(index)))
1299             index++;
1300         // Eventually, this is the empty string iff this is an anonymous class
1301         return simpleName.substring(index);
1302     }
1303 
1304     /**
1305      * Return an informative string for the name of this type.
1306      *
1307      * @return an informative string for the name of this type
1308      * @since 1.8
1309      */
1310     public String getTypeName() {
1311         if (isArray()) {
1312             try {
1313                 Class<?> cl = this;
1314                 int dimensions = 0;
1315                 while (cl.isArray()) {
1316                     dimensions++;
1317                     cl = cl.getComponentType();
1318                 }
1319                 StringBuilder sb = new StringBuilder();
1320                 sb.append(cl.getName());
1321                 for (int i = 0; i < dimensions; i++) {
1322                     sb.append("[]");
1323                 }
1324                 return sb.toString();
1325             } catch (Throwable e) { /*FALLTHRU*/ }
1326         }
1327         return getName();
1328     }
1329 
1330     /**
1331      * Character.isDigit answers {@code true} to some non-ascii
1332      * digits.  This one does not.
1333      */
1334     private static boolean isAsciiDigit(char c) {
1335         return '0' <= c && c <= '9';
1336     }
1337 
1338     /**
1339      * Returns the canonical name of the underlying class as
1340      * defined by the Java Language Specification.  Returns null if
1341      * the underlying class does not have a canonical name (i.e., if
1342      * it is a local or anonymous class or an array whose component
1343      * type does not have a canonical name).
1344      * @return the canonical name of the underlying class if it exists, and
1345      * {@code null} otherwise.
1346      * @since 1.5
1347      */
1348     public String getCanonicalName() {
1349         if (isArray()) {
1350             String canonicalName = getComponentType().getCanonicalName();
1351             if (canonicalName != null)
1352                 return canonicalName + "[]";
1353             else
1354                 return null;
1355         }
1356         if (isLocalOrAnonymousClass())
1357             return null;
1358         Class<?> enclosingClass = getEnclosingClass();
1359         if (enclosingClass == null) { // top level class
1360             return getName();
1361         } else {
1362             String enclosingName = enclosingClass.getCanonicalName();
1363             if (enclosingName == null)
1364                 return null;
1365             return enclosingName + "." + getSimpleName();
1366         }
1367     }
1368 
1369     /**
1370      * Returns {@code true} if and only if the underlying class
1371      * is an anonymous class.
1372      *
1373      * @return {@code true} if and only if this class is an anonymous class.
1374      * @since 1.5
1375      */
1376     public boolean isAnonymousClass() {
1377         return "".equals(getSimpleName());
1378     }
1379 
1380     /**
1381      * Returns {@code true} if and only if the underlying class
1382      * is a local class.
1383      *
1384      * @return {@code true} if and only if this class is a local class.
1385      * @since 1.5
1386      */
1387     public boolean isLocalClass() {
1388         return isLocalOrAnonymousClass() && !isAnonymousClass();
1389     }
1390 
1391     /**
1392      * Returns {@code true} if and only if the underlying class
1393      * is a member class.
1394      *
1395      * @return {@code true} if and only if this class is a member class.
1396      * @since 1.5
1397      */
1398     public boolean isMemberClass() {
1399         return getSimpleBinaryName() != null && !isLocalOrAnonymousClass();
1400     }
1401 
1402     /**
1403      * Returns the "simple binary name" of the underlying class, i.e.,
1404      * the binary name without the leading enclosing class name.
1405      * Returns {@code null} if the underlying class is a top level
1406      * class.
1407      */
1408     private String getSimpleBinaryName() {
1409         Class<?> enclosingClass = getEnclosingClass();
1410         if (enclosingClass == null) // top level class
1411             return null;
1412         // Otherwise, strip the enclosing class' name
1413         try {
1414             return getName().substring(enclosingClass.getName().length());
1415         } catch (IndexOutOfBoundsException ex) {
1416             throw new InternalError("Malformed class name", ex);
1417         }
1418     }
1419 
1420     /**
1421      * Returns {@code true} if this is a local class or an anonymous
1422      * class.  Returns {@code false} otherwise.
1423      */
1424     private boolean isLocalOrAnonymousClass() {
1425         // JVM Spec 4.8.6: A class must have an EnclosingMethod
1426         // attribute if and only if it is a local class or an
1427         // anonymous class.
1428         return getEnclosingMethodInfo() != null;
1429     }
1430 
1431     /**
1432      * Returns an array containing {@code Class} objects representing all
1433      * the public classes and interfaces that are members of the class
1434      * represented by this {@code Class} object.  This includes public
1435      * class and interface members inherited from superclasses and public class
1436      * and interface members declared by the class.  This method returns an
1437      * array of length 0 if this {@code Class} object has no public member
1438      * classes or interfaces.  This method also returns an array of length 0 if
1439      * this {@code Class} object represents a primitive type, an array
1440      * class, or void.
1441      *
1442      * @return the array of {@code Class} objects representing the public
1443      *         members of this class
1444      * @throws SecurityException
1445      *         If a security manager, <i>s</i>, is present and
1446      *         the caller's class loader is not the same as or an
1447      *         ancestor of the class loader for the current class and
1448      *         invocation of {@link SecurityManager#checkPackageAccess
1449      *         s.checkPackageAccess()} denies access to the package
1450      *         of this class.
1451      *
1452      * @since JDK1.1
1453      */
1454     @CallerSensitive
1455     public Class<?>[] getClasses() {
1456         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
1457 
1458         // Privileged so this implementation can look at DECLARED classes,
1459         // something the caller might not have privilege to do.  The code here
1460         // is allowed to look at DECLARED classes because (1) it does not hand
1461         // out anything other than public members and (2) public member access
1462         // has already been ok'd by the SecurityManager.
1463 
1464         return java.security.AccessController.doPrivileged(
1465             new java.security.PrivilegedAction<Class<?>[]>() {
1466                 public Class<?>[] run() {
1467                     List<Class<?>> list = new ArrayList<>();
1468                     Class<?> currentClass = Class.this;
1469                     while (currentClass != null) {
1470                         Class<?>[] members = currentClass.getDeclaredClasses();
1471                         for (int i = 0; i < members.length; i++) {
1472                             if (Modifier.isPublic(members[i].getModifiers())) {
1473                                 list.add(members[i]);
1474                             }
1475                         }
1476                         currentClass = currentClass.getSuperclass();
1477                     }
1478                     return list.toArray(new Class<?>[0]);
1479                 }
1480             });
1481     }
1482 
1483 
1484     /**
1485      * Returns an array containing {@code Field} objects reflecting all
1486      * the accessible public fields of the class or interface represented by
1487      * this {@code Class} object.  The elements in the array returned are
1488      * not sorted and are not in any particular order.  This method returns an
1489      * array of length 0 if the class or interface has no accessible public
1490      * fields, or if it represents an array class, a primitive type, or void.
1491      *
1492      * <p> Specifically, if this {@code Class} object represents a class,
1493      * this method returns the public fields of this class and of all its
1494      * superclasses.  If this {@code Class} object represents an
1495      * interface, this method returns the fields of this interface and of all
1496      * its superinterfaces.
1497      *
1498      * <p> If this Class object represents an array type, then the returned array
1499      * does not contain a Field object for the 'length' field of the array
1500      * type.
1501      *
1502      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
1503      *
1504      * @return the array of {@code Field} objects representing the
1505      *         public fields
1506      * @throws SecurityException
1507      *         If a security manager, <i>s</i>, is present and
1508      *         the caller's class loader is not the same as or an
1509      *         ancestor of the class loader for the current class and
1510      *         invocation of {@link SecurityManager#checkPackageAccess
1511      *         s.checkPackageAccess()} denies access to the package
1512      *         of this class.
1513      *
1514      * @since JDK1.1
1515      */
1516     @CallerSensitive
1517     public Field[] getFields() throws SecurityException {
1518         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1519         return copyFields(privateGetPublicFields(null));
1520     }
1521 
1522 
1523     /**
1524      * Returns an array containing {@code Method} objects reflecting all
1525      * the public <em>member</em> methods of the class or interface represented
1526      * by this {@code Class} object, including those declared by the class
1527      * or interface and those inherited from superclasses and
1528      * superinterfaces.  Array classes return all the (public) member methods
1529      * inherited from the {@code Object} class.  The elements in the array
1530      * returned are not sorted and are not in any particular order.  This
1531      * method returns an array of length 0 if this {@code Class} object
1532      * represents a class or interface that has no public member methods, or if
1533      * this {@code Class} object represents a primitive type or void.
1534      *
1535      * <p> The class initialization method {@code <clinit>} is not
1536      * included in the returned array. If the class declares multiple public
1537      * member methods with the same parameter types, they are all included in
1538      * the returned array.
1539      *
1540      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
1541      *
1542      * @return the array of {@code Method} objects representing the
1543      *         public methods of this class
1544      * @throws SecurityException
1545      *         If a security manager, <i>s</i>, is present and
1546      *         the caller's class loader is not the same as or an
1547      *         ancestor of the class loader for the current class and
1548      *         invocation of {@link SecurityManager#checkPackageAccess
1549      *         s.checkPackageAccess()} denies access to the package
1550      *         of this class.
1551      *
1552      * @since JDK1.1
1553      */
1554     @CallerSensitive
1555     public Method[] getMethods() throws SecurityException {
1556         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1557         return copyMethods(privateGetPublicMethods());
1558     }
1559 
1560 
1561     /**
1562      * Returns an array containing {@code Constructor} objects reflecting
1563      * all the public constructors of the class represented by this
1564      * {@code Class} object.  An array of length 0 is returned if the
1565      * class has no public constructors, or if the class is an array class, or
1566      * if the class reflects a primitive type or void.
1567      *
1568      * Note that while this method returns an array of {@code
1569      * Constructor<T>} objects (that is an array of constructors from
1570      * this class), the return type of this method is {@code
1571      * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
1572      * might be expected.  This less informative return type is
1573      * necessary since after being returned from this method, the
1574      * array could be modified to hold {@code Constructor} objects for
1575      * different classes, which would violate the type guarantees of
1576      * {@code Constructor<T>[]}.
1577      *
1578      * @return the array of {@code Constructor} objects representing the
1579      *         public constructors of this class
1580      * @throws SecurityException
1581      *         If a security manager, <i>s</i>, is present and
1582      *         the caller's class loader is not the same as or an
1583      *         ancestor of the class loader for the current class and
1584      *         invocation of {@link SecurityManager#checkPackageAccess
1585      *         s.checkPackageAccess()} denies access to the package
1586      *         of this class.
1587      *
1588      * @since JDK1.1
1589      */
1590     @CallerSensitive
1591     public Constructor<?>[] getConstructors() throws SecurityException {
1592         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1593         return copyConstructors(privateGetDeclaredConstructors(true));
1594     }
1595 
1596 
1597     /**
1598      * Returns a {@code Field} object that reflects the specified public
1599      * member field of the class or interface represented by this
1600      * {@code Class} object. The {@code name} parameter is a
1601      * {@code String} specifying the simple name of the desired field.
1602      *
1603      * <p> The field to be reflected is determined by the algorithm that
1604      * follows.  Let C be the class or interface represented by this object:
1605      * <OL>
1606      * <LI> If C declares a public field with the name specified, that is the
1607      *      field to be reflected.</LI>
1608      * <LI> If no field was found in step 1 above, this algorithm is applied
1609      *      recursively to each direct superinterface of C. The direct
1610      *      superinterfaces are searched in the order they were declared.</LI>
1611      * <LI> If no field was found in steps 1 and 2 above, and C has a
1612      *      superclass S, then this algorithm is invoked recursively upon S.
1613      *      If C has no superclass, then a {@code NoSuchFieldException}
1614      *      is thrown.</LI>
1615      * </OL>
1616      *
1617      * <p> If this Class object represents an array type, then this method does
1618      * not find the 'length' field of the array type.
1619      *
1620      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
1621      *
1622      * @param name the field name
1623      * @return the {@code Field} object of this class specified by
1624      *         {@code name}
1625      * @throws NoSuchFieldException if a field with the specified name is
1626      *         not found.
1627      * @throws NullPointerException if {@code name} is {@code null}
1628      * @throws SecurityException
1629      *         If a security manager, <i>s</i>, is present and
1630      *         the caller's class loader is not the same as or an
1631      *         ancestor of the class loader for the current class and
1632      *         invocation of {@link SecurityManager#checkPackageAccess
1633      *         s.checkPackageAccess()} denies access to the package
1634      *         of this class.
1635      *
1636      * @since JDK1.1
1637      */
1638     @CallerSensitive
1639     public Field getField(String name)
1640         throws NoSuchFieldException, SecurityException {
1641         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1642         Field field = getField0(name);
1643         if (field == null) {
1644             throw new NoSuchFieldException(name);
1645         }
1646         return field;
1647     }
1648 
1649 
1650     /**
1651      * Returns a {@code Method} object that reflects the specified public
1652      * member method of the class or interface represented by this
1653      * {@code Class} object. The {@code name} parameter is a
1654      * {@code String} specifying the simple name of the desired method. The
1655      * {@code parameterTypes} parameter is an array of {@code Class}
1656      * objects that identify the method's formal parameter types, in declared
1657      * order. If {@code parameterTypes} is {@code null}, it is
1658      * treated as if it were an empty array.
1659      *
1660      * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
1661      * {@code NoSuchMethodException} is raised. Otherwise, the method to
1662      * be reflected is determined by the algorithm that follows.  Let C be the
1663      * class represented by this object:
1664      * <OL>
1665      * <LI> C is searched for any <I>matching methods</I>. If no matching
1666      *      method is found, the algorithm of step 1 is invoked recursively on
1667      *      the superclass of C.</LI>
1668      * <LI> If no method was found in step 1 above, the superinterfaces of C
1669      *      are searched for a matching method. If any such method is found, it
1670      *      is reflected.</LI>
1671      * </OL>
1672      *
1673      * To find a matching method in a class C:&nbsp; If C declares exactly one
1674      * public method with the specified name and exactly the same formal
1675      * parameter types, that is the method reflected. If more than one such
1676      * method is found in C, and one of these methods has a return type that is
1677      * more specific than any of the others, that method is reflected;
1678      * otherwise one of the methods is chosen arbitrarily.
1679      *
1680      * <p>Note that there may be more than one matching method in a
1681      * class because while the Java language forbids a class to
1682      * declare multiple methods with the same signature but different
1683      * return types, the Java virtual machine does not.  This
1684      * increased flexibility in the virtual machine can be used to
1685      * implement various language features.  For example, covariant
1686      * returns can be implemented with {@linkplain
1687      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
1688      * method and the method being overridden would have the same
1689      * signature but different return types.
1690      *
1691      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
1692      *
1693      * @param name the name of the method
1694      * @param parameterTypes the list of parameters
1695      * @return the {@code Method} object that matches the specified
1696      *         {@code name} and {@code parameterTypes}
1697      * @throws NoSuchMethodException if a matching method is not found
1698      *         or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
1699      * @throws NullPointerException if {@code name} is {@code null}
1700      * @throws SecurityException
1701      *         If a security manager, <i>s</i>, is present and
1702      *         the caller's class loader is not the same as or an
1703      *         ancestor of the class loader for the current class and
1704      *         invocation of {@link SecurityManager#checkPackageAccess
1705      *         s.checkPackageAccess()} denies access to the package
1706      *         of this class.
1707      *
1708      * @since JDK1.1
1709      */
1710     @CallerSensitive
1711     public Method getMethod(String name, Class<?>... parameterTypes)
1712         throws NoSuchMethodException, SecurityException {
1713         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1714         Method method = getMethod0(name, parameterTypes);
1715         if (method == null) {
1716             throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
1717         }
1718         return method;
1719     }
1720 
1721 
1722     /**
1723      * Returns a {@code Constructor} object that reflects the specified
1724      * public constructor of the class represented by this {@code Class}
1725      * object. The {@code parameterTypes} parameter is an array of
1726      * {@code Class} objects that identify the constructor's formal
1727      * parameter types, in declared order.
1728      *
1729      * If this {@code Class} object represents an inner class
1730      * declared in a non-static context, the formal parameter types
1731      * include the explicit enclosing instance as the first parameter.
1732      *
1733      * <p> The constructor to reflect is the public constructor of the class
1734      * represented by this {@code Class} object whose formal parameter
1735      * types match those specified by {@code parameterTypes}.
1736      *
1737      * @param parameterTypes the parameter array
1738      * @return the {@code Constructor} object of the public constructor that
1739      *         matches the specified {@code parameterTypes}
1740      * @throws NoSuchMethodException if a matching method is not found.
1741      * @throws SecurityException
1742      *         If a security manager, <i>s</i>, is present and
1743      *         the caller's class loader is not the same as or an
1744      *         ancestor of the class loader for the current class and
1745      *         invocation of {@link SecurityManager#checkPackageAccess
1746      *         s.checkPackageAccess()} denies access to the package
1747      *         of this class.
1748      *
1749      * @since JDK1.1
1750      */
1751     @CallerSensitive
1752     public Constructor<T> getConstructor(Class<?>... parameterTypes)
1753         throws NoSuchMethodException, SecurityException {
1754         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1755         return getConstructor0(parameterTypes, Member.PUBLIC);
1756     }
1757 
1758 
1759     /**
1760      * Returns an array of {@code Class} objects reflecting all the
1761      * classes and interfaces declared as members of the class represented by
1762      * this {@code Class} object. This includes public, protected, default
1763      * (package) access, and private classes and interfaces declared by the
1764      * class, but excludes inherited classes and interfaces.  This method
1765      * returns an array of length 0 if the class declares no classes or
1766      * interfaces as members, or if this {@code Class} object represents a
1767      * primitive type, an array class, or void.
1768      *
1769      * @return the array of {@code Class} objects representing all the
1770      *         declared members of this class
1771      * @throws SecurityException
1772      *         If a security manager, <i>s</i>, is present and any of the
1773      *         following conditions is met:
1774      *
1775      *         <ul>
1776      *
1777      *         <li> the caller's class loader is not the same as the
1778      *         class loader of this class and invocation of
1779      *         {@link SecurityManager#checkPermission
1780      *         s.checkPermission} method with
1781      *         {@code RuntimePermission("accessDeclaredMembers")}
1782      *         denies access to the declared classes within this class
1783      *
1784      *         <li> the caller's class loader is not the same as or an
1785      *         ancestor of the class loader for the current class and
1786      *         invocation of {@link SecurityManager#checkPackageAccess
1787      *         s.checkPackageAccess()} denies access to the package
1788      *         of this class
1789      *
1790      *         </ul>
1791      *
1792      * @since JDK1.1
1793      */
1794     @CallerSensitive
1795     public Class<?>[] getDeclaredClasses() throws SecurityException {
1796         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), false);
1797         return getDeclaredClasses0();
1798     }
1799 
1800 
1801     /**
1802      * Returns an array of {@code Field} objects reflecting all the fields
1803      * declared by the class or interface represented by this
1804      * {@code Class} object. This includes public, protected, default
1805      * (package) access, and private fields, but excludes inherited fields.
1806      * The elements in the array returned are not sorted and are not in any
1807      * particular order.  This method returns an array of length 0 if the class
1808      * or interface declares no fields, or if this {@code Class} object
1809      * represents a primitive type, an array class, or void.
1810      *
1811      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
1812      *
1813      * @return  the array of {@code Field} objects representing all the
1814      *          declared fields of this class
1815      * @throws  SecurityException
1816      *          If a security manager, <i>s</i>, is present and any of the
1817      *          following conditions is met:
1818      *
1819      *          <ul>
1820      *
1821      *          <li> the caller's class loader is not the same as the
1822      *          class loader of this class and invocation of
1823      *          {@link SecurityManager#checkPermission
1824      *          s.checkPermission} method with
1825      *          {@code RuntimePermission("accessDeclaredMembers")}
1826      *          denies access to the declared fields within this class
1827      *
1828      *          <li> the caller's class loader is not the same as or an
1829      *          ancestor of the class loader for the current class and
1830      *          invocation of {@link SecurityManager#checkPackageAccess
1831      *          s.checkPackageAccess()} denies access to the package
1832      *          of this class
1833      *
1834      *          </ul>
1835      *
1836      * @since JDK1.1
1837      */
1838     @CallerSensitive
1839     public Field[] getDeclaredFields() throws SecurityException {
1840         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
1841         return copyFields(privateGetDeclaredFields(false));
1842     }
1843 
1844 
1845     /**
1846      * Returns an array of {@code Method} objects reflecting all the
1847      * methods declared by the class or interface represented by this
1848      * {@code Class} object. This includes public, protected, default
1849      * (package) access, and private methods, but excludes inherited methods.
1850      * The elements in the array returned are not sorted and are not in any
1851      * particular order.  This method returns an array of length 0 if the class
1852      * or interface declares no methods, or if this {@code Class} object
1853      * represents a primitive type, an array class, or void.  The class
1854      * initialization method {@code <clinit>} is not included in the
1855      * returned array. If the class declares multiple public member methods
1856      * with the same parameter types, they are all included in the returned
1857      * array.
1858      *
1859      * <p> See <em>The Java Language Specification</em>, section 8.2.
1860      *
1861      * @return  the array of {@code Method} objects representing all the
1862      *          declared methods of this class
1863      * @throws  SecurityException
1864      *          If a security manager, <i>s</i>, is present and any of the
1865      *          following conditions is met:
1866      *
1867      *          <ul>
1868      *
1869      *          <li> the caller's class loader is not the same as the
1870      *          class loader of this class and invocation of
1871      *          {@link SecurityManager#checkPermission
1872      *          s.checkPermission} method with
1873      *          {@code RuntimePermission("accessDeclaredMembers")}
1874      *          denies access to the declared methods within this class
1875      *
1876      *          <li> the caller's class loader is not the same as or an
1877      *          ancestor of the class loader for the current class and
1878      *          invocation of {@link SecurityManager#checkPackageAccess
1879      *          s.checkPackageAccess()} denies access to the package
1880      *          of this class
1881      *
1882      *          </ul>
1883      *
1884      * @since JDK1.1
1885      */
1886     @CallerSensitive
1887     public Method[] getDeclaredMethods() throws SecurityException {
1888         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
1889         return copyMethods(privateGetDeclaredMethods(false));
1890     }
1891 
1892 
1893     /**
1894      * Returns an array of {@code Constructor} objects reflecting all the
1895      * constructors declared by the class represented by this
1896      * {@code Class} object. These are public, protected, default
1897      * (package) access, and private constructors.  The elements in the array
1898      * returned are not sorted and are not in any particular order.  If the
1899      * class has a default constructor, it is included in the returned array.
1900      * This method returns an array of length 0 if this {@code Class}
1901      * object represents an interface, a primitive type, an array class, or
1902      * void.
1903      *
1904      * <p> See <em>The Java Language Specification</em>, section 8.2.
1905      *
1906      * @return  the array of {@code Constructor} objects representing all the
1907      *          declared constructors of this class
1908      * @throws  SecurityException
1909      *          If a security manager, <i>s</i>, is present and any of the
1910      *          following conditions is met:
1911      *
1912      *          <ul>
1913      *
1914      *          <li> the caller's class loader is not the same as the
1915      *          class loader of this class and invocation of
1916      *          {@link SecurityManager#checkPermission
1917      *          s.checkPermission} method with
1918      *          {@code RuntimePermission("accessDeclaredMembers")}
1919      *          denies access to the declared constructors within this class
1920      *
1921      *          <li> the caller's class loader is not the same as or an
1922      *          ancestor of the class loader for the current class and
1923      *          invocation of {@link SecurityManager#checkPackageAccess
1924      *          s.checkPackageAccess()} denies access to the package
1925      *          of this class
1926      *
1927      *          </ul>
1928      *
1929      * @since JDK1.1
1930      */
1931     @CallerSensitive
1932     public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
1933         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
1934         return copyConstructors(privateGetDeclaredConstructors(false));
1935     }
1936 
1937 
1938     /**
1939      * Returns a {@code Field} object that reflects the specified declared
1940      * field of the class or interface represented by this {@code Class}
1941      * object. The {@code name} parameter is a {@code String} that
1942      * specifies the simple name of the desired field.  Note that this method
1943      * will not reflect the {@code length} field of an array class.
1944      *
1945      * @param name the name of the field
1946      * @return  the {@code Field} object for the specified field in this
1947      *          class
1948      * @throws  NoSuchFieldException if a field with the specified name is
1949      *          not found.
1950      * @throws  NullPointerException if {@code name} is {@code null}
1951      * @throws  SecurityException
1952      *          If a security manager, <i>s</i>, is present and any of the
1953      *          following conditions is met:
1954      *
1955      *          <ul>
1956      *
1957      *          <li> the caller's class loader is not the same as the
1958      *          class loader of this class and invocation of
1959      *          {@link SecurityManager#checkPermission
1960      *          s.checkPermission} method with
1961      *          {@code RuntimePermission("accessDeclaredMembers")}
1962      *          denies access to the declared field
1963      *
1964      *          <li> the caller's class loader is not the same as or an
1965      *          ancestor of the class loader for the current class and
1966      *          invocation of {@link SecurityManager#checkPackageAccess
1967      *          s.checkPackageAccess()} denies access to the package
1968      *          of this class
1969      *
1970      *          </ul>
1971      *
1972      * @since JDK1.1
1973      */
1974     @CallerSensitive
1975     public Field getDeclaredField(String name)
1976         throws NoSuchFieldException, SecurityException {
1977         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
1978         Field field = searchFields(privateGetDeclaredFields(false), name);
1979         if (field == null) {
1980             throw new NoSuchFieldException(name);
1981         }
1982         return field;
1983     }
1984 
1985 
1986     /**
1987      * Returns a {@code Method} object that reflects the specified
1988      * declared method of the class or interface represented by this
1989      * {@code Class} object. The {@code name} parameter is a
1990      * {@code String} that specifies the simple name of the desired
1991      * method, and the {@code parameterTypes} parameter is an array of
1992      * {@code Class} objects that identify the method's formal parameter
1993      * types, in declared order.  If more than one method with the same
1994      * parameter types is declared in a class, and one of these methods has a
1995      * return type that is more specific than any of the others, that method is
1996      * returned; otherwise one of the methods is chosen arbitrarily.  If the
1997      * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
1998      * is raised.
1999      *
2000      * @param name the name of the method
2001      * @param parameterTypes the parameter array
2002      * @return  the {@code Method} object for the method of this class
2003      *          matching the specified name and parameters
2004      * @throws  NoSuchMethodException if a matching method is not found.
2005      * @throws  NullPointerException if {@code name} is {@code null}
2006      * @throws  SecurityException
2007      *          If a security manager, <i>s</i>, is present and any of the
2008      *          following conditions is met:
2009      *
2010      *          <ul>
2011      *
2012      *          <li> the caller's class loader is not the same as the
2013      *          class loader of this class and invocation of
2014      *          {@link SecurityManager#checkPermission
2015      *          s.checkPermission} method with
2016      *          {@code RuntimePermission("accessDeclaredMembers")}
2017      *          denies access to the declared method
2018      *
2019      *          <li> the caller's class loader is not the same as or an
2020      *          ancestor of the class loader for the current class and
2021      *          invocation of {@link SecurityManager#checkPackageAccess
2022      *          s.checkPackageAccess()} denies access to the package
2023      *          of this class
2024      *
2025      *          </ul>
2026      *
2027      * @since JDK1.1
2028      */
2029     @CallerSensitive
2030     public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2031         throws NoSuchMethodException, SecurityException {
2032         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2033         Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
2034         if (method == null) {
2035             throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
2036         }
2037         return method;
2038     }
2039 
2040 
2041     /**
2042      * Returns a {@code Constructor} object that reflects the specified
2043      * constructor of the class or interface represented by this
2044      * {@code Class} object.  The {@code parameterTypes} parameter is
2045      * an array of {@code Class} objects that identify the constructor's
2046      * formal parameter types, in declared order.
2047      *
2048      * If this {@code Class} object represents an inner class
2049      * declared in a non-static context, the formal parameter types
2050      * include the explicit enclosing instance as the first parameter.
2051      *
2052      * @param parameterTypes the parameter array
2053      * @return  The {@code Constructor} object for the constructor with the
2054      *          specified parameter list
2055      * @throws  NoSuchMethodException if a matching method is not found.
2056      * @throws  SecurityException
2057      *          If a security manager, <i>s</i>, is present and any of the
2058      *          following conditions is met:
2059      *
2060      *          <ul>
2061      *
2062      *          <li> the caller's class loader is not the same as the
2063      *          class loader of this class and invocation of
2064      *          {@link SecurityManager#checkPermission
2065      *          s.checkPermission} method with
2066      *          {@code RuntimePermission("accessDeclaredMembers")}
2067      *          denies access to the declared constructor
2068      *
2069      *          <li> the caller's class loader is not the same as or an
2070      *          ancestor of the class loader for the current class and
2071      *          invocation of {@link SecurityManager#checkPackageAccess
2072      *          s.checkPackageAccess()} denies access to the package
2073      *          of this class
2074      *
2075      *          </ul>
2076      *
2077      * @since JDK1.1
2078      */
2079     @CallerSensitive
2080     public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
2081         throws NoSuchMethodException, SecurityException {
2082         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2083         return getConstructor0(parameterTypes, Member.DECLARED);
2084     }
2085 
2086     /**
2087      * Finds a resource with a given name.  The rules for searching resources
2088      * associated with a given class are implemented by the defining
2089      * {@linkplain ClassLoader class loader} of the class.  This method
2090      * delegates to this object's class loader.  If this object was loaded by
2091      * the bootstrap class loader, the method delegates to {@link
2092      * ClassLoader#getSystemResourceAsStream}.
2093      *
2094      * <p> Before delegation, an absolute resource name is constructed from the
2095      * given resource name using this algorithm:
2096      *
2097      * <ul>
2098      *
2099      * <li> If the {@code name} begins with a {@code '/'}
2100      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
2101      * portion of the {@code name} following the {@code '/'}.
2102      *
2103      * <li> Otherwise, the absolute name is of the following form:
2104      *
2105      * <blockquote>
2106      *   {@code modified_package_name/name}
2107      * </blockquote>
2108      *
2109      * <p> Where the {@code modified_package_name} is the package name of this
2110      * object with {@code '/'} substituted for {@code '.'}
2111      * (<tt>'&#92;u002e'</tt>).
2112      *
2113      * </ul>
2114      *
2115      * @param  name name of the desired resource
2116      * @return      A {@link java.io.InputStream} object or {@code null} if
2117      *              no resource with this name is found
2118      * @throws  NullPointerException If {@code name} is {@code null}
2119      * @since  JDK1.1
2120      */
2121      public InputStream getResourceAsStream(String name) {
2122         name = resolveName(name);
2123         ClassLoader cl = getClassLoader0();
2124         if (cl==null) {
2125             // A system class.
2126             return ClassLoader.getSystemResourceAsStream(name);
2127         }
2128         return cl.getResourceAsStream(name);
2129     }
2130 
2131     /**
2132      * Finds a resource with a given name.  The rules for searching resources
2133      * associated with a given class are implemented by the defining
2134      * {@linkplain ClassLoader class loader} of the class.  This method
2135      * delegates to this object's class loader.  If this object was loaded by
2136      * the bootstrap class loader, the method delegates to {@link
2137      * ClassLoader#getSystemResource}.
2138      *
2139      * <p> Before delegation, an absolute resource name is constructed from the
2140      * given resource name using this algorithm:
2141      *
2142      * <ul>
2143      *
2144      * <li> If the {@code name} begins with a {@code '/'}
2145      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
2146      * portion of the {@code name} following the {@code '/'}.
2147      *
2148      * <li> Otherwise, the absolute name is of the following form:
2149      *
2150      * <blockquote>
2151      *   {@code modified_package_name/name}
2152      * </blockquote>
2153      *
2154      * <p> Where the {@code modified_package_name} is the package name of this
2155      * object with {@code '/'} substituted for {@code '.'}
2156      * (<tt>'&#92;u002e'</tt>).
2157      *
2158      * </ul>
2159      *
2160      * @param  name name of the desired resource
2161      * @return      A  {@link java.net.URL} object or {@code null} if no
2162      *              resource with this name is found
2163      * @since  JDK1.1
2164      */
2165     public java.net.URL getResource(String name) {
2166         name = resolveName(name);
2167         ClassLoader cl = getClassLoader0();
2168         if (cl==null) {
2169             // A system class.
2170             return ClassLoader.getSystemResource(name);
2171         }
2172         return cl.getResource(name);
2173     }
2174 
2175 
2176 
2177     /** protection domain returned when the internal domain is null */
2178     private static java.security.ProtectionDomain allPermDomain;
2179 
2180 
2181     /**
2182      * Returns the {@code ProtectionDomain} of this class.  If there is a
2183      * security manager installed, this method first calls the security
2184      * manager's {@code checkPermission} method with a
2185      * {@code RuntimePermission("getProtectionDomain")} permission to
2186      * ensure it's ok to get the
2187      * {@code ProtectionDomain}.
2188      *
2189      * @return the ProtectionDomain of this class
2190      *
2191      * @throws SecurityException
2192      *        if a security manager exists and its
2193      *        {@code checkPermission} method doesn't allow
2194      *        getting the ProtectionDomain.
2195      *
2196      * @see java.security.ProtectionDomain
2197      * @see SecurityManager#checkPermission
2198      * @see java.lang.RuntimePermission
2199      * @since 1.2
2200      */
2201     public java.security.ProtectionDomain getProtectionDomain() {
2202         SecurityManager sm = System.getSecurityManager();
2203         if (sm != null) {
2204             sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
2205         }
2206         java.security.ProtectionDomain pd = getProtectionDomain0();
2207         if (pd == null) {
2208             if (allPermDomain == null) {
2209                 java.security.Permissions perms =
2210                     new java.security.Permissions();
2211                 perms.add(SecurityConstants.ALL_PERMISSION);
2212                 allPermDomain =
2213                     new java.security.ProtectionDomain(null, perms);
2214             }
2215             pd = allPermDomain;
2216         }
2217         return pd;
2218     }
2219 
2220 
2221     /**
2222      * Returns the ProtectionDomain of this class.
2223      */
2224     private native java.security.ProtectionDomain getProtectionDomain0();
2225 
2226     /*
2227      * Return the Virtual Machine's Class object for the named
2228      * primitive type.
2229      */
2230     static native Class<?> getPrimitiveClass(String name);
2231 
2232     /*
2233      * Check if client is allowed to access members.  If access is denied,
2234      * throw a SecurityException.
2235      *
2236      * This method also enforces package access.
2237      *
2238      * <p> Default policy: allow all clients access with normal Java access
2239      * control.
2240      */
2241     private void checkMemberAccess(int which, Class<?> caller, boolean checkProxyInterfaces) {
2242         final SecurityManager s = System.getSecurityManager();
2243         if (s != null) {
2244             /* Default policy allows access to all {@link Member#PUBLIC} members,
2245              * as well as access to classes that have the same class loader as the caller.
2246              * In all other cases, it requires RuntimePermission("accessDeclaredMembers")
2247              * permission.
2248              */
2249             final ClassLoader ccl = ClassLoader.getClassLoader(caller);
2250             final ClassLoader cl = getClassLoader0();
2251             if (which != Member.PUBLIC) {
2252                 if (ccl != cl) {
2253                     s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
2254                 }
2255             }
2256             this.checkPackageAccess(ccl, checkProxyInterfaces);
2257         }
2258     }
2259 
2260     /*
2261      * Checks if a client loaded in ClassLoader ccl is allowed to access this
2262      * class under the current package access policy. If access is denied,
2263      * throw a SecurityException.
2264      */
2265     private void checkPackageAccess(final ClassLoader ccl, boolean checkProxyInterfaces) {
2266         final SecurityManager s = System.getSecurityManager();
2267         if (s != null) {
2268             final ClassLoader cl = getClassLoader0();
2269 
2270             if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
2271                 String name = this.getName();
2272                 int i = name.lastIndexOf('.');
2273                 if (i != -1) {
2274                     // skip the package access check on a proxy class in default proxy package
2275                     String pkg = name.substring(0, i);
2276                     if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {
2277                         s.checkPackageAccess(pkg);
2278                     }
2279                 }
2280             }
2281             // check package access on the proxy interfaces
2282             if (checkProxyInterfaces && Proxy.isProxyClass(this)) {
2283                 ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());
2284             }
2285         }
2286     }
2287 
2288     /**
2289      * Add a package name prefix if the name is not absolute Remove leading "/"
2290      * if name is absolute
2291      */
2292     private String resolveName(String name) {
2293         if (name == null) {
2294             return name;
2295         }
2296         if (!name.startsWith("/")) {
2297             Class<?> c = this;
2298             while (c.isArray()) {
2299                 c = c.getComponentType();
2300             }
2301             String baseName = c.getName();
2302             int index = baseName.lastIndexOf('.');
2303             if (index != -1) {
2304                 name = baseName.substring(0, index).replace('.', '/')
2305                     +"/"+name;
2306             }
2307         } else {
2308             name = name.substring(1);
2309         }
2310         return name;
2311     }
2312 
2313     /**
2314      * Atomic operations support.
2315      */
2316     private static class Atomic {
2317         // initialize Unsafe machinery here, since we need to call Class.class instance method
2318         // and have to avoid calling it in the static initializer of the Class class...
2319         private static final Unsafe unsafe = Unsafe.getUnsafe();
2320         // offset of Class.reflectionData instance field
2321         private static final long reflectionDataOffset;
2322         // offset of Class.annotationType instance field
2323         private static final long annotationTypeOffset;
2324 
2325         static {
2326             Field[] fields = Class.class.getDeclaredFields0(false); // bypass caches
2327             reflectionDataOffset = objectFieldOffset(fields, "reflectionData");
2328             annotationTypeOffset = objectFieldOffset(fields, "annotationType");
2329         }
2330 
2331         private static long objectFieldOffset(Field[] fields, String fieldName) {
2332             Field field = searchFields(fields, fieldName);
2333             if (field == null) {
2334                 throw new Error("No " + fieldName + " field found in java.lang.Class");
2335             }
2336             return unsafe.objectFieldOffset(field);
2337         }
2338 
2339         static <T> boolean casReflectionData(Class<?> clazz,
2340                                              SoftReference<ReflectionData<T>> oldData,
2341                                              SoftReference<ReflectionData<T>> newData) {
2342             return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData);
2343         }
2344 
2345         static <T> boolean casAnnotationType(Class<?> clazz,
2346                                              AnnotationType oldType,
2347                                              AnnotationType newType) {
2348             return unsafe.compareAndSwapObject(clazz, annotationTypeOffset, oldType, newType);
2349         }
2350     }
2351 
2352     /**
2353      * Reflection support.
2354      */
2355 
2356     // Caches for certain reflective results
2357     private static boolean useCaches = true;
2358 
2359     // reflection data that might get invalidated when JVM TI RedefineClasses() is called
2360     static class ReflectionData<T> {
2361         volatile Field[] declaredFields;
2362         volatile Field[] publicFields;
2363         volatile Method[] declaredMethods;
2364         volatile Method[] publicMethods;
2365         volatile Constructor<T>[] declaredConstructors;
2366         volatile Constructor<T>[] publicConstructors;
2367         // Intermediate results for getFields and getMethods
2368         volatile Field[] declaredPublicFields;
2369         volatile Method[] declaredPublicMethods;
2370         volatile Class<?>[] interfaces;
2371 
2372         // Value of classRedefinedCount when we created this ReflectionData instance
2373         final int redefinedCount;
2374 
2375         ReflectionData(int redefinedCount) {
2376             this.redefinedCount = redefinedCount;
2377         }
2378     }
2379 
2380     private volatile transient SoftReference<ReflectionData<T>> reflectionData;
2381 
2382     // Incremented by the VM on each call to JVM TI RedefineClasses()
2383     // that redefines this class or a superclass.
2384     private volatile transient int classRedefinedCount = 0;
2385 
2386     // Lazily create and cache ReflectionData
2387     private ReflectionData<T> reflectionData() {
2388         SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
2389         int classRedefinedCount = this.classRedefinedCount;
2390         ReflectionData<T> rd;
2391         if (useCaches &&
2392             reflectionData != null &&
2393             (rd = reflectionData.get()) != null &&
2394             rd.redefinedCount == classRedefinedCount) {
2395             return rd;
2396         }
2397         // else no SoftReference or cleared SoftReference or stale ReflectionData
2398         // -> create and replace new instance
2399         return newReflectionData(reflectionData, classRedefinedCount);
2400     }
2401 
2402     private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
2403                                                 int classRedefinedCount) {
2404         if (!useCaches) return null;
2405 
2406         while (true) {
2407             ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
2408             // try to CAS it...
2409             if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
2410                 return rd;
2411             }
2412             // else retry
2413             oldReflectionData = this.reflectionData;
2414             classRedefinedCount = this.classRedefinedCount;
2415             if (oldReflectionData != null &&
2416                 (rd = oldReflectionData.get()) != null &&
2417                 rd.redefinedCount == classRedefinedCount) {
2418                 return rd;
2419             }
2420         }
2421     }
2422 
2423     // Generic signature handling
2424     private native String getGenericSignature0();
2425 
2426     // Generic info repository; lazily initialized
2427     private volatile transient ClassRepository genericInfo;
2428 
2429     // accessor for factory
2430     private GenericsFactory getFactory() {
2431         // create scope and factory
2432         return CoreReflectionFactory.make(this, ClassScope.make(this));
2433     }
2434 
2435     // accessor for generic info repository;
2436     // generic info is lazily initialized
2437     private ClassRepository getGenericInfo() {
2438         ClassRepository genericInfo = this.genericInfo;
2439         if (genericInfo == null) {
2440             String signature = getGenericSignature0();
2441             if (signature == null) {
2442                 genericInfo = ClassRepository.NONE;
2443             } else {
2444                 genericInfo = ClassRepository.make(signature, getFactory());
2445             }
2446             this.genericInfo = genericInfo;
2447         }
2448         return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
2449     }
2450 
2451     // Annotations handling
2452     native byte[] getRawAnnotations();
2453     // Since 1.8
2454     native byte[] getRawTypeAnnotations();
2455     static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
2456         return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
2457     }
2458 
2459     native ConstantPool getConstantPool();
2460 
2461     //
2462     //
2463     // java.lang.reflect.Field handling
2464     //
2465     //
2466 
2467     // Returns an array of "root" fields. These Field objects must NOT
2468     // be propagated to the outside world, but must instead be copied
2469     // via ReflectionFactory.copyField.
2470     private Field[] privateGetDeclaredFields(boolean publicOnly) {
2471         checkInitted();
2472         Field[] res;
2473         ReflectionData<T> rd = reflectionData();
2474         if (rd != null) {
2475             res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
2476             if (res != null) return res;
2477         }
2478         // No cached value available; request value from VM
2479         res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
2480         if (rd != null) {
2481             if (publicOnly) {
2482                 rd.declaredPublicFields = res;
2483             } else {
2484                 rd.declaredFields = res;
2485             }
2486         }
2487         return res;
2488     }
2489 
2490     // Returns an array of "root" fields. These Field objects must NOT
2491     // be propagated to the outside world, but must instead be copied
2492     // via ReflectionFactory.copyField.
2493     private Field[] privateGetPublicFields(Set<Class<?>> traversedInterfaces) {
2494         checkInitted();
2495         Field[] res;
2496         ReflectionData<T> rd = reflectionData();
2497         if (rd != null) {
2498             res = rd.publicFields;
2499             if (res != null) return res;
2500         }
2501 
2502         // No cached value available; compute value recursively.
2503         // Traverse in correct order for getField().
2504         List<Field> fields = new ArrayList<>();
2505         if (traversedInterfaces == null) {
2506             traversedInterfaces = new HashSet<>();
2507         }
2508 
2509         // Local fields
2510         Field[] tmp = privateGetDeclaredFields(true);
2511         addAll(fields, tmp);
2512 
2513         // Direct superinterfaces, recursively
2514         for (Class<?> c : getInterfaces()) {
2515             if (!traversedInterfaces.contains(c)) {
2516                 traversedInterfaces.add(c);
2517                 addAll(fields, c.privateGetPublicFields(traversedInterfaces));
2518             }
2519         }
2520 
2521         // Direct superclass, recursively
2522         if (!isInterface()) {
2523             Class<?> c = getSuperclass();
2524             if (c != null) {
2525                 addAll(fields, c.privateGetPublicFields(traversedInterfaces));
2526             }
2527         }
2528 
2529         res = new Field[fields.size()];
2530         fields.toArray(res);
2531         if (rd != null) {
2532             rd.publicFields = res;
2533         }
2534         return res;
2535     }
2536 
2537     private static void addAll(Collection<Field> c, Field[] o) {
2538         for (int i = 0; i < o.length; i++) {
2539             c.add(o[i]);
2540         }
2541     }
2542 
2543 
2544     //
2545     //
2546     // java.lang.reflect.Constructor handling
2547     //
2548     //
2549 
2550     // Returns an array of "root" constructors. These Constructor
2551     // objects must NOT be propagated to the outside world, but must
2552     // instead be copied via ReflectionFactory.copyConstructor.
2553     private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
2554         checkInitted();
2555         Constructor<T>[] res;
2556         ReflectionData<T> rd = reflectionData();
2557         if (rd != null) {
2558             res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
2559             if (res != null) return res;
2560         }
2561         // No cached value available; request value from VM
2562         if (isInterface()) {
2563             @SuppressWarnings("unchecked")
2564             Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
2565             res = temporaryRes;
2566         } else {
2567             res = getDeclaredConstructors0(publicOnly);
2568         }
2569         if (rd != null) {
2570             if (publicOnly) {
2571                 rd.publicConstructors = res;
2572             } else {
2573                 rd.declaredConstructors = res;
2574             }
2575         }
2576         return res;
2577     }
2578 
2579     //
2580     //
2581     // java.lang.reflect.Method handling
2582     //
2583     //
2584 
2585     // Returns an array of "root" methods. These Method objects must NOT
2586     // be propagated to the outside world, but must instead be copied
2587     // via ReflectionFactory.copyMethod.
2588     private Method[] privateGetDeclaredMethods(boolean publicOnly) {
2589         checkInitted();
2590         Method[] res;
2591         ReflectionData<T> rd = reflectionData();
2592         if (rd != null) {
2593             res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
2594             if (res != null) return res;
2595         }
2596         // No cached value available; request value from VM
2597         res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
2598         if (rd != null) {
2599             if (publicOnly) {
2600                 rd.declaredPublicMethods = res;
2601             } else {
2602                 rd.declaredMethods = res;
2603             }
2604         }
2605         return res;
2606     }
2607 
2608     static class MethodArray {
2609         private Method[] methods;
2610         private int length;
2611 
2612         MethodArray() {
2613             methods = new Method[20];
2614             length = 0;
2615         }
2616 
2617         void add(Method m) {
2618             if (length == methods.length) {
2619                 methods = Arrays.copyOf(methods, 2 * methods.length);
2620             }
2621             methods[length++] = m;
2622         }
2623 
2624         void addAll(Method[] ma) {
2625             for (int i = 0; i < ma.length; i++) {
2626                 add(ma[i]);
2627             }
2628         }
2629 
2630         void addAll(MethodArray ma) {
2631             for (int i = 0; i < ma.length(); i++) {
2632                 add(ma.get(i));
2633             }
2634         }
2635 
2636         void addIfNotPresent(Method newMethod) {
2637             for (int i = 0; i < length; i++) {
2638                 Method m = methods[i];
2639                 if (m == newMethod || (m != null && m.equals(newMethod))) {
2640                     return;
2641                 }
2642             }
2643             add(newMethod);
2644         }
2645 
2646         void addAllIfNotPresent(MethodArray newMethods) {
2647             for (int i = 0; i < newMethods.length(); i++) {
2648                 Method m = newMethods.get(i);
2649                 if (m != null) {
2650                     addIfNotPresent(m);
2651                 }
2652             }
2653         }
2654 
2655         int length() {
2656             return length;
2657         }
2658 
2659         Method get(int i) {
2660             return methods[i];
2661         }
2662 
2663         void removeByNameAndSignature(Method toRemove) {
2664             for (int i = 0; i < length; i++) {
2665                 Method m = methods[i];
2666                 if (m != null &&
2667                     m.getReturnType() == toRemove.getReturnType() &&
2668                     m.getName() == toRemove.getName() &&
2669                     arrayContentsEq(m.getParameterTypes(),
2670                                     toRemove.getParameterTypes())) {
2671                     methods[i] = null;
2672                 }
2673             }
2674         }
2675 
2676         void compactAndTrim() {
2677             int newPos = 0;
2678             // Get rid of null slots
2679             for (int pos = 0; pos < length; pos++) {
2680                 Method m = methods[pos];
2681                 if (m != null) {
2682                     if (pos != newPos) {
2683                         methods[newPos] = m;
2684                     }
2685                     newPos++;
2686                 }
2687             }
2688             if (newPos != methods.length) {
2689                 methods = Arrays.copyOf(methods, newPos);
2690             }
2691         }
2692 
2693         Method[] getArray() {
2694             return methods;
2695         }
2696     }
2697 
2698 
2699     // Returns an array of "root" methods. These Method objects must NOT
2700     // be propagated to the outside world, but must instead be copied
2701     // via ReflectionFactory.copyMethod.
2702     private Method[] privateGetPublicMethods() {
2703         checkInitted();
2704         Method[] res;
2705         ReflectionData<T> rd = reflectionData();
2706         if (rd != null) {
2707             res = rd.publicMethods;
2708             if (res != null) return res;
2709         }
2710 
2711         // No cached value available; compute value recursively.
2712         // Start by fetching public declared methods
2713         MethodArray methods = new MethodArray();
2714         {
2715             Method[] tmp = privateGetDeclaredMethods(true);
2716             methods.addAll(tmp);
2717         }
2718         // Now recur over superclass and direct superinterfaces.
2719         // Go over superinterfaces first so we can more easily filter
2720         // out concrete implementations inherited from superclasses at
2721         // the end.
2722         MethodArray inheritedMethods = new MethodArray();
2723         Class<?>[] interfaces = getInterfaces();
2724         for (int i = 0; i < interfaces.length; i++) {
2725             inheritedMethods.addAll(interfaces[i].privateGetPublicMethods());
2726         }
2727         if (!isInterface()) {
2728             Class<?> c = getSuperclass();
2729             if (c != null) {
2730                 MethodArray supers = new MethodArray();
2731                 supers.addAll(c.privateGetPublicMethods());
2732                 // Filter out concrete implementations of any
2733                 // interface methods
2734                 for (int i = 0; i < supers.length(); i++) {
2735                     Method m = supers.get(i);
2736                     if (m != null && !Modifier.isAbstract(m.getModifiers())) {
2737                         inheritedMethods.removeByNameAndSignature(m);
2738                     }
2739                 }
2740                 // Insert superclass's inherited methods before
2741                 // superinterfaces' to satisfy getMethod's search
2742                 // order
2743                 supers.addAll(inheritedMethods);
2744                 inheritedMethods = supers;
2745             }
2746         }
2747         // Filter out all local methods from inherited ones
2748         for (int i = 0; i < methods.length(); i++) {
2749             Method m = methods.get(i);
2750             inheritedMethods.removeByNameAndSignature(m);
2751         }
2752         methods.addAllIfNotPresent(inheritedMethods);
2753         methods.compactAndTrim();
2754         res = methods.getArray();
2755         if (rd != null) {
2756             rd.publicMethods = res;
2757         }
2758         return res;
2759     }
2760 
2761 
2762     //
2763     // Helpers for fetchers of one field, method, or constructor
2764     //
2765 
2766     private static Field searchFields(Field[] fields, String name) {
2767         String internedName = name.intern();
2768         for (int i = 0; i < fields.length; i++) {
2769             if (fields[i].getName() == internedName) {
2770                 return getReflectionFactory().copyField(fields[i]);
2771             }
2772         }
2773         return null;
2774     }
2775 
2776     private Field getField0(String name) throws NoSuchFieldException {
2777         // Note: the intent is that the search algorithm this routine
2778         // uses be equivalent to the ordering imposed by
2779         // privateGetPublicFields(). It fetches only the declared
2780         // public fields for each class, however, to reduce the number
2781         // of Field objects which have to be created for the common
2782         // case where the field being requested is declared in the
2783         // class which is being queried.
2784         Field res;
2785         // Search declared public fields
2786         if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
2787             return res;
2788         }
2789         // Direct superinterfaces, recursively
2790         Class<?>[] interfaces = getInterfaces();
2791         for (int i = 0; i < interfaces.length; i++) {
2792             Class<?> c = interfaces[i];
2793             if ((res = c.getField0(name)) != null) {
2794                 return res;
2795             }
2796         }
2797         // Direct superclass, recursively
2798         if (!isInterface()) {
2799             Class<?> c = getSuperclass();
2800             if (c != null) {
2801                 if ((res = c.getField0(name)) != null) {
2802                     return res;
2803                 }
2804             }
2805         }
2806         return null;
2807     }
2808 
2809     private static Method searchMethods(Method[] methods,
2810                                         String name,
2811                                         Class<?>[] parameterTypes)
2812     {
2813         Method res = null;
2814         String internedName = name.intern();
2815         for (int i = 0; i < methods.length; i++) {
2816             Method m = methods[i];
2817             if (m.getName() == internedName
2818                 && arrayContentsEq(parameterTypes, m.getParameterTypes())
2819                 && (res == null
2820                     || res.getReturnType().isAssignableFrom(m.getReturnType())))
2821                 res = m;
2822         }
2823 
2824         return (res == null ? res : getReflectionFactory().copyMethod(res));
2825     }
2826 
2827 
2828     private Method getMethod0(String name, Class<?>[] parameterTypes) {
2829         // Note: the intent is that the search algorithm this routine
2830         // uses be equivalent to the ordering imposed by
2831         // privateGetPublicMethods(). It fetches only the declared
2832         // public methods for each class, however, to reduce the
2833         // number of Method objects which have to be created for the
2834         // common case where the method being requested is declared in
2835         // the class which is being queried.
2836         Method res;
2837         // Search declared public methods
2838         if ((res = searchMethods(privateGetDeclaredMethods(true),
2839                                  name,
2840                                  parameterTypes)) != null) {
2841             return res;
2842         }
2843         // Search superclass's methods
2844         if (!isInterface()) {
2845             Class<? super T> c = getSuperclass();
2846             if (c != null) {
2847                 if ((res = c.getMethod0(name, parameterTypes)) != null) {
2848                     return res;
2849                 }
2850             }
2851         }
2852         // Search superinterfaces' methods
2853         Class<?>[] interfaces = getInterfaces();
2854         for (int i = 0; i < interfaces.length; i++) {
2855             Class<?> c = interfaces[i];
2856             if ((res = c.getMethod0(name, parameterTypes)) != null) {
2857                 return res;
2858             }
2859         }
2860         // Not found
2861         return null;
2862     }
2863 
2864     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
2865                                         int which) throws NoSuchMethodException
2866     {
2867         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
2868         for (Constructor<T> constructor : constructors) {
2869             if (arrayContentsEq(parameterTypes,
2870                                 constructor.getParameterTypes())) {
2871                 return getReflectionFactory().copyConstructor(constructor);
2872             }
2873         }
2874         throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
2875     }
2876 
2877     //
2878     // Other helpers and base implementation
2879     //
2880 
2881     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
2882         if (a1 == null) {
2883             return a2 == null || a2.length == 0;
2884         }
2885 
2886         if (a2 == null) {
2887             return a1.length == 0;
2888         }
2889 
2890         if (a1.length != a2.length) {
2891             return false;
2892         }
2893 
2894         for (int i = 0; i < a1.length; i++) {
2895             if (a1[i] != a2[i]) {
2896                 return false;
2897             }
2898         }
2899 
2900         return true;
2901     }
2902 
2903     private static Field[] copyFields(Field[] arg) {
2904         Field[] out = new Field[arg.length];
2905         ReflectionFactory fact = getReflectionFactory();
2906         for (int i = 0; i < arg.length; i++) {
2907             out[i] = fact.copyField(arg[i]);
2908         }
2909         return out;
2910     }
2911 
2912     private static Method[] copyMethods(Method[] arg) {
2913         Method[] out = new Method[arg.length];
2914         ReflectionFactory fact = getReflectionFactory();
2915         for (int i = 0; i < arg.length; i++) {
2916             out[i] = fact.copyMethod(arg[i]);
2917         }
2918         return out;
2919     }
2920 
2921     private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
2922         Constructor<U>[] out = arg.clone();
2923         ReflectionFactory fact = getReflectionFactory();
2924         for (int i = 0; i < out.length; i++) {
2925             out[i] = fact.copyConstructor(out[i]);
2926         }
2927         return out;
2928     }
2929 
2930     private native Field[]       getDeclaredFields0(boolean publicOnly);
2931     private native Method[]      getDeclaredMethods0(boolean publicOnly);
2932     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
2933     private native Class<?>[]   getDeclaredClasses0();
2934 
2935     private static String        argumentTypesToString(Class<?>[] argTypes) {
2936         StringBuilder buf = new StringBuilder();
2937         buf.append("(");
2938         if (argTypes != null) {
2939             for (int i = 0; i < argTypes.length; i++) {
2940                 if (i > 0) {
2941                     buf.append(", ");
2942                 }
2943                 Class<?> c = argTypes[i];
2944                 buf.append((c == null) ? "null" : c.getName());
2945             }
2946         }
2947         buf.append(")");
2948         return buf.toString();
2949     }
2950 
2951     /** use serialVersionUID from JDK 1.1 for interoperability */
2952     private static final long serialVersionUID = 3206093459760846163L;
2953 
2954 
2955     /**
2956      * Class Class is special cased within the Serialization Stream Protocol.
2957      *
2958      * A Class instance is written initially into an ObjectOutputStream in the
2959      * following format:
2960      * <pre>
2961      *      {@code TC_CLASS} ClassDescriptor
2962      *      A ClassDescriptor is a special cased serialization of
2963      *      a {@code java.io.ObjectStreamClass} instance.
2964      * </pre>
2965      * A new handle is generated for the initial time the class descriptor
2966      * is written into the stream. Future references to the class descriptor
2967      * are written as references to the initial class descriptor instance.
2968      *
2969      * @see java.io.ObjectStreamClass
2970      */
2971     private static final ObjectStreamField[] serialPersistentFields =
2972         new ObjectStreamField[0];
2973 
2974 
2975     /**
2976      * Returns the assertion status that would be assigned to this
2977      * class if it were to be initialized at the time this method is invoked.
2978      * If this class has had its assertion status set, the most recent
2979      * setting will be returned; otherwise, if any package default assertion
2980      * status pertains to this class, the most recent setting for the most
2981      * specific pertinent package default assertion status is returned;
2982      * otherwise, if this class is not a system class (i.e., it has a
2983      * class loader) its class loader's default assertion status is returned;
2984      * otherwise, the system class default assertion status is returned.
2985      * <p>
2986      * Few programmers will have any need for this method; it is provided
2987      * for the benefit of the JRE itself.  (It allows a class to determine at
2988      * the time that it is initialized whether assertions should be enabled.)
2989      * Note that this method is not guaranteed to return the actual
2990      * assertion status that was (or will be) associated with the specified
2991      * class when it was (or will be) initialized.
2992      *
2993      * @return the desired assertion status of the specified class.
2994      * @see    java.lang.ClassLoader#setClassAssertionStatus
2995      * @see    java.lang.ClassLoader#setPackageAssertionStatus
2996      * @see    java.lang.ClassLoader#setDefaultAssertionStatus
2997      * @since  1.4
2998      */
2999     public boolean desiredAssertionStatus() {
3000         ClassLoader loader = getClassLoader();
3001         // If the loader is null this is a system class, so ask the VM
3002         if (loader == null)
3003             return desiredAssertionStatus0(this);
3004 
3005         // If the classloader has been initialized with the assertion
3006         // directives, ask it. Otherwise, ask the VM.
3007         synchronized(loader.assertionLock) {
3008             if (loader.classAssertionStatus != null) {
3009                 return loader.desiredAssertionStatus(getName());
3010             }
3011         }
3012         return desiredAssertionStatus0(this);
3013     }
3014 
3015     // Retrieves the desired assertion status of this class from the VM
3016     private static native boolean desiredAssertionStatus0(Class<?> clazz);
3017 
3018     /**
3019      * Returns true if and only if this class was declared as an enum in the
3020      * source code.
3021      *
3022      * @return true if and only if this class was declared as an enum in the
3023      *     source code
3024      * @since 1.5
3025      */
3026     public boolean isEnum() {
3027         // An enum must both directly extend java.lang.Enum and have
3028         // the ENUM bit set; classes for specialized enum constants
3029         // don't do the former.
3030         return (this.getModifiers() & ENUM) != 0 &&
3031         this.getSuperclass() == java.lang.Enum.class;
3032     }
3033 
3034     // Fetches the factory for reflective objects
3035     private static ReflectionFactory getReflectionFactory() {
3036         if (reflectionFactory == null) {
3037             reflectionFactory =
3038                 java.security.AccessController.doPrivileged
3039                     (new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());
3040         }
3041         return reflectionFactory;
3042     }
3043     private static ReflectionFactory reflectionFactory;
3044 
3045     // To be able to query system properties as soon as they're available
3046     private static boolean initted = false;
3047     private static void checkInitted() {
3048         if (initted) return;
3049         AccessController.doPrivileged(new PrivilegedAction<Void>() {
3050                 public Void run() {
3051                     // Tests to ensure the system properties table is fully
3052                     // initialized. This is needed because reflection code is
3053                     // called very early in the initialization process (before
3054                     // command-line arguments have been parsed and therefore
3055                     // these user-settable properties installed.) We assume that
3056                     // if System.out is non-null then the System class has been
3057                     // fully initialized and that the bulk of the startup code
3058                     // has been run.
3059 
3060                     if (System.out == null) {
3061                         // java.lang.System not yet fully initialized
3062                         return null;
3063                     }
3064 
3065                     // Doesn't use Boolean.getBoolean to avoid class init.
3066                     String val =
3067                         System.getProperty("sun.reflect.noCaches");
3068                     if (val != null && val.equals("true")) {
3069                         useCaches = false;
3070                     }
3071 
3072                     initted = true;
3073                     return null;
3074                 }
3075             });
3076     }
3077 
3078     /**
3079      * Returns the elements of this enum class or null if this
3080      * Class object does not represent an enum type.
3081      *
3082      * @return an array containing the values comprising the enum class
3083      *     represented by this Class object in the order they're
3084      *     declared, or null if this Class object does not
3085      *     represent an enum type
3086      * @since 1.5
3087      */
3088     public T[] getEnumConstants() {
3089         T[] values = getEnumConstantsShared();
3090         return (values != null) ? values.clone() : null;
3091     }
3092 
3093     /**
3094      * Returns the elements of this enum class or null if this
3095      * Class object does not represent an enum type;
3096      * identical to getEnumConstants except that the result is
3097      * uncloned, cached, and shared by all callers.
3098      */
3099     T[] getEnumConstantsShared() {
3100         if (enumConstants == null) {
3101             if (!isEnum()) return null;
3102             try {
3103                 final Method values = getMethod("values");
3104                 java.security.AccessController.doPrivileged(
3105                     new java.security.PrivilegedAction<Void>() {
3106                         public Void run() {
3107                                 values.setAccessible(true);
3108                                 return null;
3109                             }
3110                         });
3111                 @SuppressWarnings("unchecked")
3112                 T[] temporaryConstants = (T[])values.invoke(null);
3113                 enumConstants = temporaryConstants;
3114             }
3115             // These can happen when users concoct enum-like classes
3116             // that don't comply with the enum spec.
3117             catch (InvocationTargetException | NoSuchMethodException |
3118                    IllegalAccessException ex) { return null; }
3119         }
3120         return enumConstants;
3121     }
3122     private volatile transient T[] enumConstants = null;
3123 
3124     /**
3125      * Returns a map from simple name to enum constant.  This package-private
3126      * method is used internally by Enum to implement
3127      * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}
3128      * efficiently.  Note that the map is returned by this method is
3129      * created lazily on first use.  Typically it won't ever get created.
3130      */
3131     Map<String, T> enumConstantDirectory() {
3132         if (enumConstantDirectory == null) {
3133             T[] universe = getEnumConstantsShared();
3134             if (universe == null)
3135                 throw new IllegalArgumentException(
3136                     getName() + " is not an enum type");
3137             Map<String, T> m = new HashMap<>(2 * universe.length);
3138             for (T constant : universe)
3139                 m.put(((Enum<?>)constant).name(), constant);
3140             enumConstantDirectory = m;
3141         }
3142         return enumConstantDirectory;
3143     }
3144     private volatile transient Map<String, T> enumConstantDirectory = null;
3145 
3146     /**
3147      * Casts an object to the class or interface represented
3148      * by this {@code Class} object.
3149      *
3150      * @param obj the object to be cast
3151      * @return the object after casting, or null if obj is null
3152      *
3153      * @throws ClassCastException if the object is not
3154      * null and is not assignable to the type T.
3155      *
3156      * @since 1.5
3157      */
3158     @SuppressWarnings("unchecked")
3159     public T cast(Object obj) {
3160         if (obj != null && !isInstance(obj))
3161             throw new ClassCastException(cannotCastMsg(obj));
3162         return (T) obj;
3163     }
3164 
3165     private String cannotCastMsg(Object obj) {
3166         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3167     }
3168 
3169     /**
3170      * Casts this {@code Class} object to represent a subclass of the class
3171      * represented by the specified class object.  Checks that the cast
3172      * is valid, and throws a {@code ClassCastException} if it is not.  If
3173      * this method succeeds, it always returns a reference to this class object.
3174      *
3175      * <p>This method is useful when a client needs to "narrow" the type of
3176      * a {@code Class} object to pass it to an API that restricts the
3177      * {@code Class} objects that it is willing to accept.  A cast would
3178      * generate a compile-time warning, as the correctness of the cast
3179      * could not be checked at runtime (because generic types are implemented
3180      * by erasure).
3181      *
3182      * @param <U> the type to cast this class object to
3183      * @param clazz the class of the type to cast this class object to
3184      * @return this {@code Class} object, cast to represent a subclass of
3185      *    the specified class object.
3186      * @throws ClassCastException if this {@code Class} object does not
3187      *    represent a subclass of the specified class (here "subclass" includes
3188      *    the class itself).
3189      * @since 1.5
3190      */
3191     @SuppressWarnings("unchecked")
3192     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
3193         if (clazz.isAssignableFrom(this))
3194             return (Class<? extends U>) this;
3195         else
3196             throw new ClassCastException(this.toString());
3197     }
3198 
3199     /**
3200      * @throws NullPointerException {@inheritDoc}
3201      * @since 1.5
3202      */
3203     @SuppressWarnings("unchecked")
3204     public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
3205         Objects.requireNonNull(annotationClass);
3206 
3207         initAnnotationsIfNecessary();
3208         return (A) annotations.get(annotationClass);
3209     }
3210 
3211     /**
3212      * {@inheritDoc}
3213      * @throws NullPointerException {@inheritDoc}
3214      * @since 1.5
3215      */
3216     @Override
3217     public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
3218         return GenericDeclaration.super.isAnnotationPresent(annotationClass);
3219     }
3220 
3221     /**
3222      * @throws NullPointerException {@inheritDoc}
3223      * @since 1.8
3224      */
3225     @Override
3226     public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {
3227         Objects.requireNonNull(annotationClass);
3228 
3229         initAnnotationsIfNecessary();
3230         return AnnotationSupport.getMultipleAnnotations(annotations, annotationClass);
3231     }
3232 
3233     /**
3234      * @since 1.5
3235      */
3236     public Annotation[] getAnnotations() {
3237         initAnnotationsIfNecessary();
3238         return AnnotationParser.toArray(annotations);
3239     }
3240 
3241     /**
3242      * @throws NullPointerException {@inheritDoc}
3243      * @since 1.8
3244      */
3245     @Override
3246     @SuppressWarnings("unchecked")
3247     public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
3248         Objects.requireNonNull(annotationClass);
3249 
3250         initAnnotationsIfNecessary();
3251         return (A) declaredAnnotations.get(annotationClass);
3252     }
3253 
3254     /**
3255      * @throws NullPointerException {@inheritDoc}
3256      * @since 1.8
3257      */
3258     @Override
3259     public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {
3260         Objects.requireNonNull(annotationClass);
3261 
3262         initAnnotationsIfNecessary();
3263         return AnnotationSupport.getMultipleAnnotations(declaredAnnotations, annotationClass);
3264     }
3265 
3266     /**
3267      * @since 1.5
3268      */
3269     public Annotation[] getDeclaredAnnotations()  {
3270         initAnnotationsIfNecessary();
3271         return AnnotationParser.toArray(declaredAnnotations);
3272     }
3273 
3274     // Annotations cache
3275     private transient Map<Class<? extends Annotation>, Annotation> annotations;
3276     private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
3277     // Value of classRedefinedCount when we last cleared the cached annotations and declaredAnnotations fields
3278     private  transient int lastAnnotationsRedefinedCount = 0;
3279 
3280     // Clears cached values that might possibly have been obsoleted by
3281     // a class redefinition.
3282     private void clearAnnotationCachesOnClassRedefinition() {
3283         if (lastAnnotationsRedefinedCount != classRedefinedCount) {
3284             annotations = declaredAnnotations = null;
3285             lastAnnotationsRedefinedCount = classRedefinedCount;
3286         }
3287     }
3288 
3289     private synchronized void initAnnotationsIfNecessary() {
3290         clearAnnotationCachesOnClassRedefinition();
3291         if (annotations != null)
3292             return;
3293         declaredAnnotations = AnnotationParser.parseAnnotations(
3294             getRawAnnotations(), getConstantPool(), this);
3295         Class<?> superClass = getSuperclass();
3296         if (superClass == null) {
3297             annotations = declaredAnnotations;
3298         } else {
3299             annotations = new HashMap<>();
3300             superClass.initAnnotationsIfNecessary();
3301             for (Map.Entry<Class<? extends Annotation>, Annotation> e : superClass.annotations.entrySet()) {
3302                 Class<? extends Annotation> annotationClass = e.getKey();
3303                 if (AnnotationType.getInstance(annotationClass).isInherited())
3304                     annotations.put(annotationClass, e.getValue());
3305             }
3306             annotations.putAll(declaredAnnotations);
3307         }
3308     }
3309 
3310     // Annotation types cache their internal (AnnotationType) form
3311 
3312     @SuppressWarnings("UnusedDeclaration")
3313     private volatile transient AnnotationType annotationType;
3314 
3315     boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {
3316         return Atomic.casAnnotationType(this, oldType, newType);
3317     }
3318 
3319     AnnotationType getAnnotationType() {
3320         return annotationType;
3321     }
3322 
3323     /* Backing store of user-defined values pertaining to this class.
3324      * Maintained by the ClassValue class.
3325      */
3326     transient ClassValue.ClassValueMap classValueMap;
3327 
3328     /**
3329      * Returns an AnnotatedType object that represents the use of a type to specify
3330      * the superclass of the entity represented by this Class. (The <em>use</em> of type
3331      * Foo to specify the superclass in '... extends Foo' is distinct from the
3332      * <em>declaration</em> of type Foo.)
3333      *
3334      * If this Class represents a class type whose declaration does not explicitly
3335      * indicate an annotated superclass, the return value is null.
3336      *
3337      * If this Class represents either the Object class, an interface type, an
3338      * array type, a primitive type, or void, the return value is null.
3339      *
3340      * @return an object representing the superclass
3341      * @since 1.8
3342      */
3343     public AnnotatedType getAnnotatedSuperclass() {
3344         if (this == Object.class ||
3345                 isInterface() ||
3346                 isArray() ||
3347                 isPrimitive() ||
3348                 this == Void.TYPE) {
3349             return null;
3350         }
3351 
3352         return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
3353     }
3354 
3355     /**
3356      * Returns an array of AnnotatedType objects that represent the use of types to
3357      * specify superinterfaces of the entity represented by this Class. (The <em>use</em>
3358      * of type Foo to specify a superinterface in '... implements Foo' is
3359      * distinct from the <em>declaration</em> of type Foo.)
3360      *
3361      * If this Class represents a class, the return value is an array
3362      * containing objects representing the uses of interface types to specify
3363      * interfaces implemented by the class. The order of the objects in the
3364      * array corresponds to the order of the interface types used in the
3365      * 'implements' clause of the declaration of this Class.
3366      *
3367      * If this Class represents an interface, the return value is an array
3368      * containing objects representing the uses of interface types to specify
3369      * interfaces directly extended by the interface. The order of the objects in
3370      * the array corresponds to the order of the interface types used in the
3371      * 'extends' clause of the declaration of this Class.
3372      *
3373      * If this Class represents a class or interface whose declaration does not
3374      * explicitly indicate any annotated superinterfaces, the return value is an
3375      * array of length 0.
3376      *
3377      * If this Class represents either the Object class, an array type, a
3378      * primitive type, or void, the return value is an array of length 0.
3379      *
3380      * @return an array representing the superinterfaces
3381      * @since 1.8
3382      */
3383     public AnnotatedType[] getAnnotatedInterfaces() {
3384          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3385     }
3386 }