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 {@code
 161      * &#64;interface}, as appropriate), followed by the type's name,
 162      * followed by an angle-bracketed comma-separated list of the
 163      * 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             if (System.getSecurityManager() != null) {
1020                 enclosingCandidate.checkMemberAccess(Member.DECLARED,
1021                                                      Reflection.getCallerClass(), true);
1022             }
1023             /*
1024              * Loop over all declared methods; match method name,
1025              * number of and type of parameters, *and* return
1026              * type.  Matching return type is also necessary
1027              * because of covariant returns, etc.
1028              */
1029             for(Method m: enclosingCandidate.getDeclaredMethods()) {
1030                 if (m.getName().equals(enclosingInfo.getName()) ) {
1031                     Class<?>[] candidateParamClasses = m.getParameterTypes();
1032                     if (candidateParamClasses.length == parameterClasses.length) {
1033                         boolean matches = true;
1034                         for(int i = 0; i < candidateParamClasses.length; i++) {
1035                             if (!candidateParamClasses[i].equals(parameterClasses[i])) {
1036                                 matches = false;
1037                                 break;
1038                             }
1039                         }
1040 
1041                         if (matches) { // finally, check return type
1042                             if (m.getReturnType().equals(returnType) )
1043                                 return m;
1044                         }
1045                     }
1046                 }
1047             }
1048 
1049             throw new InternalError("Enclosing method not found");
1050         }
1051     }
1052 
1053     private native Object[] getEnclosingMethod0();
1054 
1055     private EnclosingMethodInfo getEnclosingMethodInfo() {
1056         Object[] enclosingInfo = getEnclosingMethod0();
1057         if (enclosingInfo == null)
1058             return null;
1059         else {
1060             return new EnclosingMethodInfo(enclosingInfo);
1061         }
1062     }
1063 
1064     private final static class EnclosingMethodInfo {
1065         private Class<?> enclosingClass;
1066         private String name;
1067         private String descriptor;
1068 
1069         private EnclosingMethodInfo(Object[] enclosingInfo) {
1070             if (enclosingInfo.length != 3)
1071                 throw new InternalError("Malformed enclosing method information");
1072             try {
1073                 // The array is expected to have three elements:
1074 
1075                 // the immediately enclosing class
1076                 enclosingClass = (Class<?>) enclosingInfo[0];
1077                 assert(enclosingClass != null);
1078 
1079                 // the immediately enclosing method or constructor's
1080                 // name (can be null).
1081                 name            = (String)   enclosingInfo[1];
1082 
1083                 // the immediately enclosing method or constructor's
1084                 // descriptor (null iff name is).
1085                 descriptor      = (String)   enclosingInfo[2];
1086                 assert((name != null && descriptor != null) || name == descriptor);
1087             } catch (ClassCastException cce) {
1088                 throw new InternalError("Invalid type in enclosing method information", cce);
1089             }
1090         }
1091 
1092         boolean isPartial() {
1093             return enclosingClass == null || name == null || descriptor == null;
1094         }
1095 
1096         boolean isConstructor() { return !isPartial() && "<init>".equals(name); }
1097 
1098         boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }
1099 
1100         Class<?> getEnclosingClass() { return enclosingClass; }
1101 
1102         String getName() { return name; }
1103 
1104         String getDescriptor() { return descriptor; }
1105 
1106     }
1107 
1108     private static Class<?> toClass(Type o) {
1109         if (o instanceof GenericArrayType)
1110             return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
1111                                      0)
1112                 .getClass();
1113         return (Class<?>)o;
1114      }
1115 
1116     /**
1117      * If this {@code Class} object represents a local or anonymous
1118      * class within a constructor, returns a {@link
1119      * java.lang.reflect.Constructor Constructor} object representing
1120      * the immediately enclosing constructor of the underlying
1121      * class. Returns {@code null} otherwise.  In particular, this
1122      * method returns {@code null} if the underlying class is a local
1123      * or anonymous class immediately enclosed by a type declaration,
1124      * instance initializer or static initializer.
1125      *
1126      * @return the immediately enclosing constructor of the underlying class, if
1127      *     that class is a local or anonymous class; otherwise {@code null}.
1128      * @throws SecurityException
1129      *         If a security manager, <i>s</i>, is present and any of the
1130      *         following conditions is met:
1131      *
1132      *         <ul>
1133      *
1134      *         <li> the caller's class loader is not the same as the
1135      *         class loader of the enclosing class and invocation of
1136      *         {@link SecurityManager#checkPermission
1137      *         s.checkPermission} method with
1138      *         {@code RuntimePermission("accessDeclaredMembers")}
1139      *         denies access to the constructors within the enclosing class
1140      *
1141      *         <li> the caller's class loader is not the same as or an
1142      *         ancestor of the class loader for the enclosing class and
1143      *         invocation of {@link SecurityManager#checkPackageAccess
1144      *         s.checkPackageAccess()} denies access to the package
1145      *         of the enclosing class
1146      *
1147      *         </ul>
1148      * @since 1.5
1149      */
1150     @CallerSensitive
1151     public Constructor<?> getEnclosingConstructor() throws SecurityException {
1152         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1153 
1154         if (enclosingInfo == null)
1155             return null;
1156         else {
1157             if (!enclosingInfo.isConstructor())
1158                 return null;
1159 
1160             ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
1161                                                                         getFactory());
1162             Type []    parameterTypes   = typeInfo.getParameterTypes();
1163             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1164 
1165             // Convert Types to Classes; returned types *should*
1166             // be class objects since the methodDescriptor's used
1167             // don't have generics information
1168             for(int i = 0; i < parameterClasses.length; i++)
1169                 parameterClasses[i] = toClass(parameterTypes[i]);
1170 
1171             // Perform access check
1172             Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1173             if (System.getSecurityManager() != null) {
1174                 enclosingCandidate.checkMemberAccess(Member.DECLARED,
1175                                                      Reflection.getCallerClass(), true);
1176             }
1177             /*
1178              * Loop over all declared constructors; match number
1179              * of and type of parameters.
1180              */
1181             for(Constructor<?> c: enclosingCandidate.getDeclaredConstructors()) {
1182                 Class<?>[] candidateParamClasses = c.getParameterTypes();
1183                 if (candidateParamClasses.length == parameterClasses.length) {
1184                     boolean matches = true;
1185                     for(int i = 0; i < candidateParamClasses.length; i++) {
1186                         if (!candidateParamClasses[i].equals(parameterClasses[i])) {
1187                             matches = false;
1188                             break;
1189                         }
1190                     }
1191 
1192                     if (matches)
1193                         return c;
1194                 }
1195             }
1196 
1197             throw new InternalError("Enclosing constructor not found");
1198         }
1199     }
1200 
1201 
1202     /**
1203      * If the class or interface represented by this {@code Class} object
1204      * is a member of another class, returns the {@code Class} object
1205      * representing the class in which it was declared.  This method returns
1206      * null if this class or interface is not a member of any other class.  If
1207      * this {@code Class} object represents an array class, a primitive
1208      * type, or void,then this method returns null.
1209      *
1210      * @return the declaring class for this class
1211      * @since JDK1.1
1212      */
1213     public native Class<?> getDeclaringClass();
1214 
1215 
1216     /**
1217      * Returns the immediately enclosing class of the underlying
1218      * class.  If the underlying class is a top level class this
1219      * method returns {@code null}.
1220      * @return the immediately enclosing class of the underlying class
1221      * @exception  SecurityException
1222      *             If a security manager, <i>s</i>, is present and the caller's
1223      *             class loader is not the same as or an ancestor of the class
1224      *             loader for the enclosing class and invocation of {@link
1225      *             SecurityManager#checkPackageAccess s.checkPackageAccess()}
1226      *             denies access to the package of the enclosing class
1227      * @since 1.5
1228      */
1229     @CallerSensitive
1230     public Class<?> getEnclosingClass() throws SecurityException {
1231         // There are five kinds of classes (or interfaces):
1232         // a) Top level classes
1233         // b) Nested classes (static member classes)
1234         // c) Inner classes (non-static member classes)
1235         // d) Local classes (named classes declared within a method)
1236         // e) Anonymous classes
1237 
1238 
1239         // JVM Spec 4.8.6: A class must have an EnclosingMethod
1240         // attribute if and only if it is a local class or an
1241         // anonymous class.
1242         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1243         Class<?> enclosingCandidate;
1244 
1245         if (enclosingInfo == null) {
1246             // This is a top level or a nested class or an inner class (a, b, or c)
1247             enclosingCandidate = getDeclaringClass();
1248         } else {
1249             Class<?> enclosingClass = enclosingInfo.getEnclosingClass();
1250             // This is a local class or an anonymous class (d or e)
1251             if (enclosingClass == this || enclosingClass == null)
1252                 throw new InternalError("Malformed enclosing method information");
1253             else
1254                 enclosingCandidate = enclosingClass;
1255         }
1256 
1257         if (enclosingCandidate != null)
1258             enclosingCandidate.checkPackageAccess(
1259                     ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
1260         return enclosingCandidate;
1261     }
1262 
1263     /**
1264      * Returns the simple name of the underlying class as given in the
1265      * source code. Returns an empty string if the underlying class is
1266      * anonymous.
1267      *
1268      * <p>The simple name of an array is the simple name of the
1269      * component type with "[]" appended.  In particular the simple
1270      * name of an array whose component type is anonymous is "[]".
1271      *
1272      * @return the simple name of the underlying class
1273      * @since 1.5
1274      */
1275     public String getSimpleName() {
1276         if (isArray())
1277             return getComponentType().getSimpleName()+"[]";
1278 
1279         String simpleName = getSimpleBinaryName();
1280         if (simpleName == null) { // top level class
1281             simpleName = getName();
1282             return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
1283         }
1284         // According to JLS3 "Binary Compatibility" (13.1) the binary
1285         // name of non-package classes (not top level) is the binary
1286         // name of the immediately enclosing class followed by a '$' followed by:
1287         // (for nested and inner classes): the simple name.
1288         // (for local classes): 1 or more digits followed by the simple name.
1289         // (for anonymous classes): 1 or more digits.
1290 
1291         // Since getSimpleBinaryName() will strip the binary name of
1292         // the immediatly enclosing class, we are now looking at a
1293         // string that matches the regular expression "\$[0-9]*"
1294         // followed by a simple name (considering the simple of an
1295         // anonymous class to be the empty string).
1296 
1297         // Remove leading "\$[0-9]*" from the name
1298         int length = simpleName.length();
1299         if (length < 1 || simpleName.charAt(0) != '$')
1300             throw new InternalError("Malformed class name");
1301         int index = 1;
1302         while (index < length && isAsciiDigit(simpleName.charAt(index)))
1303             index++;
1304         // Eventually, this is the empty string iff this is an anonymous class
1305         return simpleName.substring(index);
1306     }
1307 
1308     /**
1309      * Return an informative string for the name of this type.
1310      *
1311      * @return an informative string for the name of this type
1312      * @since 1.8
1313      */
1314     public String getTypeName() {
1315         if (isArray()) {
1316             try {
1317                 Class<?> cl = this;
1318                 int dimensions = 0;
1319                 while (cl.isArray()) {
1320                     dimensions++;
1321                     cl = cl.getComponentType();
1322                 }
1323                 StringBuilder sb = new StringBuilder();
1324                 sb.append(cl.getName());
1325                 for (int i = 0; i < dimensions; i++) {
1326                     sb.append("[]");
1327                 }
1328                 return sb.toString();
1329             } catch (Throwable e) { /*FALLTHRU*/ }
1330         }
1331         return getName();
1332     }
1333 
1334     /**
1335      * Character.isDigit answers {@code true} to some non-ascii
1336      * digits.  This one does not.
1337      */
1338     private static boolean isAsciiDigit(char c) {
1339         return '0' <= c && c <= '9';
1340     }
1341 
1342     /**
1343      * Returns the canonical name of the underlying class as
1344      * defined by the Java Language Specification.  Returns null if
1345      * the underlying class does not have a canonical name (i.e., if
1346      * it is a local or anonymous class or an array whose component
1347      * type does not have a canonical name).
1348      * @return the canonical name of the underlying class if it exists, and
1349      * {@code null} otherwise.
1350      * @since 1.5
1351      */
1352     public String getCanonicalName() {
1353         if (isArray()) {
1354             String canonicalName = getComponentType().getCanonicalName();
1355             if (canonicalName != null)
1356                 return canonicalName + "[]";
1357             else
1358                 return null;
1359         }
1360         if (isLocalOrAnonymousClass())
1361             return null;
1362         Class<?> enclosingClass = getEnclosingClass();
1363         if (enclosingClass == null) { // top level class
1364             return getName();
1365         } else {
1366             String enclosingName = enclosingClass.getCanonicalName();
1367             if (enclosingName == null)
1368                 return null;
1369             return enclosingName + "." + getSimpleName();
1370         }
1371     }
1372 
1373     /**
1374      * Returns {@code true} if and only if the underlying class
1375      * is an anonymous class.
1376      *
1377      * @return {@code true} if and only if this class is an anonymous class.
1378      * @since 1.5
1379      */
1380     public boolean isAnonymousClass() {
1381         return "".equals(getSimpleName());
1382     }
1383 
1384     /**
1385      * Returns {@code true} if and only if the underlying class
1386      * is a local class.
1387      *
1388      * @return {@code true} if and only if this class is a local class.
1389      * @since 1.5
1390      */
1391     public boolean isLocalClass() {
1392         return isLocalOrAnonymousClass() && !isAnonymousClass();
1393     }
1394 
1395     /**
1396      * Returns {@code true} if and only if the underlying class
1397      * is a member class.
1398      *
1399      * @return {@code true} if and only if this class is a member class.
1400      * @since 1.5
1401      */
1402     public boolean isMemberClass() {
1403         return getSimpleBinaryName() != null && !isLocalOrAnonymousClass();
1404     }
1405 
1406     /**
1407      * Returns the "simple binary name" of the underlying class, i.e.,
1408      * the binary name without the leading enclosing class name.
1409      * Returns {@code null} if the underlying class is a top level
1410      * class.
1411      */
1412     private String getSimpleBinaryName() {
1413         Class<?> enclosingClass = getEnclosingClass();
1414         if (enclosingClass == null) // top level class
1415             return null;
1416         // Otherwise, strip the enclosing class' name
1417         try {
1418             return getName().substring(enclosingClass.getName().length());
1419         } catch (IndexOutOfBoundsException ex) {
1420             throw new InternalError("Malformed class name", ex);
1421         }
1422     }
1423 
1424     /**
1425      * Returns {@code true} if this is a local class or an anonymous
1426      * class.  Returns {@code false} otherwise.
1427      */
1428     private boolean isLocalOrAnonymousClass() {
1429         // JVM Spec 4.8.6: A class must have an EnclosingMethod
1430         // attribute if and only if it is a local class or an
1431         // anonymous class.
1432         return getEnclosingMethodInfo() != null;
1433     }
1434 
1435     /**
1436      * Returns an array containing {@code Class} objects representing all
1437      * the public classes and interfaces that are members of the class
1438      * represented by this {@code Class} object.  This includes public
1439      * class and interface members inherited from superclasses and public class
1440      * and interface members declared by the class.  This method returns an
1441      * array of length 0 if this {@code Class} object has no public member
1442      * classes or interfaces.  This method also returns an array of length 0 if
1443      * this {@code Class} object represents a primitive type, an array
1444      * class, or void.
1445      *
1446      * @return the array of {@code Class} objects representing the public
1447      *         members of this class
1448      * @throws SecurityException
1449      *         If a security manager, <i>s</i>, is present and
1450      *         the caller's class loader is not the same as or an
1451      *         ancestor of the class loader for the current class and
1452      *         invocation of {@link SecurityManager#checkPackageAccess
1453      *         s.checkPackageAccess()} denies access to the package
1454      *         of this class.
1455      *
1456      * @since JDK1.1
1457      */
1458     @CallerSensitive
1459     public Class<?>[] getClasses() {
1460         if (System.getSecurityManager() != null) {
1461             checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
1462         }
1463 
1464         // Privileged so this implementation can look at DECLARED classes,
1465         // something the caller might not have privilege to do.  The code here
1466         // is allowed to look at DECLARED classes because (1) it does not hand
1467         // out anything other than public members and (2) public member access
1468         // has already been ok'd by the SecurityManager.
1469 
1470         return java.security.AccessController.doPrivileged(
1471             new java.security.PrivilegedAction<Class<?>[]>() {
1472                 public Class<?>[] run() {
1473                     List<Class<?>> list = new ArrayList<>();
1474                     Class<?> currentClass = Class.this;
1475                     while (currentClass != null) {
1476                         Class<?>[] members = currentClass.getDeclaredClasses();
1477                         for (int i = 0; i < members.length; i++) {
1478                             if (Modifier.isPublic(members[i].getModifiers())) {
1479                                 list.add(members[i]);
1480                             }
1481                         }
1482                         currentClass = currentClass.getSuperclass();
1483                     }
1484                     return list.toArray(new Class<?>[0]);
1485                 }
1486             });
1487     }
1488 
1489 
1490     /**
1491      * Returns an array containing {@code Field} objects reflecting all
1492      * the accessible public fields of the class or interface represented by
1493      * this {@code Class} object.  The elements in the array returned are
1494      * not sorted and are not in any particular order.  This method returns an
1495      * array of length 0 if the class or interface has no accessible public
1496      * fields, or if it represents an array class, a primitive type, or void.
1497      *
1498      * <p> Specifically, if this {@code Class} object represents a class,
1499      * this method returns the public fields of this class and of all its
1500      * superclasses.  If this {@code Class} object represents an
1501      * interface, this method returns the fields of this interface and of all
1502      * its superinterfaces.
1503      *
1504      * <p> The implicit length field for array class is not reflected by this
1505      * method. User code should use the methods of class {@code Array} to
1506      * manipulate arrays.
1507      *
1508      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
1509      *
1510      * @return the array of {@code Field} objects representing the
1511      *         public fields
1512      * @throws SecurityException
1513      *         If a security manager, <i>s</i>, is present and
1514      *         the caller's class loader is not the same as or an
1515      *         ancestor of the class loader for the current class and
1516      *         invocation of {@link SecurityManager#checkPackageAccess
1517      *         s.checkPackageAccess()} denies access to the package
1518      *         of this class.
1519      *
1520      * @since JDK1.1
1521      */
1522     @CallerSensitive
1523     public Field[] getFields() throws SecurityException {
1524         if (System.getSecurityManager() != null) {
1525             checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1526         }
1527         return copyFields(privateGetPublicFields(null));
1528     }
1529 
1530 
1531     /**
1532      * Returns an array containing {@code Method} objects reflecting all
1533      * the public <em>member</em> methods of the class or interface represented
1534      * by this {@code Class} object, including those declared by the class
1535      * or interface and those inherited from superclasses and
1536      * superinterfaces.  Array classes return all the (public) member methods
1537      * inherited from the {@code Object} class.  The elements in the array
1538      * returned are not sorted and are not in any particular order.  This
1539      * method returns an array of length 0 if this {@code Class} object
1540      * represents a class or interface that has no public member methods, or if
1541      * this {@code Class} object represents a primitive type or void.
1542      *
1543      * <p> The class initialization method {@code <clinit>} is not
1544      * included in the returned array. If the class declares multiple public
1545      * member methods with the same parameter types, they are all included in
1546      * the returned array.
1547      *
1548      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
1549      *
1550      * @return the array of {@code Method} objects representing the
1551      *         public methods of this class
1552      * @throws SecurityException
1553      *         If a security manager, <i>s</i>, is present and
1554      *         the caller's class loader is not the same as or an
1555      *         ancestor of the class loader for the current class and
1556      *         invocation of {@link SecurityManager#checkPackageAccess
1557      *         s.checkPackageAccess()} denies access to the package
1558      *         of this class.
1559      *
1560      * @since JDK1.1
1561      */
1562     @CallerSensitive
1563     public Method[] getMethods() throws SecurityException {
1564         if (System.getSecurityManager() != null) {
1565             checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1566         }
1567         return copyMethods(privateGetPublicMethods());
1568     }
1569 
1570 
1571     /**
1572      * Returns an array containing {@code Constructor} objects reflecting
1573      * all the public constructors of the class represented by this
1574      * {@code Class} object.  An array of length 0 is returned if the
1575      * class has no public constructors, or if the class is an array class, or
1576      * if the class reflects a primitive type or void.
1577      *
1578      * Note that while this method returns an array of {@code
1579      * Constructor<T>} objects (that is an array of constructors from
1580      * this class), the return type of this method is {@code
1581      * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
1582      * might be expected.  This less informative return type is
1583      * necessary since after being returned from this method, the
1584      * array could be modified to hold {@code Constructor} objects for
1585      * different classes, which would violate the type guarantees of
1586      * {@code Constructor<T>[]}.
1587      *
1588      * @return the array of {@code Constructor} objects representing the
1589      *         public constructors of this class
1590      * @throws SecurityException
1591      *         If a security manager, <i>s</i>, is present and
1592      *         the caller's class loader is not the same as or an
1593      *         ancestor of the class loader for the current class and
1594      *         invocation of {@link SecurityManager#checkPackageAccess
1595      *         s.checkPackageAccess()} denies access to the package
1596      *         of this class.
1597      *
1598      * @since JDK1.1
1599      */
1600     @CallerSensitive
1601     public Constructor<?>[] getConstructors() throws SecurityException {
1602         if (System.getSecurityManager() != null) {
1603             checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1604         }
1605         return copyConstructors(privateGetDeclaredConstructors(true));
1606     }
1607 
1608 
1609     /**
1610      * Returns a {@code Field} object that reflects the specified public
1611      * member field of the class or interface represented by this
1612      * {@code Class} object. The {@code name} parameter is a
1613      * {@code String} specifying the simple name of the desired field.
1614      *
1615      * <p> The field to be reflected is determined by the algorithm that
1616      * follows.  Let C be the class represented by this object:
1617      * <OL>
1618      * <LI> If C declares a public field with the name specified, that is the
1619      *      field to be reflected.</LI>
1620      * <LI> If no field was found in step 1 above, this algorithm is applied
1621      *      recursively to each direct superinterface of C. The direct
1622      *      superinterfaces are searched in the order they were declared.</LI>
1623      * <LI> If no field was found in steps 1 and 2 above, and C has a
1624      *      superclass S, then this algorithm is invoked recursively upon S.
1625      *      If C has no superclass, then a {@code NoSuchFieldException}
1626      *      is thrown.</LI>
1627      * </OL>
1628      *
1629      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
1630      *
1631      * @param name the field name
1632      * @return the {@code Field} object of this class specified by
1633      *         {@code name}
1634      * @throws NoSuchFieldException if a field with the specified name is
1635      *         not found.
1636      * @throws NullPointerException if {@code name} is {@code null}
1637      * @throws SecurityException
1638      *         If a security manager, <i>s</i>, is present and
1639      *         the caller's class loader is not the same as or an
1640      *         ancestor of the class loader for the current class and
1641      *         invocation of {@link SecurityManager#checkPackageAccess
1642      *         s.checkPackageAccess()} denies access to the package
1643      *         of this class.
1644      *
1645      * @since JDK1.1
1646      */
1647     @CallerSensitive
1648     public Field getField(String name)
1649         throws NoSuchFieldException, SecurityException {
1650         if (System.getSecurityManager() != null) {
1651             checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1652         }
1653         Field field = getField0(name);
1654         if (field == null) {
1655             throw new NoSuchFieldException(name);
1656         }
1657         return field;
1658     }
1659 
1660 
1661     /**
1662      * Returns a {@code Method} object that reflects the specified public
1663      * member method of the class or interface represented by this
1664      * {@code Class} object. The {@code name} parameter is a
1665      * {@code String} specifying the simple name of the desired method. The
1666      * {@code parameterTypes} parameter is an array of {@code Class}
1667      * objects that identify the method's formal parameter types, in declared
1668      * order. If {@code parameterTypes} is {@code null}, it is
1669      * treated as if it were an empty array.
1670      *
1671      * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
1672      * {@code NoSuchMethodException} is raised. Otherwise, the method to
1673      * be reflected is determined by the algorithm that follows.  Let C be the
1674      * class represented by this object:
1675      * <OL>
1676      * <LI> C is searched for any <I>matching methods</I>. If no matching
1677      *      method is found, the algorithm of step 1 is invoked recursively on
1678      *      the superclass of C.</LI>
1679      * <LI> If no method was found in step 1 above, the superinterfaces of C
1680      *      are searched for a matching method. If any such method is found, it
1681      *      is reflected.</LI>
1682      * </OL>
1683      *
1684      * To find a matching method in a class C:&nbsp; If C declares exactly one
1685      * public method with the specified name and exactly the same formal
1686      * parameter types, that is the method reflected. If more than one such
1687      * method is found in C, and one of these methods has a return type that is
1688      * more specific than any of the others, that method is reflected;
1689      * otherwise one of the methods is chosen arbitrarily.
1690      *
1691      * <p>Note that there may be more than one matching method in a
1692      * class because while the Java language forbids a class to
1693      * declare multiple methods with the same signature but different
1694      * return types, the Java virtual machine does not.  This
1695      * increased flexibility in the virtual machine can be used to
1696      * implement various language features.  For example, covariant
1697      * returns can be implemented with {@linkplain
1698      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
1699      * method and the method being overridden would have the same
1700      * signature but different return types.
1701      *
1702      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
1703      *
1704      * @param name the name of the method
1705      * @param parameterTypes the list of parameters
1706      * @return the {@code Method} object that matches the specified
1707      *         {@code name} and {@code parameterTypes}
1708      * @throws NoSuchMethodException if a matching method is not found
1709      *         or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
1710      * @throws NullPointerException if {@code name} is {@code null}
1711      * @throws SecurityException
1712      *         If a security manager, <i>s</i>, is present and
1713      *         the caller's class loader is not the same as or an
1714      *         ancestor of the class loader for the current class and
1715      *         invocation of {@link SecurityManager#checkPackageAccess
1716      *         s.checkPackageAccess()} denies access to the package
1717      *         of this class.
1718      *
1719      * @since JDK1.1
1720      */
1721     @CallerSensitive
1722     public Method getMethod(String name, Class<?>... parameterTypes)
1723         throws NoSuchMethodException, SecurityException {
1724         if (System.getSecurityManager() != null) {
1725             checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1726         }
1727         Method method = getMethod0(name, parameterTypes);
1728         if (method == null) {
1729             throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
1730         }
1731         return method;
1732     }
1733 
1734 
1735     /**
1736      * Returns a {@code Constructor} object that reflects the specified
1737      * public constructor of the class represented by this {@code Class}
1738      * object. The {@code parameterTypes} parameter is an array of
1739      * {@code Class} objects that identify the constructor's formal
1740      * parameter types, in declared order.
1741      *
1742      * If this {@code Class} object represents an inner class
1743      * declared in a non-static context, the formal parameter types
1744      * include the explicit enclosing instance as the first parameter.
1745      *
1746      * <p> The constructor to reflect is the public constructor of the class
1747      * represented by this {@code Class} object whose formal parameter
1748      * types match those specified by {@code parameterTypes}.
1749      *
1750      * @param parameterTypes the parameter array
1751      * @return the {@code Constructor} object of the public constructor that
1752      *         matches the specified {@code parameterTypes}
1753      * @throws NoSuchMethodException if a matching method is not found.
1754      * @throws SecurityException
1755      *         If a security manager, <i>s</i>, is present and
1756      *         the caller's class loader is not the same as or an
1757      *         ancestor of the class loader for the current class and
1758      *         invocation of {@link SecurityManager#checkPackageAccess
1759      *         s.checkPackageAccess()} denies access to the package
1760      *         of this class.
1761      *
1762      * @since JDK1.1
1763      */
1764     @CallerSensitive
1765     public Constructor<T> getConstructor(Class<?>... parameterTypes)
1766         throws NoSuchMethodException, SecurityException {
1767         if (System.getSecurityManager() != null) {
1768             checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1769         }
1770         return getConstructor0(parameterTypes, Member.PUBLIC);
1771     }
1772 
1773 
1774     /**
1775      * Returns an array of {@code Class} objects reflecting all the
1776      * classes and interfaces declared as members of the class represented by
1777      * this {@code Class} object. This includes public, protected, default
1778      * (package) access, and private classes and interfaces declared by the
1779      * class, but excludes inherited classes and interfaces.  This method
1780      * returns an array of length 0 if the class declares no classes or
1781      * interfaces as members, or if this {@code Class} object represents a
1782      * primitive type, an array class, or void.
1783      *
1784      * @return the array of {@code Class} objects representing all the
1785      *         declared members of this class
1786      * @throws SecurityException
1787      *         If a security manager, <i>s</i>, is present and any of the
1788      *         following conditions is met:
1789      *
1790      *         <ul>
1791      *
1792      *         <li> the caller's class loader is not the same as the
1793      *         class loader of this class and invocation of
1794      *         {@link SecurityManager#checkPermission
1795      *         s.checkPermission} method with
1796      *         {@code RuntimePermission("accessDeclaredMembers")}
1797      *         denies access to the declared classes within this class
1798      *
1799      *         <li> the caller's class loader is not the same as or an
1800      *         ancestor of the class loader for the current class and
1801      *         invocation of {@link SecurityManager#checkPackageAccess
1802      *         s.checkPackageAccess()} denies access to the package
1803      *         of this class
1804      *
1805      *         </ul>
1806      *
1807      * @since JDK1.1
1808      */
1809     @CallerSensitive
1810     public Class<?>[] getDeclaredClasses() throws SecurityException {
1811         if (System.getSecurityManager() != null) {
1812             checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), false);
1813         }
1814         return getDeclaredClasses0();
1815     }
1816 
1817 
1818     /**
1819      * Returns an array of {@code Field} objects reflecting all the fields
1820      * declared by the class or interface represented by this
1821      * {@code Class} object. This includes public, protected, default
1822      * (package) access, and private fields, but excludes inherited fields.
1823      * The elements in the array returned are not sorted and are not in any
1824      * particular order.  This method returns an array of length 0 if the class
1825      * or interface declares no fields, or if this {@code Class} object
1826      * represents a primitive type, an array class, or void.
1827      *
1828      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
1829      *
1830      * @return  the array of {@code Field} objects representing all the
1831      *          declared fields of this class
1832      * @throws  SecurityException
1833      *          If a security manager, <i>s</i>, is present and any of the
1834      *          following conditions is met:
1835      *
1836      *          <ul>
1837      *
1838      *          <li> the caller's class loader is not the same as the
1839      *          class loader of this class and invocation of
1840      *          {@link SecurityManager#checkPermission
1841      *          s.checkPermission} method with
1842      *          {@code RuntimePermission("accessDeclaredMembers")}
1843      *          denies access to the declared fields within this class
1844      *
1845      *          <li> the caller's class loader is not the same as or an
1846      *          ancestor of the class loader for the current class and
1847      *          invocation of {@link SecurityManager#checkPackageAccess
1848      *          s.checkPackageAccess()} denies access to the package
1849      *          of this class
1850      *
1851      *          </ul>
1852      *
1853      * @since JDK1.1
1854      */
1855     @CallerSensitive
1856     public Field[] getDeclaredFields() throws SecurityException {
1857         if (System.getSecurityManager() != null) {
1858             checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
1859         }
1860         return copyFields(privateGetDeclaredFields(false));
1861     }
1862 
1863 
1864     /**
1865      * Returns an array of {@code Method} objects reflecting all the
1866      * methods declared by the class or interface represented by this
1867      * {@code Class} object. This includes public, protected, default
1868      * (package) access, and private methods, but excludes inherited methods.
1869      * The elements in the array returned are not sorted and are not in any
1870      * particular order.  This method returns an array of length 0 if the class
1871      * or interface declares no methods, or if this {@code Class} object
1872      * represents a primitive type, an array class, or void.  The class
1873      * initialization method {@code <clinit>} is not included in the
1874      * returned array. If the class declares multiple public member methods
1875      * with the same parameter types, they are all included in the returned
1876      * array.
1877      *
1878      * <p> See <em>The Java Language Specification</em>, section 8.2.
1879      *
1880      * @return  the array of {@code Method} objects representing all the
1881      *          declared methods of this class
1882      * @throws  SecurityException
1883      *          If a security manager, <i>s</i>, is present and any of the
1884      *          following conditions is met:
1885      *
1886      *          <ul>
1887      *
1888      *          <li> the caller's class loader is not the same as the
1889      *          class loader of this class and invocation of
1890      *          {@link SecurityManager#checkPermission
1891      *          s.checkPermission} method with
1892      *          {@code RuntimePermission("accessDeclaredMembers")}
1893      *          denies access to the declared methods within this class
1894      *
1895      *          <li> the caller's class loader is not the same as or an
1896      *          ancestor of the class loader for the current class and
1897      *          invocation of {@link SecurityManager#checkPackageAccess
1898      *          s.checkPackageAccess()} denies access to the package
1899      *          of this class
1900      *
1901      *          </ul>
1902      *
1903      * @since JDK1.1
1904      */
1905     @CallerSensitive
1906     public Method[] getDeclaredMethods() throws SecurityException {
1907         if (System.getSecurityManager() != null) {
1908             checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
1909         }
1910         return copyMethods(privateGetDeclaredMethods(false));
1911     }
1912 
1913 
1914     /**
1915      * Returns an array of {@code Constructor} objects reflecting all the
1916      * constructors declared by the class represented by this
1917      * {@code Class} object. These are public, protected, default
1918      * (package) access, and private constructors.  The elements in the array
1919      * returned are not sorted and are not in any particular order.  If the
1920      * class has a default constructor, it is included in the returned array.
1921      * This method returns an array of length 0 if this {@code Class}
1922      * object represents an interface, a primitive type, an array class, or
1923      * void.
1924      *
1925      * <p> See <em>The Java Language Specification</em>, section 8.2.
1926      *
1927      * @return  the array of {@code Constructor} objects representing all the
1928      *          declared constructors of this class
1929      * @throws  SecurityException
1930      *          If a security manager, <i>s</i>, is present and any of the
1931      *          following conditions is met:
1932      *
1933      *          <ul>
1934      *
1935      *          <li> the caller's class loader is not the same as the
1936      *          class loader of this class and invocation of
1937      *          {@link SecurityManager#checkPermission
1938      *          s.checkPermission} method with
1939      *          {@code RuntimePermission("accessDeclaredMembers")}
1940      *          denies access to the declared constructors within this class
1941      *
1942      *          <li> the caller's class loader is not the same as or an
1943      *          ancestor of the class loader for the current class and
1944      *          invocation of {@link SecurityManager#checkPackageAccess
1945      *          s.checkPackageAccess()} denies access to the package
1946      *          of this class
1947      *
1948      *          </ul>
1949      *
1950      * @since JDK1.1
1951      */
1952     @CallerSensitive
1953     public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
1954         if (System.getSecurityManager() != null) {
1955             checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
1956         }
1957         return copyConstructors(privateGetDeclaredConstructors(false));
1958     }
1959 
1960 
1961     /**
1962      * Returns a {@code Field} object that reflects the specified declared
1963      * field of the class or interface represented by this {@code Class}
1964      * object. The {@code name} parameter is a {@code String} that
1965      * specifies the simple name of the desired field.  Note that this method
1966      * will not reflect the {@code length} field of an array class.
1967      *
1968      * @param name the name of the field
1969      * @return  the {@code Field} object for the specified field in this
1970      *          class
1971      * @throws  NoSuchFieldException if a field with the specified name is
1972      *          not found.
1973      * @throws  NullPointerException if {@code name} is {@code null}
1974      * @throws  SecurityException
1975      *          If a security manager, <i>s</i>, is present and any of the
1976      *          following conditions is met:
1977      *
1978      *          <ul>
1979      *
1980      *          <li> the caller's class loader is not the same as the
1981      *          class loader of this class and invocation of
1982      *          {@link SecurityManager#checkPermission
1983      *          s.checkPermission} method with
1984      *          {@code RuntimePermission("accessDeclaredMembers")}
1985      *          denies access to the declared field
1986      *
1987      *          <li> the caller's class loader is not the same as or an
1988      *          ancestor of the class loader for the current class and
1989      *          invocation of {@link SecurityManager#checkPackageAccess
1990      *          s.checkPackageAccess()} denies access to the package
1991      *          of this class
1992      *
1993      *          </ul>
1994      *
1995      * @since JDK1.1
1996      */
1997     @CallerSensitive
1998     public Field getDeclaredField(String name)
1999         throws NoSuchFieldException, SecurityException {
2000         if (System.getSecurityManager() != null) {
2001             checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2002         }
2003         Field field = searchFields(privateGetDeclaredFields(false), name);
2004         if (field == null) {
2005             throw new NoSuchFieldException(name);
2006         }
2007         return field;
2008     }
2009 
2010 
2011     /**
2012      * Returns a {@code Method} object that reflects the specified
2013      * declared method of the class or interface represented by this
2014      * {@code Class} object. The {@code name} parameter is a
2015      * {@code String} that specifies the simple name of the desired
2016      * method, and the {@code parameterTypes} parameter is an array of
2017      * {@code Class} objects that identify the method's formal parameter
2018      * types, in declared order.  If more than one method with the same
2019      * parameter types is declared in a class, and one of these methods has a
2020      * return type that is more specific than any of the others, that method is
2021      * returned; otherwise one of the methods is chosen arbitrarily.  If the
2022      * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
2023      * is raised.
2024      *
2025      * @param name the name of the method
2026      * @param parameterTypes the parameter array
2027      * @return  the {@code Method} object for the method of this class
2028      *          matching the specified name and parameters
2029      * @throws  NoSuchMethodException if a matching method is not found.
2030      * @throws  NullPointerException if {@code name} is {@code null}
2031      * @throws  SecurityException
2032      *          If a security manager, <i>s</i>, is present and any of the
2033      *          following conditions is met:
2034      *
2035      *          <ul>
2036      *
2037      *          <li> the caller's class loader is not the same as the
2038      *          class loader of this class and invocation of
2039      *          {@link SecurityManager#checkPermission
2040      *          s.checkPermission} method with
2041      *          {@code RuntimePermission("accessDeclaredMembers")}
2042      *          denies access to the declared method
2043      *
2044      *          <li> the caller's class loader is not the same as or an
2045      *          ancestor of the class loader for the current class and
2046      *          invocation of {@link SecurityManager#checkPackageAccess
2047      *          s.checkPackageAccess()} denies access to the package
2048      *          of this class
2049      *
2050      *          </ul>
2051      *
2052      * @since JDK1.1
2053      */
2054     @CallerSensitive
2055     public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2056         throws NoSuchMethodException, SecurityException {
2057         if (System.getSecurityManager() != null) {
2058             checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2059         }
2060         Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
2061         if (method == null) {
2062             throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
2063         }
2064         return method;
2065     }
2066 
2067 
2068     /**
2069      * Returns a {@code Constructor} object that reflects the specified
2070      * constructor of the class or interface represented by this
2071      * {@code Class} object.  The {@code parameterTypes} parameter is
2072      * an array of {@code Class} objects that identify the constructor's
2073      * formal parameter types, in declared order.
2074      *
2075      * If this {@code Class} object represents an inner class
2076      * declared in a non-static context, the formal parameter types
2077      * include the explicit enclosing instance as the first parameter.
2078      *
2079      * @param parameterTypes the parameter array
2080      * @return  The {@code Constructor} object for the constructor with the
2081      *          specified parameter list
2082      * @throws  NoSuchMethodException if a matching method is not found.
2083      * @throws  SecurityException
2084      *          If a security manager, <i>s</i>, is present and any of the
2085      *          following conditions is met:
2086      *
2087      *          <ul>
2088      *
2089      *          <li> the caller's class loader is not the same as the
2090      *          class loader of this class and invocation of
2091      *          {@link SecurityManager#checkPermission
2092      *          s.checkPermission} method with
2093      *          {@code RuntimePermission("accessDeclaredMembers")}
2094      *          denies access to the declared constructor
2095      *
2096      *          <li> the caller's class loader is not the same as or an
2097      *          ancestor of the class loader for the current class and
2098      *          invocation of {@link SecurityManager#checkPackageAccess
2099      *          s.checkPackageAccess()} denies access to the package
2100      *          of this class
2101      *
2102      *          </ul>
2103      *
2104      * @since JDK1.1
2105      */
2106     @CallerSensitive
2107     public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
2108         throws NoSuchMethodException, SecurityException {
2109         if (System.getSecurityManager() != null) {
2110             checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2111         }
2112         return getConstructor0(parameterTypes, Member.DECLARED);
2113     }
2114 
2115     /**
2116      * Finds a resource with a given name.  The rules for searching resources
2117      * associated with a given class are implemented by the defining
2118      * {@linkplain ClassLoader class loader} of the class.  This method
2119      * delegates to this object's class loader.  If this object was loaded by
2120      * the bootstrap class loader, the method delegates to {@link
2121      * ClassLoader#getSystemResourceAsStream}.
2122      *
2123      * <p> Before delegation, an absolute resource name is constructed from the
2124      * given resource name using this algorithm:
2125      *
2126      * <ul>
2127      *
2128      * <li> If the {@code name} begins with a {@code '/'}
2129      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
2130      * portion of the {@code name} following the {@code '/'}.
2131      *
2132      * <li> Otherwise, the absolute name is of the following form:
2133      *
2134      * <blockquote>
2135      *   {@code modified_package_name/name}
2136      * </blockquote>
2137      *
2138      * <p> Where the {@code modified_package_name} is the package name of this
2139      * object with {@code '/'} substituted for {@code '.'}
2140      * (<tt>'&#92;u002e'</tt>).
2141      *
2142      * </ul>
2143      *
2144      * @param  name name of the desired resource
2145      * @return      A {@link java.io.InputStream} object or {@code null} if
2146      *              no resource with this name is found
2147      * @throws  NullPointerException If {@code name} is {@code null}
2148      * @since  JDK1.1
2149      */
2150      public InputStream getResourceAsStream(String name) {
2151         name = resolveName(name);
2152         ClassLoader cl = getClassLoader0();
2153         if (cl==null) {
2154             // A system class.
2155             return ClassLoader.getSystemResourceAsStream(name);
2156         }
2157         return cl.getResourceAsStream(name);
2158     }
2159 
2160     /**
2161      * Finds a resource with a given name.  The rules for searching resources
2162      * associated with a given class are implemented by the defining
2163      * {@linkplain ClassLoader class loader} of the class.  This method
2164      * delegates to this object's class loader.  If this object was loaded by
2165      * the bootstrap class loader, the method delegates to {@link
2166      * ClassLoader#getSystemResource}.
2167      *
2168      * <p> Before delegation, an absolute resource name is constructed from the
2169      * given resource name using this algorithm:
2170      *
2171      * <ul>
2172      *
2173      * <li> If the {@code name} begins with a {@code '/'}
2174      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
2175      * portion of the {@code name} following the {@code '/'}.
2176      *
2177      * <li> Otherwise, the absolute name is of the following form:
2178      *
2179      * <blockquote>
2180      *   {@code modified_package_name/name}
2181      * </blockquote>
2182      *
2183      * <p> Where the {@code modified_package_name} is the package name of this
2184      * object with {@code '/'} substituted for {@code '.'}
2185      * (<tt>'&#92;u002e'</tt>).
2186      *
2187      * </ul>
2188      *
2189      * @param  name name of the desired resource
2190      * @return      A  {@link java.net.URL} object or {@code null} if no
2191      *              resource with this name is found
2192      * @since  JDK1.1
2193      */
2194     public java.net.URL getResource(String name) {
2195         name = resolveName(name);
2196         ClassLoader cl = getClassLoader0();
2197         if (cl==null) {
2198             // A system class.
2199             return ClassLoader.getSystemResource(name);
2200         }
2201         return cl.getResource(name);
2202     }
2203 
2204 
2205 
2206     /** protection domain returned when the internal domain is null */
2207     private static java.security.ProtectionDomain allPermDomain;
2208 
2209 
2210     /**
2211      * Returns the {@code ProtectionDomain} of this class.  If there is a
2212      * security manager installed, this method first calls the security
2213      * manager's {@code checkPermission} method with a
2214      * {@code RuntimePermission("getProtectionDomain")} permission to
2215      * ensure it's ok to get the
2216      * {@code ProtectionDomain}.
2217      *
2218      * @return the ProtectionDomain of this class
2219      *
2220      * @throws SecurityException
2221      *        if a security manager exists and its
2222      *        {@code checkPermission} method doesn't allow
2223      *        getting the ProtectionDomain.
2224      *
2225      * @see java.security.ProtectionDomain
2226      * @see SecurityManager#checkPermission
2227      * @see java.lang.RuntimePermission
2228      * @since 1.2
2229      */
2230     public java.security.ProtectionDomain getProtectionDomain() {
2231         SecurityManager sm = System.getSecurityManager();
2232         if (sm != null) {
2233             sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
2234         }
2235         java.security.ProtectionDomain pd = getProtectionDomain0();
2236         if (pd == null) {
2237             if (allPermDomain == null) {
2238                 java.security.Permissions perms =
2239                     new java.security.Permissions();
2240                 perms.add(SecurityConstants.ALL_PERMISSION);
2241                 allPermDomain =
2242                     new java.security.ProtectionDomain(null, perms);
2243             }
2244             pd = allPermDomain;
2245         }
2246         return pd;
2247     }
2248 
2249 
2250     /**
2251      * Returns the ProtectionDomain of this class.
2252      */
2253     private native java.security.ProtectionDomain getProtectionDomain0();
2254 
2255     /*
2256      * Return the Virtual Machine's Class object for the named
2257      * primitive type.
2258      */
2259     static native Class<?> getPrimitiveClass(String name);
2260 
2261     /*
2262      * Check if client is allowed to access members.  If access is denied,
2263      * throw a SecurityException.
2264      *
2265      * This method also enforces package access.
2266      *
2267      * <p> Default policy: allow all clients access with normal Java access
2268      * control.
2269      */
2270     private void checkMemberAccess(int which, Class<?> caller, boolean checkProxyInterfaces) {
2271         final SecurityManager s = System.getSecurityManager();
2272         if (s != null) {
2273             /* Default policy allows access to all {@link Member#PUBLIC} members,
2274              * as well as access to classes that have the same class loader as the caller.
2275              * In all other cases, it requires RuntimePermission("accessDeclaredMembers")
2276              * permission.
2277              */
2278             final ClassLoader ccl = ClassLoader.getClassLoader(caller);
2279             final ClassLoader cl = getClassLoader0();
2280             if (which != Member.PUBLIC) {
2281                 if (ccl != cl) {
2282                     s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
2283                 }
2284             }
2285             this.checkPackageAccess(ccl, checkProxyInterfaces);
2286         }
2287     }
2288 
2289     /*
2290      * Checks if a client loaded in ClassLoader ccl is allowed to access this
2291      * class under the current package access policy. If access is denied,
2292      * throw a SecurityException.
2293      */
2294     private void checkPackageAccess(final ClassLoader ccl, boolean checkProxyInterfaces) {
2295         final SecurityManager s = System.getSecurityManager();
2296         if (s != null) {
2297             final ClassLoader cl = getClassLoader0();
2298 
2299             if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
2300                 String name = this.getName();
2301                 int i = name.lastIndexOf('.');
2302                 if (i != -1) {
2303                     // skip the package access check on a proxy class in default proxy package
2304                     String pkg = name.substring(0, i);
2305                     if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {
2306                         s.checkPackageAccess(pkg);
2307                     }
2308                 }
2309             }
2310             // check package access on the proxy interfaces
2311             if (checkProxyInterfaces && Proxy.isProxyClass(this)) {
2312                 ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());
2313             }
2314         }
2315     }
2316 
2317     /**
2318      * Add a package name prefix if the name is not absolute Remove leading "/"
2319      * if name is absolute
2320      */
2321     private String resolveName(String name) {
2322         if (name == null) {
2323             return name;
2324         }
2325         if (!name.startsWith("/")) {
2326             Class<?> c = this;
2327             while (c.isArray()) {
2328                 c = c.getComponentType();
2329             }
2330             String baseName = c.getName();
2331             int index = baseName.lastIndexOf('.');
2332             if (index != -1) {
2333                 name = baseName.substring(0, index).replace('.', '/')
2334                     +"/"+name;
2335             }
2336         } else {
2337             name = name.substring(1);
2338         }
2339         return name;
2340     }
2341 
2342     /**
2343      * Reflection support.
2344      */
2345 
2346     // Caches for certain reflective results
2347     private static boolean useCaches = true;
2348 
2349     // reflection data that might get invalidated when JVM TI RedefineClasses() is called
2350     static class ReflectionData<T> {
2351         volatile Field[] declaredFields;
2352         volatile Field[] publicFields;
2353         volatile Method[] declaredMethods;
2354         volatile Method[] publicMethods;
2355         volatile Constructor<T>[] declaredConstructors;
2356         volatile Constructor<T>[] publicConstructors;
2357         // Intermediate results for getFields and getMethods
2358         volatile Field[] declaredPublicFields;
2359         volatile Method[] declaredPublicMethods;
2360         volatile Class<?>[] interfaces;
2361 
2362         // Value of classRedefinedCount when we created this ReflectionData instance
2363         final int redefinedCount;
2364 
2365         ReflectionData(int redefinedCount) {
2366             this.redefinedCount = redefinedCount;
2367         }
2368 
2369         // initialize Unsafe machinery here, since we need to call Class.class instance method
2370         // and have to avoid calling it in the static initializer of the Class class...
2371         private static final Unsafe unsafe;
2372         // offset of Class.reflectionData instance field
2373         private static final long reflectionDataOffset;
2374 
2375         static {
2376             unsafe = Unsafe.getUnsafe();
2377             // bypass caches
2378             Field reflectionDataField = searchFields(Class.class.getDeclaredFields0(false),
2379                                                      "reflectionData");
2380             if (reflectionDataField == null) {
2381                 throw new Error("No reflectionData field found in java.lang.Class");
2382             }
2383             reflectionDataOffset = unsafe.objectFieldOffset(reflectionDataField);
2384         }
2385 
2386         static <T> boolean compareAndSwap(Class<?> clazz,
2387                                           SoftReference<ReflectionData<T>> oldData,
2388                                           SoftReference<ReflectionData<T>> newData) {
2389             return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData);
2390         }
2391     }
2392 
2393     private volatile transient SoftReference<ReflectionData<T>> reflectionData;
2394 
2395     // Incremented by the VM on each call to JVM TI RedefineClasses()
2396     // that redefines this class or a superclass.
2397     private volatile transient int classRedefinedCount = 0;
2398 
2399     // Lazily create and cache ReflectionData
2400     private ReflectionData<T> reflectionData() {
2401         SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
2402         int classRedefinedCount = this.classRedefinedCount;
2403         ReflectionData<T> rd;
2404         if (useCaches &&
2405             reflectionData != null &&
2406             (rd = reflectionData.get()) != null &&
2407             rd.redefinedCount == classRedefinedCount) {
2408             return rd;
2409         }
2410         // else no SoftReference or cleared SoftReference or stale ReflectionData
2411         // -> create and replace new instance
2412         return newReflectionData(reflectionData, classRedefinedCount);
2413     }
2414 
2415     private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
2416                                                 int classRedefinedCount) {
2417         if (!useCaches) return null;
2418 
2419         while (true) {
2420             ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
2421             // try to CAS it...
2422             if (ReflectionData.compareAndSwap(this, oldReflectionData, new SoftReference<>(rd))) {
2423                 return rd;
2424             }
2425             // else retry
2426             oldReflectionData = this.reflectionData;
2427             classRedefinedCount = this.classRedefinedCount;
2428             if (oldReflectionData != null &&
2429                 (rd = oldReflectionData.get()) != null &&
2430                 rd.redefinedCount == classRedefinedCount) {
2431                 return rd;
2432             }
2433         }
2434     }
2435 
2436     // Generic signature handling
2437     private native String getGenericSignature0();
2438 
2439     // Generic info repository; lazily initialized
2440     private volatile transient ClassRepository genericInfo;
2441 
2442     // accessor for factory
2443     private GenericsFactory getFactory() {
2444         // create scope and factory
2445         return CoreReflectionFactory.make(this, ClassScope.make(this));
2446     }
2447 
2448     // accessor for generic info repository;
2449     // generic info is lazily initialized
2450     private ClassRepository getGenericInfo() {
2451         ClassRepository genericInfo = this.genericInfo;
2452         if (genericInfo == null) {
2453             String signature = getGenericSignature0();
2454             if (signature == null) {
2455                 genericInfo = ClassRepository.NONE;
2456             } else {
2457                 genericInfo = ClassRepository.make(signature, getFactory());
2458             }
2459             this.genericInfo = genericInfo;
2460         }
2461         return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
2462     }
2463 
2464     // Annotations handling
2465     private native byte[] getRawAnnotations();
2466     // Since 1.8
2467     native byte[] getRawTypeAnnotations();
2468     static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
2469         return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
2470     }
2471 
2472     native ConstantPool getConstantPool();
2473 
2474     //
2475     //
2476     // java.lang.reflect.Field handling
2477     //
2478     //
2479 
2480     // Returns an array of "root" fields. These Field objects must NOT
2481     // be propagated to the outside world, but must instead be copied
2482     // via ReflectionFactory.copyField.
2483     private Field[] privateGetDeclaredFields(boolean publicOnly) {
2484         checkInitted();
2485         Field[] res;
2486         ReflectionData<T> rd = reflectionData();
2487         if (rd != null) {
2488             res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
2489             if (res != null) return res;
2490         }
2491         // No cached value available; request value from VM
2492         res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
2493         if (rd != null) {
2494             if (publicOnly) {
2495                 rd.declaredPublicFields = res;
2496             } else {
2497                 rd.declaredFields = res;
2498             }
2499         }
2500         return res;
2501     }
2502 
2503     // Returns an array of "root" fields. These Field objects must NOT
2504     // be propagated to the outside world, but must instead be copied
2505     // via ReflectionFactory.copyField.
2506     private Field[] privateGetPublicFields(Set<Class<?>> traversedInterfaces) {
2507         checkInitted();
2508         Field[] res;
2509         ReflectionData<T> rd = reflectionData();
2510         if (rd != null) {
2511             res = rd.publicFields;
2512             if (res != null) return res;
2513         }
2514 
2515         // No cached value available; compute value recursively.
2516         // Traverse in correct order for getField().
2517         List<Field> fields = new ArrayList<>();
2518         if (traversedInterfaces == null) {
2519             traversedInterfaces = new HashSet<>();
2520         }
2521 
2522         // Local fields
2523         Field[] tmp = privateGetDeclaredFields(true);
2524         addAll(fields, tmp);
2525 
2526         // Direct superinterfaces, recursively
2527         for (Class<?> c : getInterfaces()) {
2528             if (!traversedInterfaces.contains(c)) {
2529                 traversedInterfaces.add(c);
2530                 addAll(fields, c.privateGetPublicFields(traversedInterfaces));
2531             }
2532         }
2533 
2534         // Direct superclass, recursively
2535         if (!isInterface()) {
2536             Class<?> c = getSuperclass();
2537             if (c != null) {
2538                 addAll(fields, c.privateGetPublicFields(traversedInterfaces));
2539             }
2540         }
2541 
2542         res = new Field[fields.size()];
2543         fields.toArray(res);
2544         if (rd != null) {
2545             rd.publicFields = res;
2546         }
2547         return res;
2548     }
2549 
2550     private static void addAll(Collection<Field> c, Field[] o) {
2551         for (int i = 0; i < o.length; i++) {
2552             c.add(o[i]);
2553         }
2554     }
2555 
2556 
2557     //
2558     //
2559     // java.lang.reflect.Constructor handling
2560     //
2561     //
2562 
2563     // Returns an array of "root" constructors. These Constructor
2564     // objects must NOT be propagated to the outside world, but must
2565     // instead be copied via ReflectionFactory.copyConstructor.
2566     private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
2567         checkInitted();
2568         Constructor<T>[] res;
2569         ReflectionData<T> rd = reflectionData();
2570         if (rd != null) {
2571             res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
2572             if (res != null) return res;
2573         }
2574         // No cached value available; request value from VM
2575         if (isInterface()) {
2576             @SuppressWarnings("unchecked")
2577             Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
2578             res = temporaryRes;
2579         } else {
2580             res = getDeclaredConstructors0(publicOnly);
2581         }
2582         if (rd != null) {
2583             if (publicOnly) {
2584                 rd.publicConstructors = res;
2585             } else {
2586                 rd.declaredConstructors = res;
2587             }
2588         }
2589         return res;
2590     }
2591 
2592     //
2593     //
2594     // java.lang.reflect.Method handling
2595     //
2596     //
2597 
2598     // Returns an array of "root" methods. These Method objects must NOT
2599     // be propagated to the outside world, but must instead be copied
2600     // via ReflectionFactory.copyMethod.
2601     private Method[] privateGetDeclaredMethods(boolean publicOnly) {
2602         checkInitted();
2603         Method[] res;
2604         ReflectionData<T> rd = reflectionData();
2605         if (rd != null) {
2606             res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
2607             if (res != null) return res;
2608         }
2609         // No cached value available; request value from VM
2610         res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
2611         if (rd != null) {
2612             if (publicOnly) {
2613                 rd.declaredPublicMethods = res;
2614             } else {
2615                 rd.declaredMethods = res;
2616             }
2617         }
2618         return res;
2619     }
2620 
2621     static class MethodArray {
2622         private Method[] methods;
2623         private int length;
2624 
2625         MethodArray() {
2626             methods = new Method[20];
2627             length = 0;
2628         }
2629 
2630         void add(Method m) {
2631             if (length == methods.length) {
2632                 methods = Arrays.copyOf(methods, 2 * methods.length);
2633             }
2634             methods[length++] = m;
2635         }
2636 
2637         void addAll(Method[] ma) {
2638             for (int i = 0; i < ma.length; i++) {
2639                 add(ma[i]);
2640             }
2641         }
2642 
2643         void addAll(MethodArray ma) {
2644             for (int i = 0; i < ma.length(); i++) {
2645                 add(ma.get(i));
2646             }
2647         }
2648 
2649         void addIfNotPresent(Method newMethod) {
2650             for (int i = 0; i < length; i++) {
2651                 Method m = methods[i];
2652                 if (m == newMethod || (m != null && m.equals(newMethod))) {
2653                     return;
2654                 }
2655             }
2656             add(newMethod);
2657         }
2658 
2659         void addAllIfNotPresent(MethodArray newMethods) {
2660             for (int i = 0; i < newMethods.length(); i++) {
2661                 Method m = newMethods.get(i);
2662                 if (m != null) {
2663                     addIfNotPresent(m);
2664                 }
2665             }
2666         }
2667 
2668         int length() {
2669             return length;
2670         }
2671 
2672         Method get(int i) {
2673             return methods[i];
2674         }
2675 
2676         void removeByNameAndSignature(Method toRemove) {
2677             for (int i = 0; i < length; i++) {
2678                 Method m = methods[i];
2679                 if (m != null &&
2680                     m.getReturnType() == toRemove.getReturnType() &&
2681                     m.getName() == toRemove.getName() &&
2682                     arrayContentsEq(m.getParameterTypes(),
2683                                     toRemove.getParameterTypes())) {
2684                     methods[i] = null;
2685                 }
2686             }
2687         }
2688 
2689         void compactAndTrim() {
2690             int newPos = 0;
2691             // Get rid of null slots
2692             for (int pos = 0; pos < length; pos++) {
2693                 Method m = methods[pos];
2694                 if (m != null) {
2695                     if (pos != newPos) {
2696                         methods[newPos] = m;
2697                     }
2698                     newPos++;
2699                 }
2700             }
2701             if (newPos != methods.length) {
2702                 methods = Arrays.copyOf(methods, newPos);
2703             }
2704         }
2705 
2706         Method[] getArray() {
2707             return methods;
2708         }
2709     }
2710 
2711 
2712     // Returns an array of "root" methods. These Method objects must NOT
2713     // be propagated to the outside world, but must instead be copied
2714     // via ReflectionFactory.copyMethod.
2715     private Method[] privateGetPublicMethods() {
2716         checkInitted();
2717         Method[] res;
2718         ReflectionData<T> rd = reflectionData();
2719         if (rd != null) {
2720             res = rd.publicMethods;
2721             if (res != null) return res;
2722         }
2723 
2724         // No cached value available; compute value recursively.
2725         // Start by fetching public declared methods
2726         MethodArray methods = new MethodArray();
2727         {
2728             Method[] tmp = privateGetDeclaredMethods(true);
2729             methods.addAll(tmp);
2730         }
2731         // Now recur over superclass and direct superinterfaces.
2732         // Go over superinterfaces first so we can more easily filter
2733         // out concrete implementations inherited from superclasses at
2734         // the end.
2735         MethodArray inheritedMethods = new MethodArray();
2736         Class<?>[] interfaces = getInterfaces();
2737         for (int i = 0; i < interfaces.length; i++) {
2738             inheritedMethods.addAll(interfaces[i].privateGetPublicMethods());
2739         }
2740         if (!isInterface()) {
2741             Class<?> c = getSuperclass();
2742             if (c != null) {
2743                 MethodArray supers = new MethodArray();
2744                 supers.addAll(c.privateGetPublicMethods());
2745                 // Filter out concrete implementations of any
2746                 // interface methods
2747                 for (int i = 0; i < supers.length(); i++) {
2748                     Method m = supers.get(i);
2749                     if (m != null && !Modifier.isAbstract(m.getModifiers())) {
2750                         inheritedMethods.removeByNameAndSignature(m);
2751                     }
2752                 }
2753                 // Insert superclass's inherited methods before
2754                 // superinterfaces' to satisfy getMethod's search
2755                 // order
2756                 supers.addAll(inheritedMethods);
2757                 inheritedMethods = supers;
2758             }
2759         }
2760         // Filter out all local methods from inherited ones
2761         for (int i = 0; i < methods.length(); i++) {
2762             Method m = methods.get(i);
2763             inheritedMethods.removeByNameAndSignature(m);
2764         }
2765         methods.addAllIfNotPresent(inheritedMethods);
2766         methods.compactAndTrim();
2767         res = methods.getArray();
2768         if (rd != null) {
2769             rd.publicMethods = res;
2770         }
2771         return res;
2772     }
2773 
2774 
2775     //
2776     // Helpers for fetchers of one field, method, or constructor
2777     //
2778 
2779     private static Field searchFields(Field[] fields, String name) {
2780         String internedName = name.intern();
2781         for (int i = 0; i < fields.length; i++) {
2782             if (fields[i].getName() == internedName) {
2783                 return getReflectionFactory().copyField(fields[i]);
2784             }
2785         }
2786         return null;
2787     }
2788 
2789     private Field getField0(String name) throws NoSuchFieldException {
2790         // Note: the intent is that the search algorithm this routine
2791         // uses be equivalent to the ordering imposed by
2792         // privateGetPublicFields(). It fetches only the declared
2793         // public fields for each class, however, to reduce the number
2794         // of Field objects which have to be created for the common
2795         // case where the field being requested is declared in the
2796         // class which is being queried.
2797         Field res;
2798         // Search declared public fields
2799         if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
2800             return res;
2801         }
2802         // Direct superinterfaces, recursively
2803         Class<?>[] interfaces = getInterfaces();
2804         for (int i = 0; i < interfaces.length; i++) {
2805             Class<?> c = interfaces[i];
2806             if ((res = c.getField0(name)) != null) {
2807                 return res;
2808             }
2809         }
2810         // Direct superclass, recursively
2811         if (!isInterface()) {
2812             Class<?> c = getSuperclass();
2813             if (c != null) {
2814                 if ((res = c.getField0(name)) != null) {
2815                     return res;
2816                 }
2817             }
2818         }
2819         return null;
2820     }
2821 
2822     private static Method searchMethods(Method[] methods,
2823                                         String name,
2824                                         Class<?>[] parameterTypes)
2825     {
2826         Method res = null;
2827         String internedName = name.intern();
2828         for (int i = 0; i < methods.length; i++) {
2829             Method m = methods[i];
2830             if (m.getName() == internedName
2831                 && arrayContentsEq(parameterTypes, m.getParameterTypes())
2832                 && (res == null
2833                     || res.getReturnType().isAssignableFrom(m.getReturnType())))
2834                 res = m;
2835         }
2836 
2837         return (res == null ? res : getReflectionFactory().copyMethod(res));
2838     }
2839 
2840 
2841     private Method getMethod0(String name, Class<?>[] parameterTypes) {
2842         // Note: the intent is that the search algorithm this routine
2843         // uses be equivalent to the ordering imposed by
2844         // privateGetPublicMethods(). It fetches only the declared
2845         // public methods for each class, however, to reduce the
2846         // number of Method objects which have to be created for the
2847         // common case where the method being requested is declared in
2848         // the class which is being queried.
2849         Method res;
2850         // Search declared public methods
2851         if ((res = searchMethods(privateGetDeclaredMethods(true),
2852                                  name,
2853                                  parameterTypes)) != null) {
2854             return res;
2855         }
2856         // Search superclass's methods
2857         if (!isInterface()) {
2858             Class<? super T> c = getSuperclass();
2859             if (c != null) {
2860                 if ((res = c.getMethod0(name, parameterTypes)) != null) {
2861                     return res;
2862                 }
2863             }
2864         }
2865         // Search superinterfaces' methods
2866         Class<?>[] interfaces = getInterfaces();
2867         for (int i = 0; i < interfaces.length; i++) {
2868             Class<?> c = interfaces[i];
2869             if ((res = c.getMethod0(name, parameterTypes)) != null) {
2870                 return res;
2871             }
2872         }
2873         // Not found
2874         return null;
2875     }
2876 
2877     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
2878                                         int which) throws NoSuchMethodException
2879     {
2880         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
2881         for (Constructor<T> constructor : constructors) {
2882             if (arrayContentsEq(parameterTypes,
2883                                 constructor.getParameterTypes())) {
2884                 return getReflectionFactory().copyConstructor(constructor);
2885             }
2886         }
2887         throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
2888     }
2889 
2890     //
2891     // Other helpers and base implementation
2892     //
2893 
2894     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
2895         if (a1 == null) {
2896             return a2 == null || a2.length == 0;
2897         }
2898 
2899         if (a2 == null) {
2900             return a1.length == 0;
2901         }
2902 
2903         if (a1.length != a2.length) {
2904             return false;
2905         }
2906 
2907         for (int i = 0; i < a1.length; i++) {
2908             if (a1[i] != a2[i]) {
2909                 return false;
2910             }
2911         }
2912 
2913         return true;
2914     }
2915 
2916     private static Field[] copyFields(Field[] arg) {
2917         Field[] out = new Field[arg.length];
2918         ReflectionFactory fact = getReflectionFactory();
2919         for (int i = 0; i < arg.length; i++) {
2920             out[i] = fact.copyField(arg[i]);
2921         }
2922         return out;
2923     }
2924 
2925     private static Method[] copyMethods(Method[] arg) {
2926         Method[] out = new Method[arg.length];
2927         ReflectionFactory fact = getReflectionFactory();
2928         for (int i = 0; i < arg.length; i++) {
2929             out[i] = fact.copyMethod(arg[i]);
2930         }
2931         return out;
2932     }
2933 
2934     private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
2935         Constructor<U>[] out = arg.clone();
2936         ReflectionFactory fact = getReflectionFactory();
2937         for (int i = 0; i < out.length; i++) {
2938             out[i] = fact.copyConstructor(out[i]);
2939         }
2940         return out;
2941     }
2942 
2943     private native Field[]       getDeclaredFields0(boolean publicOnly);
2944     private native Method[]      getDeclaredMethods0(boolean publicOnly);
2945     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
2946     private native Class<?>[]   getDeclaredClasses0();
2947 
2948     private static String        argumentTypesToString(Class<?>[] argTypes) {
2949         StringBuilder buf = new StringBuilder();
2950         buf.append("(");
2951         if (argTypes != null) {
2952             for (int i = 0; i < argTypes.length; i++) {
2953                 if (i > 0) {
2954                     buf.append(", ");
2955                 }
2956                 Class<?> c = argTypes[i];
2957                 buf.append((c == null) ? "null" : c.getName());
2958             }
2959         }
2960         buf.append(")");
2961         return buf.toString();
2962     }
2963 
2964     /** use serialVersionUID from JDK 1.1 for interoperability */
2965     private static final long serialVersionUID = 3206093459760846163L;
2966 
2967 
2968     /**
2969      * Class Class is special cased within the Serialization Stream Protocol.
2970      *
2971      * A Class instance is written initially into an ObjectOutputStream in the
2972      * following format:
2973      * <pre>
2974      *      {@code TC_CLASS} ClassDescriptor
2975      *      A ClassDescriptor is a special cased serialization of
2976      *      a {@code java.io.ObjectStreamClass} instance.
2977      * </pre>
2978      * A new handle is generated for the initial time the class descriptor
2979      * is written into the stream. Future references to the class descriptor
2980      * are written as references to the initial class descriptor instance.
2981      *
2982      * @see java.io.ObjectStreamClass
2983      */
2984     private static final ObjectStreamField[] serialPersistentFields =
2985         new ObjectStreamField[0];
2986 
2987 
2988     /**
2989      * Returns the assertion status that would be assigned to this
2990      * class if it were to be initialized at the time this method is invoked.
2991      * If this class has had its assertion status set, the most recent
2992      * setting will be returned; otherwise, if any package default assertion
2993      * status pertains to this class, the most recent setting for the most
2994      * specific pertinent package default assertion status is returned;
2995      * otherwise, if this class is not a system class (i.e., it has a
2996      * class loader) its class loader's default assertion status is returned;
2997      * otherwise, the system class default assertion status is returned.
2998      * <p>
2999      * Few programmers will have any need for this method; it is provided
3000      * for the benefit of the JRE itself.  (It allows a class to determine at
3001      * the time that it is initialized whether assertions should be enabled.)
3002      * Note that this method is not guaranteed to return the actual
3003      * assertion status that was (or will be) associated with the specified
3004      * class when it was (or will be) initialized.
3005      *
3006      * @return the desired assertion status of the specified class.
3007      * @see    java.lang.ClassLoader#setClassAssertionStatus
3008      * @see    java.lang.ClassLoader#setPackageAssertionStatus
3009      * @see    java.lang.ClassLoader#setDefaultAssertionStatus
3010      * @since  1.4
3011      */
3012     public boolean desiredAssertionStatus() {
3013         ClassLoader loader = getClassLoader();
3014         // If the loader is null this is a system class, so ask the VM
3015         if (loader == null)
3016             return desiredAssertionStatus0(this);
3017 
3018         // If the classloader has been initialized with the assertion
3019         // directives, ask it. Otherwise, ask the VM.
3020         synchronized(loader.assertionLock) {
3021             if (loader.classAssertionStatus != null) {
3022                 return loader.desiredAssertionStatus(getName());
3023             }
3024         }
3025         return desiredAssertionStatus0(this);
3026     }
3027 
3028     // Retrieves the desired assertion status of this class from the VM
3029     private static native boolean desiredAssertionStatus0(Class<?> clazz);
3030 
3031     /**
3032      * Returns true if and only if this class was declared as an enum in the
3033      * source code.
3034      *
3035      * @return true if and only if this class was declared as an enum in the
3036      *     source code
3037      * @since 1.5
3038      */
3039     public boolean isEnum() {
3040         // An enum must both directly extend java.lang.Enum and have
3041         // the ENUM bit set; classes for specialized enum constants
3042         // don't do the former.
3043         return (this.getModifiers() & ENUM) != 0 &&
3044         this.getSuperclass() == java.lang.Enum.class;
3045     }
3046 
3047     // Fetches the factory for reflective objects
3048     private static ReflectionFactory getReflectionFactory() {
3049         if (reflectionFactory == null) {
3050             reflectionFactory =
3051                 java.security.AccessController.doPrivileged
3052                     (new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());
3053         }
3054         return reflectionFactory;
3055     }
3056     private static ReflectionFactory reflectionFactory;
3057 
3058     // To be able to query system properties as soon as they're available
3059     private static boolean initted = false;
3060     private static void checkInitted() {
3061         if (initted) return;
3062         AccessController.doPrivileged(new PrivilegedAction<Void>() {
3063                 public Void run() {
3064                     // Tests to ensure the system properties table is fully
3065                     // initialized. This is needed because reflection code is
3066                     // called very early in the initialization process (before
3067                     // command-line arguments have been parsed and therefore
3068                     // these user-settable properties installed.) We assume that
3069                     // if System.out is non-null then the System class has been
3070                     // fully initialized and that the bulk of the startup code
3071                     // has been run.
3072 
3073                     if (System.out == null) {
3074                         // java.lang.System not yet fully initialized
3075                         return null;
3076                     }
3077 
3078                     // Doesn't use Boolean.getBoolean to avoid class init.
3079                     String val =
3080                         System.getProperty("sun.reflect.noCaches");
3081                     if (val != null && val.equals("true")) {
3082                         useCaches = false;
3083                     }
3084 
3085                     initted = true;
3086                     return null;
3087                 }
3088             });
3089     }
3090 
3091     /**
3092      * Returns the elements of this enum class or null if this
3093      * Class object does not represent an enum type.
3094      *
3095      * @return an array containing the values comprising the enum class
3096      *     represented by this Class object in the order they're
3097      *     declared, or null if this Class object does not
3098      *     represent an enum type
3099      * @since 1.5
3100      */
3101     public T[] getEnumConstants() {
3102         T[] values = getEnumConstantsShared();
3103         return (values != null) ? values.clone() : null;
3104     }
3105 
3106     /**
3107      * Returns the elements of this enum class or null if this
3108      * Class object does not represent an enum type;
3109      * identical to getEnumConstants except that the result is
3110      * uncloned, cached, and shared by all callers.
3111      */
3112     T[] getEnumConstantsShared() {
3113         if (enumConstants == null) {
3114             if (!isEnum()) return null;
3115             try {
3116                 final Method values = getMethod("values");
3117                 java.security.AccessController.doPrivileged(
3118                     new java.security.PrivilegedAction<Void>() {
3119                         public Void run() {
3120                                 values.setAccessible(true);
3121                                 return null;
3122                             }
3123                         });
3124                 @SuppressWarnings("unchecked")
3125                 T[] temporaryConstants = (T[])values.invoke(null);
3126                 enumConstants = temporaryConstants;
3127             }
3128             // These can happen when users concoct enum-like classes
3129             // that don't comply with the enum spec.
3130             catch (InvocationTargetException | NoSuchMethodException |
3131                    IllegalAccessException ex) { return null; }
3132         }
3133         return enumConstants;
3134     }
3135     private volatile transient T[] enumConstants = null;
3136 
3137     /**
3138      * Returns a map from simple name to enum constant.  This package-private
3139      * method is used internally by Enum to implement
3140      * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}
3141      * efficiently.  Note that the map is returned by this method is
3142      * created lazily on first use.  Typically it won't ever get created.
3143      */
3144     Map<String, T> enumConstantDirectory() {
3145         if (enumConstantDirectory == null) {
3146             T[] universe = getEnumConstantsShared();
3147             if (universe == null)
3148                 throw new IllegalArgumentException(
3149                     getName() + " is not an enum type");
3150             Map<String, T> m = new HashMap<>(2 * universe.length);
3151             for (T constant : universe)
3152                 m.put(((Enum<?>)constant).name(), constant);
3153             enumConstantDirectory = m;
3154         }
3155         return enumConstantDirectory;
3156     }
3157     private volatile transient Map<String, T> enumConstantDirectory = null;
3158 
3159     /**
3160      * Casts an object to the class or interface represented
3161      * by this {@code Class} object.
3162      *
3163      * @param obj the object to be cast
3164      * @return the object after casting, or null if obj is null
3165      *
3166      * @throws ClassCastException if the object is not
3167      * null and is not assignable to the type T.
3168      *
3169      * @since 1.5
3170      */
3171     @SuppressWarnings("unchecked")
3172     public T cast(Object obj) {
3173         if (obj != null && !isInstance(obj))
3174             throw new ClassCastException(cannotCastMsg(obj));
3175         return (T) obj;
3176     }
3177 
3178     private String cannotCastMsg(Object obj) {
3179         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3180     }
3181 
3182     /**
3183      * Casts this {@code Class} object to represent a subclass of the class
3184      * represented by the specified class object.  Checks that the cast
3185      * is valid, and throws a {@code ClassCastException} if it is not.  If
3186      * this method succeeds, it always returns a reference to this class object.
3187      *
3188      * <p>This method is useful when a client needs to "narrow" the type of
3189      * a {@code Class} object to pass it to an API that restricts the
3190      * {@code Class} objects that it is willing to accept.  A cast would
3191      * generate a compile-time warning, as the correctness of the cast
3192      * could not be checked at runtime (because generic types are implemented
3193      * by erasure).
3194      *
3195      * @return this {@code Class} object, cast to represent a subclass of
3196      *    the specified class object.
3197      * @throws ClassCastException if this {@code Class} object does not
3198      *    represent a subclass of the specified class (here "subclass" includes
3199      *    the class itself).
3200      * @since 1.5
3201      */
3202     @SuppressWarnings("unchecked")
3203     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
3204         if (clazz.isAssignableFrom(this))
3205             return (Class<? extends U>) this;
3206         else
3207             throw new ClassCastException(this.toString());
3208     }
3209 
3210     /**
3211      * @throws NullPointerException {@inheritDoc}
3212      * @since 1.5
3213      */
3214     @SuppressWarnings("unchecked")
3215     public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
3216         Objects.requireNonNull(annotationClass);
3217 
3218         initAnnotationsIfNecessary();
3219         return (A) annotations.get(annotationClass);
3220     }
3221 
3222     /**
3223      * {@inheritDoc}
3224      * @throws NullPointerException {@inheritDoc}
3225      * @since 1.5
3226      */
3227     @Override
3228     public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
3229         return GenericDeclaration.super.isAnnotationPresent(annotationClass);
3230     }
3231 
3232     /**
3233      * @throws NullPointerException {@inheritDoc}
3234      * @since 1.8
3235      */
3236     @Override
3237     public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {
3238         Objects.requireNonNull(annotationClass);
3239 
3240         initAnnotationsIfNecessary();
3241         return AnnotationSupport.getMultipleAnnotations(annotations, annotationClass);
3242     }
3243 
3244     /**
3245      * @since 1.5
3246      */
3247     public Annotation[] getAnnotations() {
3248         initAnnotationsIfNecessary();
3249         return AnnotationParser.toArray(annotations);
3250     }
3251 
3252     /**
3253      * @throws NullPointerException {@inheritDoc}
3254      * @since 1.8
3255      */
3256     @Override
3257     @SuppressWarnings("unchecked")
3258     public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
3259         Objects.requireNonNull(annotationClass);
3260 
3261         initAnnotationsIfNecessary();
3262         return (A) declaredAnnotations.get(annotationClass);
3263     }
3264 
3265     /**
3266      * @throws NullPointerException {@inheritDoc}
3267      * @since 1.8
3268      */
3269     @Override
3270     public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {
3271         Objects.requireNonNull(annotationClass);
3272 
3273         initAnnotationsIfNecessary();
3274         return AnnotationSupport.getMultipleAnnotations(declaredAnnotations, annotationClass);
3275     }
3276 
3277     /**
3278      * @since 1.5
3279      */
3280     public Annotation[] getDeclaredAnnotations()  {
3281         initAnnotationsIfNecessary();
3282         return AnnotationParser.toArray(declaredAnnotations);
3283     }
3284 
3285     // Annotations cache
3286     private transient Map<Class<? extends Annotation>, Annotation> annotations;
3287     private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
3288     // Value of classRedefinedCount when we last cleared the cached annotations and declaredAnnotations fields
3289     private  transient int lastAnnotationsRedefinedCount = 0;
3290 
3291     // Clears cached values that might possibly have been obsoleted by
3292     // a class redefinition.
3293     private void clearAnnotationCachesOnClassRedefinition() {
3294         if (lastAnnotationsRedefinedCount != classRedefinedCount) {
3295             annotations = declaredAnnotations = null;
3296             lastAnnotationsRedefinedCount = classRedefinedCount;
3297         }
3298     }
3299 
3300     private synchronized void initAnnotationsIfNecessary() {
3301         clearAnnotationCachesOnClassRedefinition();
3302         if (annotations != null)
3303             return;
3304         declaredAnnotations = AnnotationParser.parseAnnotations(
3305             getRawAnnotations(), getConstantPool(), this);
3306         Class<?> superClass = getSuperclass();
3307         if (superClass == null) {
3308             annotations = declaredAnnotations;
3309         } else {
3310             annotations = new HashMap<>();
3311             superClass.initAnnotationsIfNecessary();
3312             for (Map.Entry<Class<? extends Annotation>, Annotation> e : superClass.annotations.entrySet()) {
3313                 Class<? extends Annotation> annotationClass = e.getKey();
3314                 if (AnnotationType.getInstance(annotationClass).isInherited())
3315                     annotations.put(annotationClass, e.getValue());
3316             }
3317             annotations.putAll(declaredAnnotations);
3318         }
3319     }
3320 
3321     // Annotation types cache their internal (AnnotationType) form
3322 
3323     private AnnotationType annotationType;
3324 
3325     void setAnnotationType(AnnotationType type) {
3326         annotationType = type;
3327     }
3328 
3329     AnnotationType getAnnotationType() {
3330         return annotationType;
3331     }
3332 
3333     /* Backing store of user-defined values pertaining to this class.
3334      * Maintained by the ClassValue class.
3335      */
3336     transient ClassValue.ClassValueMap classValueMap;
3337 
3338     /**
3339      * Returns an AnnotatedType object that represents the use of a type to specify
3340      * the superclass of the entity represented by this Class. (The <em>use</em> of type
3341      * Foo to specify the superclass in '... extends Foo' is distinct from the
3342      * <em>declaration</em> of type Foo.)
3343      *
3344      * If this Class represents a class type whose declaration does not explicitly
3345      * indicate an annotated superclass, the return value is null.
3346      *
3347      * If this Class represents either the Object class, an interface type, an
3348      * array type, a primitive type, or void, the return value is null.
3349      *
3350      * @since 1.8
3351      */
3352     public AnnotatedType getAnnotatedSuperclass() {
3353          return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
3354 }
3355 
3356     /**
3357      * Returns an array of AnnotatedType objects that represent the use of types to
3358      * specify superinterfaces of the entity represented by this Class. (The <em>use</em>
3359      * of type Foo to specify a superinterface in '... implements Foo' is
3360      * distinct from the <em>declaration</em> of type Foo.)
3361      *
3362      * If this Class represents a class, the return value is an array
3363      * containing objects representing the uses of interface types to specify
3364      * interfaces implemented by the class. The order of the objects in the
3365      * array corresponds to the order of the interface types used in the
3366      * 'implements' clause of the declaration of this Class.
3367      *
3368      * If this Class represents an interface, the return value is an array
3369      * containing objects representing the uses of interface types to specify
3370      * interfaces directly extended by the interface. The order of the objects in
3371      * the array corresponds to the order of the interface types used in the
3372      * 'extends' clause of the declaration of this Class.
3373      *
3374      * If this Class represents a class or interface whose declaration does not
3375      * explicitly indicate any annotated superinterfaces, the return value is an
3376      * array of length 0.
3377      *
3378      * If this Class represents either the Object class, an array type, a
3379      * primitive type, or void, the return value is an array of length 0.
3380      *
3381      * @since 1.8
3382      */
3383     public AnnotatedType[] getAnnotatedInterfaces() {
3384          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3385     }
3386 }