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