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