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                         Class<?>[] members = currentClass.getDeclaredClasses();
1492                         for (int i = 0; i < members.length; i++) {
1493                             if (Modifier.isPublic(members[i].getModifiers())) {
1494                                 list.add(members[i]);
1495                             }
1496                         }
1497                         currentClass = currentClass.getSuperclass();
1498                     }
1499                     return list.toArray(new Class<?>[0]);
1500                 }
1501             });
1502     }
1503 
1504 
1505     /**
1506      * Returns an array containing {@code Field} objects reflecting all
1507      * the accessible public fields of the class or interface represented by
1508      * this {@code Class} object.
1509      *
1510      * <p> If this {@code Class} object represents a class or interface with no
1511      * no accessible public fields, then this method returns an array of length
1512      * 0.
1513      *
1514      * <p> If this {@code Class} object represents a class, then this method
1515      * returns the public fields of the class and of all its superclasses.
1516      *
1517      * <p> If this {@code Class} object represents an interface, then this
1518      * method returns the fields of the interface and of all its
1519      * superinterfaces.
1520      *
1521      * <p> If this {@code Class} object represents an array type, a primitive
1522      * type, or void, then this method returns an array of length 0.
1523      *
1524      * <p> The elements in the returned array are not sorted and are not in any
1525      * particular order.
1526      *
1527      * @return the array of {@code Field} objects representing the
1528      *         public fields
1529      * @throws SecurityException
1530      *         If a security manager, <i>s</i>, is present and
1531      *         the caller's class loader is not the same as or an
1532      *         ancestor of the class loader for the current class and
1533      *         invocation of {@link SecurityManager#checkPackageAccess
1534      *         s.checkPackageAccess()} denies access to the package
1535      *         of this class.
1536      *
1537      * @since JDK1.1
1538      * @jls 8.2 Class Members
1539      * @jls 8.3 Field Declarations
1540      */
1541     @CallerSensitive
1542     public Field[] getFields() throws SecurityException {
1543         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1544         return copyFields(privateGetPublicFields(null));
1545     }
1546 
1547 
1548     /**
1549      * Returns an array containing {@code Method} objects reflecting all the
1550      * public methods of the class or interface represented by this {@code
1551      * Class} object, including those declared by the class or interface and
1552      * those inherited from superclasses and superinterfaces.
1553      *
1554      * <p> If this {@code Class} object represents a type that has multiple
1555      * public methods with the same name and parameter types, but different
1556      * return types, then the returned array has a {@code Method} object for
1557      * each such method.
1558      *
1559      * <p> If this {@code Class} object represents a type with a class
1560      * initialization method {@code <clinit>}, then the returned array does
1561      * <em>not</em> have a corresponding {@code Method} object.
1562      *
1563      * <p> If this {@code Class} object represents an array type, then the
1564      * returned array has a {@code Method} object for each of the public
1565      * methods inherited by the array type from {@code Object}. It does not
1566      * contain a {@code Method} object for {@code clone()}.
1567      *
1568      * <p> If this {@code Class} object represents an interface then the
1569      * returned array does not contain any implicitly declared methods from
1570      * {@code Object}. Therefore, if no methods are explicitly declared in
1571      * this interface or any of its superinterfaces then the returned array
1572      * has length 0. (Note that a {@code Class} object which represents a class
1573      * always has public methods, inherited from {@code Object}.)
1574      *
1575      * <p> If this {@code Class} object represents a primitive type or void,
1576      * then the returned array has length 0.
1577      *
1578      * <p> Static methods declared in superinterfaces of the class or interface
1579      * represented by this {@code Class} object are not considered members of
1580      * the class or interface.
1581      *
1582      * <p> The elements in the returned array are not sorted and are not in any
1583      * particular order.
1584      *
1585      * @return the array of {@code Method} objects representing the
1586      *         public methods of this class
1587      * @throws SecurityException
1588      *         If a security manager, <i>s</i>, is present and
1589      *         the caller's class loader is not the same as or an
1590      *         ancestor of the class loader for the current class and
1591      *         invocation of {@link SecurityManager#checkPackageAccess
1592      *         s.checkPackageAccess()} denies access to the package
1593      *         of this class.
1594      *
1595      * @jls 8.2 Class Members
1596      * @jls 8.4 Method Declarations
1597      * @since JDK1.1
1598      */
1599     @CallerSensitive
1600     public Method[] getMethods() throws SecurityException {
1601         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1602         return copyMethods(privateGetPublicMethods());
1603     }
1604 
1605 
1606     /**
1607      * Returns an array containing {@code Constructor} objects reflecting
1608      * all the public constructors of the class represented by this
1609      * {@code Class} object.  An array of length 0 is returned if the
1610      * class has no public constructors, or if the class is an array class, or
1611      * if the class reflects a primitive type or void.
1612      *
1613      * Note that while this method returns an array of {@code
1614      * Constructor<T>} objects (that is an array of constructors from
1615      * this class), the return type of this method is {@code
1616      * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
1617      * might be expected.  This less informative return type is
1618      * necessary since after being returned from this method, the
1619      * array could be modified to hold {@code Constructor} objects for
1620      * different classes, which would violate the type guarantees of
1621      * {@code Constructor<T>[]}.
1622      *
1623      * @return the array of {@code Constructor} objects representing the
1624      *         public constructors of this class
1625      * @throws SecurityException
1626      *         If a security manager, <i>s</i>, is present and
1627      *         the caller's class loader is not the same as or an
1628      *         ancestor of the class loader for the current class and
1629      *         invocation of {@link SecurityManager#checkPackageAccess
1630      *         s.checkPackageAccess()} denies access to the package
1631      *         of this class.
1632      *
1633      * @since JDK1.1
1634      */
1635     @CallerSensitive
1636     public Constructor<?>[] getConstructors() throws SecurityException {
1637         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1638         return copyConstructors(privateGetDeclaredConstructors(true));
1639     }
1640 
1641 
1642     /**
1643      * Returns a {@code Field} object that reflects the specified public member
1644      * field of the class or interface represented by this {@code Class}
1645      * object. The {@code name} parameter is a {@code String} specifying the
1646      * simple name of the desired field.
1647      *
1648      * <p> The field to be reflected is determined by the algorithm that
1649      * follows.  Let C be the class or interface represented by this object:
1650      *
1651      * <OL>
1652      * <LI> If C declares a public field with the name specified, that is the
1653      *      field to be reflected.</LI>
1654      * <LI> If no field was found in step 1 above, this algorithm is applied
1655      *      recursively to each direct superinterface of C. The direct
1656      *      superinterfaces are searched in the order they were declared.</LI>
1657      * <LI> If no field was found in steps 1 and 2 above, and C has a
1658      *      superclass S, then this algorithm is invoked recursively upon S.
1659      *      If C has no superclass, then a {@code NoSuchFieldException}
1660      *      is thrown.</LI>
1661      * </OL>
1662      *
1663      * <p> If this {@code Class} object represents an array type, then this
1664      * method does not find the {@code length} field of the array type.
1665      *
1666      * @param name the field name
1667      * @return the {@code Field} object of this class specified by
1668      *         {@code name}
1669      * @throws NoSuchFieldException if a field with the specified name is
1670      *         not found.
1671      * @throws NullPointerException if {@code name} is {@code null}
1672      * @throws SecurityException
1673      *         If a security manager, <i>s</i>, is present and
1674      *         the caller's class loader is not the same as or an
1675      *         ancestor of the class loader for the current class and
1676      *         invocation of {@link SecurityManager#checkPackageAccess
1677      *         s.checkPackageAccess()} denies access to the package
1678      *         of this class.
1679      *
1680      * @since JDK1.1
1681      * @jls 8.2 Class Members
1682      * @jls 8.3 Field Declarations
1683      */
1684     @CallerSensitive
1685     public Field getField(String name)
1686         throws NoSuchFieldException, SecurityException {
1687         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1688         Field field = getField0(name);
1689         if (field == null) {
1690             throw new NoSuchFieldException(name);
1691         }
1692         return field;
1693     }
1694 
1695 
1696     /**
1697      * Returns a {@code Method} object that reflects the specified public
1698      * member method of the class or interface represented by this
1699      * {@code Class} object. The {@code name} parameter is a
1700      * {@code String} specifying the simple name of the desired method. The
1701      * {@code parameterTypes} parameter is an array of {@code Class}
1702      * objects that identify the method's formal parameter types, in declared
1703      * order. If {@code parameterTypes} is {@code null}, it is
1704      * treated as if it were an empty array.
1705      *
1706      * <p> If the {@code name} is "{@code <init>}" or "{@code <clinit>}" a
1707      * {@code NoSuchMethodException} is raised. Otherwise, the method to
1708      * be reflected is determined by the algorithm that follows.  Let C be the
1709      * class or interface represented by this object:
1710      * <OL>
1711      * <LI> C is searched for a <I>matching method</I>, as defined below. If a
1712      *      matching method is found, it is reflected.</LI>
1713      * <LI> If no matching method is found by step 1 then:
1714      *   <OL TYPE="a">
1715      *   <LI> If C is a class other than {@code Object}, then this algorithm is
1716      *        invoked recursively on the superclass of C.</LI>
1717      *   <LI> If C is the class {@code Object}, or if C is an interface, then
1718      *        the superinterfaces of C (if any) are searched for a matching
1719      *        method. If any such method is found, it is reflected.</LI>
1720      *   </OL></LI>
1721      * </OL>
1722      *
1723      * <p> To find a matching method in a class or interface C:&nbsp; If C
1724      * declares exactly one public method with the specified name and exactly
1725      * the same formal parameter types, that is the method reflected. If more
1726      * than one such method is found in C, and one of these methods has a
1727      * return type that is more specific than any of the others, that method is
1728      * reflected; otherwise one of the methods is chosen arbitrarily.
1729      *
1730      * <p>Note that there may be more than one matching method in a
1731      * class because while the Java language forbids a class to
1732      * declare multiple methods with the same signature but different
1733      * return types, the Java virtual machine does not.  This
1734      * increased flexibility in the virtual machine can be used to
1735      * implement various language features.  For example, covariant
1736      * returns can be implemented with {@linkplain
1737      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
1738      * method and the method being overridden would have the same
1739      * signature but different return types.
1740      *
1741      * <p> If this {@code Class} object represents an array type, then this
1742      * method does not find the {@code clone()} method.
1743      *
1744      * <p> Static methods declared in superinterfaces of the class or interface
1745      * represented by this {@code Class} object are not considered members of
1746      * the class or interface.
1747      *
1748      * @param name the name of the method
1749      * @param parameterTypes the list of parameters
1750      * @return the {@code Method} object that matches the specified
1751      *         {@code name} and {@code parameterTypes}
1752      * @throws NoSuchMethodException if a matching method is not found
1753      *         or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
1754      * @throws NullPointerException if {@code name} is {@code null}
1755      * @throws SecurityException
1756      *         If a security manager, <i>s</i>, is present and
1757      *         the caller's class loader is not the same as or an
1758      *         ancestor of the class loader for the current class and
1759      *         invocation of {@link SecurityManager#checkPackageAccess
1760      *         s.checkPackageAccess()} denies access to the package
1761      *         of this class.
1762      *
1763      * @jls 8.2 Class Members
1764      * @jls 8.4 Method Declarations
1765      * @since JDK1.1
1766      */
1767     @CallerSensitive
1768     public Method getMethod(String name, Class<?>... parameterTypes)
1769         throws NoSuchMethodException, SecurityException {
1770         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1771         Method method = getMethod0(name, parameterTypes, true);
1772         if (method == null) {
1773             throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
1774         }
1775         return method;
1776     }
1777 
1778 
1779     /**
1780      * Returns a {@code Constructor} object that reflects the specified
1781      * public constructor of the class represented by this {@code Class}
1782      * object. The {@code parameterTypes} parameter is an array of
1783      * {@code Class} objects that identify the constructor's formal
1784      * parameter types, in declared order.
1785      *
1786      * If this {@code Class} object represents an inner class
1787      * declared in a non-static context, the formal parameter types
1788      * include the explicit enclosing instance as the first parameter.
1789      *
1790      * <p> The constructor to reflect is the public constructor of the class
1791      * represented by this {@code Class} object whose formal parameter
1792      * types match those specified by {@code parameterTypes}.
1793      *
1794      * @param parameterTypes the parameter array
1795      * @return the {@code Constructor} object of the public constructor that
1796      *         matches the specified {@code parameterTypes}
1797      * @throws NoSuchMethodException if a matching method is not found.
1798      * @throws SecurityException
1799      *         If a security manager, <i>s</i>, is present and
1800      *         the caller's class loader is not the same as or an
1801      *         ancestor of the class loader for the current class and
1802      *         invocation of {@link SecurityManager#checkPackageAccess
1803      *         s.checkPackageAccess()} denies access to the package
1804      *         of this class.
1805      *
1806      * @since JDK1.1
1807      */
1808     @CallerSensitive
1809     public Constructor<T> getConstructor(Class<?>... parameterTypes)
1810         throws NoSuchMethodException, SecurityException {
1811         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1812         return getConstructor0(parameterTypes, Member.PUBLIC);
1813     }
1814 
1815 
1816     /**
1817      * Returns an array of {@code Class} objects reflecting all the
1818      * classes and interfaces declared as members of the class represented by
1819      * this {@code Class} object. This includes public, protected, default
1820      * (package) access, and private classes and interfaces declared by the
1821      * class, but excludes inherited classes and interfaces.  This method
1822      * returns an array of length 0 if the class declares no classes or
1823      * interfaces as members, or if this {@code Class} object represents a
1824      * primitive type, an array class, or void.
1825      *
1826      * @return the array of {@code Class} objects representing all the
1827      *         declared members of this class
1828      * @throws SecurityException
1829      *         If a security manager, <i>s</i>, is present and any of the
1830      *         following conditions is met:
1831      *
1832      *         <ul>
1833      *
1834      *         <li> the caller's class loader is not the same as the
1835      *         class loader of this class and invocation of
1836      *         {@link SecurityManager#checkPermission
1837      *         s.checkPermission} method with
1838      *         {@code RuntimePermission("accessDeclaredMembers")}
1839      *         denies access to the declared classes within this class
1840      *
1841      *         <li> the caller's class loader is not the same as or an
1842      *         ancestor of the class loader for the current class and
1843      *         invocation of {@link SecurityManager#checkPackageAccess
1844      *         s.checkPackageAccess()} denies access to the package
1845      *         of this class
1846      *
1847      *         </ul>
1848      *
1849      * @since JDK1.1
1850      */
1851     @CallerSensitive
1852     public Class<?>[] getDeclaredClasses() throws SecurityException {
1853         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), false);
1854         return getDeclaredClasses0();
1855     }
1856 
1857 
1858     /**
1859      * Returns an array of {@code Field} objects reflecting all the fields
1860      * declared by the class or interface represented by this
1861      * {@code Class} object. This includes public, protected, default
1862      * (package) access, and private fields, but excludes inherited fields.
1863      *
1864      * <p> If this {@code Class} object represents a class or interface with no
1865      * declared fields, then this method returns an array of length 0.
1866      *
1867      * <p> If this {@code Class} object represents an array type, a primitive
1868      * type, or void, then this method returns an array of length 0.
1869      *
1870      * <p> The elements in the returned array are not sorted and are not in any
1871      * particular order.
1872      *
1873      * @return  the array of {@code Field} objects representing all the
1874      *          declared fields of this class
1875      * @throws  SecurityException
1876      *          If a security manager, <i>s</i>, is present and any of the
1877      *          following conditions is met:
1878      *
1879      *          <ul>
1880      *
1881      *          <li> the caller's class loader is not the same as the
1882      *          class loader of this class and invocation of
1883      *          {@link SecurityManager#checkPermission
1884      *          s.checkPermission} method with
1885      *          {@code RuntimePermission("accessDeclaredMembers")}
1886      *          denies access to the declared fields within this class
1887      *
1888      *          <li> the caller's class loader is not the same as or an
1889      *          ancestor of the class loader for the current class and
1890      *          invocation of {@link SecurityManager#checkPackageAccess
1891      *          s.checkPackageAccess()} denies access to the package
1892      *          of this class
1893      *
1894      *          </ul>
1895      *
1896      * @since JDK1.1
1897      * @jls 8.2 Class Members
1898      * @jls 8.3 Field Declarations
1899      */
1900     @CallerSensitive
1901     public Field[] getDeclaredFields() throws SecurityException {
1902         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
1903         return copyFields(privateGetDeclaredFields(false));
1904     }
1905 
1906 
1907     /**
1908      *
1909      * Returns an array containing {@code Method} objects reflecting all the
1910      * declared methods of the class or interface represented by this {@code
1911      * Class} object, including public, protected, default (package)
1912      * access, and private methods, but excluding inherited methods.
1913      *
1914      * <p> If this {@code Class} object represents a type that has multiple
1915      * declared methods with the same name and parameter types, but different
1916      * return types, then the returned array has a {@code Method} object for
1917      * each such method.
1918      *
1919      * <p> If this {@code Class} object represents a type that has a class
1920      * initialization method {@code <clinit>}, then the returned array does
1921      * <em>not</em> have a corresponding {@code Method} object.
1922      *
1923      * <p> If this {@code Class} object represents a class or interface with no
1924      * declared methods, then the returned array has length 0.
1925      *
1926      * <p> If this {@code Class} object represents an array type, a primitive
1927      * type, or void, then the returned array has length 0.
1928      *
1929      * <p> The elements in the returned array are not sorted and are not in any
1930      * particular order.
1931      *
1932      * @return  the array of {@code Method} objects representing all the
1933      *          declared methods of this class
1934      * @throws  SecurityException
1935      *          If a security manager, <i>s</i>, is present and any of the
1936      *          following conditions is met:
1937      *
1938      *          <ul>
1939      *
1940      *          <li> the caller's class loader is not the same as the
1941      *          class loader of this class and invocation of
1942      *          {@link SecurityManager#checkPermission
1943      *          s.checkPermission} method with
1944      *          {@code RuntimePermission("accessDeclaredMembers")}
1945      *          denies access to the declared methods within this class
1946      *
1947      *          <li> the caller's class loader is not the same as or an
1948      *          ancestor of the class loader for the current class and
1949      *          invocation of {@link SecurityManager#checkPackageAccess
1950      *          s.checkPackageAccess()} denies access to the package
1951      *          of this class
1952      *
1953      *          </ul>
1954      *
1955      * @jls 8.2 Class Members
1956      * @jls 8.4 Method Declarations
1957      * @since JDK1.1
1958      */
1959     @CallerSensitive
1960     public Method[] getDeclaredMethods() throws SecurityException {
1961         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
1962         return copyMethods(privateGetDeclaredMethods(false));
1963     }
1964 
1965 
1966     /**
1967      * Returns an array of {@code Constructor} objects reflecting all the
1968      * constructors declared by the class represented by this
1969      * {@code Class} object. These are public, protected, default
1970      * (package) access, and private constructors.  The elements in the array
1971      * returned are not sorted and are not in any particular order.  If the
1972      * class has a default constructor, it is included in the returned array.
1973      * This method returns an array of length 0 if this {@code Class}
1974      * object represents an interface, a primitive type, an array class, or
1975      * void.
1976      *
1977      * <p> See <em>The Java Language Specification</em>, section 8.2.
1978      *
1979      * @return  the array of {@code Constructor} objects representing all the
1980      *          declared constructors of this class
1981      * @throws  SecurityException
1982      *          If a security manager, <i>s</i>, is present and any of the
1983      *          following conditions is met:
1984      *
1985      *          <ul>
1986      *
1987      *          <li> the caller's class loader is not the same as the
1988      *          class loader of this class and invocation of
1989      *          {@link SecurityManager#checkPermission
1990      *          s.checkPermission} method with
1991      *          {@code RuntimePermission("accessDeclaredMembers")}
1992      *          denies access to the declared constructors within this class
1993      *
1994      *          <li> the caller's class loader is not the same as or an
1995      *          ancestor of the class loader for the current class and
1996      *          invocation of {@link SecurityManager#checkPackageAccess
1997      *          s.checkPackageAccess()} denies access to the package
1998      *          of this class
1999      *
2000      *          </ul>
2001      *
2002      * @since JDK1.1
2003      */
2004     @CallerSensitive
2005     public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
2006         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2007         return copyConstructors(privateGetDeclaredConstructors(false));
2008     }
2009 
2010 
2011     /**
2012      * Returns a {@code Field} object that reflects the specified declared
2013      * field of the class or interface represented by this {@code Class}
2014      * object. The {@code name} parameter is a {@code String} that specifies
2015      * the simple name of the desired field.
2016      *
2017      * <p> If this {@code Class} object represents an array type, then this
2018      * method does not find the {@code length} field of the array type.
2019      *
2020      * @param name the name of the field
2021      * @return  the {@code Field} object for the specified field in this
2022      *          class
2023      * @throws  NoSuchFieldException if a field with the specified name is
2024      *          not found.
2025      * @throws  NullPointerException if {@code name} is {@code null}
2026      * @throws  SecurityException
2027      *          If a security manager, <i>s</i>, is present and any of the
2028      *          following conditions is met:
2029      *
2030      *          <ul>
2031      *
2032      *          <li> the caller's class loader is not the same as the
2033      *          class loader of this class and invocation of
2034      *          {@link SecurityManager#checkPermission
2035      *          s.checkPermission} method with
2036      *          {@code RuntimePermission("accessDeclaredMembers")}
2037      *          denies access to the declared field
2038      *
2039      *          <li> the caller's class loader is not the same as or an
2040      *          ancestor of the class loader for the current class and
2041      *          invocation of {@link SecurityManager#checkPackageAccess
2042      *          s.checkPackageAccess()} denies access to the package
2043      *          of this class
2044      *
2045      *          </ul>
2046      *
2047      * @since JDK1.1
2048      * @jls 8.2 Class Members
2049      * @jls 8.3 Field Declarations
2050      */
2051     @CallerSensitive
2052     public Field getDeclaredField(String name)
2053         throws NoSuchFieldException, SecurityException {
2054         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2055         Field field = searchFields(privateGetDeclaredFields(false), name);
2056         if (field == null) {
2057             throw new NoSuchFieldException(name);
2058         }
2059         return field;
2060     }
2061 
2062 
2063     /**
2064      * Returns a {@code Method} object that reflects the specified
2065      * declared method of the class or interface represented by this
2066      * {@code Class} object. The {@code name} parameter is a
2067      * {@code String} that specifies the simple name of the desired
2068      * method, and the {@code parameterTypes} parameter is an array of
2069      * {@code Class} objects that identify the method's formal parameter
2070      * types, in declared order.  If more than one method with the same
2071      * parameter types is declared in a class, and one of these methods has a
2072      * return type that is more specific than any of the others, that method is
2073      * returned; otherwise one of the methods is chosen arbitrarily.  If the
2074      * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
2075      * is raised.
2076      *
2077      * <p> If this {@code Class} object represents an array type, then this
2078      * method does not find the {@code clone()} method.
2079      *
2080      * @param name the name of the method
2081      * @param parameterTypes the parameter array
2082      * @return  the {@code Method} object for the method of this class
2083      *          matching the specified name and parameters
2084      * @throws  NoSuchMethodException if a matching method is not found.
2085      * @throws  NullPointerException if {@code name} is {@code null}
2086      * @throws  SecurityException
2087      *          If a security manager, <i>s</i>, is present and any of the
2088      *          following conditions is met:
2089      *
2090      *          <ul>
2091      *
2092      *          <li> the caller's class loader is not the same as the
2093      *          class loader of this class and invocation of
2094      *          {@link SecurityManager#checkPermission
2095      *          s.checkPermission} method with
2096      *          {@code RuntimePermission("accessDeclaredMembers")}
2097      *          denies access to the declared method
2098      *
2099      *          <li> the caller's class loader is not the same as or an
2100      *          ancestor of the class loader for the current class and
2101      *          invocation of {@link SecurityManager#checkPackageAccess
2102      *          s.checkPackageAccess()} denies access to the package
2103      *          of this class
2104      *
2105      *          </ul>
2106      *
2107      * @jls 8.2 Class Members
2108      * @jls 8.4 Method Declarations
2109      * @since JDK1.1
2110      */
2111     @CallerSensitive
2112     public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2113         throws NoSuchMethodException, SecurityException {
2114         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2115         Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
2116         if (method == null) {
2117             throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
2118         }
2119         return method;
2120     }
2121 
2122 
2123     /**
2124      * Returns a {@code Constructor} object that reflects the specified
2125      * constructor of the class or interface represented by this
2126      * {@code Class} object.  The {@code parameterTypes} parameter is
2127      * an array of {@code Class} objects that identify the constructor's
2128      * formal parameter types, in declared order.
2129      *
2130      * If this {@code Class} object represents an inner class
2131      * declared in a non-static context, the formal parameter types
2132      * include the explicit enclosing instance as the first parameter.
2133      *
2134      * @param parameterTypes the parameter array
2135      * @return  The {@code Constructor} object for the constructor with the
2136      *          specified parameter list
2137      * @throws  NoSuchMethodException if a matching method is not found.
2138      * @throws  SecurityException
2139      *          If a security manager, <i>s</i>, is present and any of the
2140      *          following conditions is met:
2141      *
2142      *          <ul>
2143      *
2144      *          <li> the caller's class loader is not the same as the
2145      *          class loader of this class and invocation of
2146      *          {@link SecurityManager#checkPermission
2147      *          s.checkPermission} method with
2148      *          {@code RuntimePermission("accessDeclaredMembers")}
2149      *          denies access to the declared constructor
2150      *
2151      *          <li> the caller's class loader is not the same as or an
2152      *          ancestor of the class loader for the current class and
2153      *          invocation of {@link SecurityManager#checkPackageAccess
2154      *          s.checkPackageAccess()} denies access to the package
2155      *          of this class
2156      *
2157      *          </ul>
2158      *
2159      * @since JDK1.1
2160      */
2161     @CallerSensitive
2162     public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
2163         throws NoSuchMethodException, SecurityException {
2164         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2165         return getConstructor0(parameterTypes, Member.DECLARED);
2166     }
2167 
2168     /**
2169      * Finds a resource with a given name.  The rules for searching resources
2170      * associated with a given class are implemented by the defining
2171      * {@linkplain ClassLoader class loader} of the class.  This method
2172      * delegates to this object's class loader.  If this object was loaded by
2173      * the bootstrap class loader, the method delegates to {@link
2174      * ClassLoader#getSystemResourceAsStream}.
2175      *
2176      * <p> Before delegation, an absolute resource name is constructed from the
2177      * given resource name using this algorithm:
2178      *
2179      * <ul>
2180      *
2181      * <li> If the {@code name} begins with a {@code '/'}
2182      * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
2183      * portion of the {@code name} following the {@code '/'}.
2184      *
2185      * <li> Otherwise, the absolute name is of the following form:
2186      *
2187      * <blockquote>
2188      *   {@code modified_package_name/name}
2189      * </blockquote>
2190      *
2191      * <p> Where the {@code modified_package_name} is the package name of this
2192      * object with {@code '/'} substituted for {@code '.'}
2193      * (<tt>'\u002e'</tt>).
2194      *
2195      * </ul>
2196      *
2197      * @param  name name of the desired resource
2198      * @return      A {@link java.io.InputStream} object or {@code null} if
2199      *              no resource with this name is found
2200      * @throws  NullPointerException If {@code name} is {@code null}
2201      * @since  JDK1.1
2202      */
2203      public InputStream getResourceAsStream(String name) {
2204         name = resolveName(name);
2205         ClassLoader cl = getClassLoader0();
2206         if (cl==null) {
2207             // A system class.
2208             return ClassLoader.getSystemResourceAsStream(name);
2209         }
2210         return cl.getResourceAsStream(name);
2211     }
2212 
2213     /**
2214      * Finds a resource with a given name.  The rules for searching resources
2215      * associated with a given class are implemented by the defining
2216      * {@linkplain ClassLoader class loader} of the class.  This method
2217      * delegates to this object's class loader.  If this object was loaded by
2218      * the bootstrap class loader, the method delegates to {@link
2219      * ClassLoader#getSystemResource}.
2220      *
2221      * <p> Before delegation, an absolute resource name is constructed from the
2222      * given resource name using this algorithm:
2223      *
2224      * <ul>
2225      *
2226      * <li> If the {@code name} begins with a {@code '/'}
2227      * (<tt>'\u002f'</tt>), then the absolute name of the resource is the
2228      * portion of the {@code name} following the {@code '/'}.
2229      *
2230      * <li> Otherwise, the absolute name is of the following form:
2231      *
2232      * <blockquote>
2233      *   {@code modified_package_name/name}
2234      * </blockquote>
2235      *
2236      * <p> Where the {@code modified_package_name} is the package name of this
2237      * object with {@code '/'} substituted for {@code '.'}
2238      * (<tt>'\u002e'</tt>).
2239      *
2240      * </ul>
2241      *
2242      * @param  name name of the desired resource
2243      * @return      A  {@link java.net.URL} object or {@code null} if no
2244      *              resource with this name is found
2245      * @since  JDK1.1
2246      */
2247     public java.net.URL getResource(String name) {
2248         name = resolveName(name);
2249         ClassLoader cl = getClassLoader0();
2250         if (cl==null) {
2251             // A system class.
2252             return ClassLoader.getSystemResource(name);
2253         }
2254         return cl.getResource(name);
2255     }
2256 
2257 
2258 
2259     /** protection domain returned when the internal domain is null */
2260     private static java.security.ProtectionDomain allPermDomain;
2261 
2262 
2263     /**
2264      * Returns the {@code ProtectionDomain} of this class.  If there is a
2265      * security manager installed, this method first calls the security
2266      * manager's {@code checkPermission} method with a
2267      * {@code RuntimePermission("getProtectionDomain")} permission to
2268      * ensure it's ok to get the
2269      * {@code ProtectionDomain}.
2270      *
2271      * @return the ProtectionDomain of this class
2272      *
2273      * @throws SecurityException
2274      *        if a security manager exists and its
2275      *        {@code checkPermission} method doesn't allow
2276      *        getting the ProtectionDomain.
2277      *
2278      * @see java.security.ProtectionDomain
2279      * @see SecurityManager#checkPermission
2280      * @see java.lang.RuntimePermission
2281      * @since 1.2
2282      */
2283     public java.security.ProtectionDomain getProtectionDomain() {
2284         SecurityManager sm = System.getSecurityManager();
2285         if (sm != null) {
2286             sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
2287         }
2288         java.security.ProtectionDomain pd = getProtectionDomain0();
2289         if (pd == null) {
2290             if (allPermDomain == null) {
2291                 java.security.Permissions perms =
2292                     new java.security.Permissions();
2293                 perms.add(SecurityConstants.ALL_PERMISSION);
2294                 allPermDomain =
2295                     new java.security.ProtectionDomain(null, perms);
2296             }
2297             pd = allPermDomain;
2298         }
2299         return pd;
2300     }
2301 
2302 
2303     /**
2304      * Returns the ProtectionDomain of this class.
2305      */
2306     private native java.security.ProtectionDomain getProtectionDomain0();
2307 
2308     /*
2309      * Return the Virtual Machine's Class object for the named
2310      * primitive type.
2311      */
2312     static native Class<?> getPrimitiveClass(String name);
2313 
2314     /*
2315      * Check if client is allowed to access members.  If access is denied,
2316      * throw a SecurityException.
2317      *
2318      * This method also enforces package access.
2319      *
2320      * <p> Default policy: allow all clients access with normal Java access
2321      * control.
2322      */
2323     private void checkMemberAccess(int which, Class<?> caller, boolean checkProxyInterfaces) {
2324         final SecurityManager s = System.getSecurityManager();
2325         if (s != null) {
2326             /* Default policy allows access to all {@link Member#PUBLIC} members,
2327              * as well as access to classes that have the same class loader as the caller.
2328              * In all other cases, it requires RuntimePermission("accessDeclaredMembers")
2329              * permission.
2330              */
2331             final ClassLoader ccl = ClassLoader.getClassLoader(caller);
2332             final ClassLoader cl = getClassLoader0();
2333             if (which != Member.PUBLIC) {
2334                 if (ccl != cl) {
2335                     s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
2336                 }
2337             }
2338             this.checkPackageAccess(ccl, checkProxyInterfaces);
2339         }
2340     }
2341 
2342     /*
2343      * Checks if a client loaded in ClassLoader ccl is allowed to access this
2344      * class under the current package access policy. If access is denied,
2345      * throw a SecurityException.
2346      */
2347     private void checkPackageAccess(final ClassLoader ccl, boolean checkProxyInterfaces) {
2348         final SecurityManager s = System.getSecurityManager();
2349         if (s != null) {
2350             final ClassLoader cl = getClassLoader0();
2351 
2352             if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
2353                 String name = this.getName();
2354                 int i = name.lastIndexOf('.');
2355                 if (i != -1) {
2356                     // skip the package access check on a proxy class in default proxy package
2357                     String pkg = name.substring(0, i);
2358                     if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {
2359                         s.checkPackageAccess(pkg);
2360                     }
2361                 }
2362             }
2363             // check package access on the proxy interfaces
2364             if (checkProxyInterfaces && Proxy.isProxyClass(this)) {
2365                 ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());
2366             }
2367         }
2368     }
2369 
2370     /**
2371      * Add a package name prefix if the name is not absolute Remove leading "/"
2372      * if name is absolute
2373      */
2374     private String resolveName(String name) {
2375         if (name == null) {
2376             return name;
2377         }
2378         if (!name.startsWith("/")) {
2379             Class<?> c = this;
2380             while (c.isArray()) {
2381                 c = c.getComponentType();
2382             }
2383             String baseName = c.getName();
2384             int index = baseName.lastIndexOf('.');
2385             if (index != -1) {
2386                 name = baseName.substring(0, index).replace('.', '/')
2387                     +"/"+name;
2388             }
2389         } else {
2390             name = name.substring(1);
2391         }
2392         return name;
2393     }
2394 
2395     /**
2396      * Atomic operations support.
2397      */
2398     private static class Atomic {
2399         // initialize Unsafe machinery here, since we need to call Class.class instance method
2400         // and have to avoid calling it in the static initializer of the Class class...
2401         private static final Unsafe unsafe = Unsafe.getUnsafe();
2402         // offset of Class.reflectionData instance field
2403         private static final long reflectionDataOffset;
2404         // offset of Class.annotationType instance field
2405         private static final long annotationTypeOffset;
2406         // offset of Class.annotationData instance field
2407         private static final long annotationDataOffset;
2408 
2409         static {
2410             Field[] fields = Class.class.getDeclaredFields0(false); // bypass caches
2411             reflectionDataOffset = objectFieldOffset(fields, "reflectionData");
2412             annotationTypeOffset = objectFieldOffset(fields, "annotationType");
2413             annotationDataOffset = objectFieldOffset(fields, "annotationData");
2414         }
2415 
2416         private static long objectFieldOffset(Field[] fields, String fieldName) {
2417             Field field = searchFields(fields, fieldName);
2418             if (field == null) {
2419                 throw new Error("No " + fieldName + " field found in java.lang.Class");
2420             }
2421             return unsafe.objectFieldOffset(field);
2422         }
2423 
2424         static <T> boolean casReflectionData(Class<?> clazz,
2425                                              SoftReference<ReflectionData<T>> oldData,
2426                                              SoftReference<ReflectionData<T>> newData) {
2427             return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData);
2428         }
2429 
2430         static <T> boolean casAnnotationType(Class<?> clazz,
2431                                              AnnotationType oldType,
2432                                              AnnotationType newType) {
2433             return unsafe.compareAndSwapObject(clazz, annotationTypeOffset, oldType, newType);
2434         }
2435 
2436         static <T> boolean casAnnotationData(Class<?> clazz,
2437                                              AnnotationData oldData,
2438                                              AnnotationData newData) {
2439             return unsafe.compareAndSwapObject(clazz, annotationDataOffset, oldData, newData);
2440         }
2441     }
2442 
2443     /**
2444      * Reflection support.
2445      */
2446 
2447     // Caches for certain reflective results
2448     private static boolean useCaches = true;
2449 
2450     // reflection data that might get invalidated when JVM TI RedefineClasses() is called
2451     private static class ReflectionData<T> {
2452         volatile Field[] declaredFields;
2453         volatile Field[] publicFields;
2454         volatile Method[] declaredMethods;
2455         volatile Method[] publicMethods;
2456         volatile Constructor<T>[] declaredConstructors;
2457         volatile Constructor<T>[] publicConstructors;
2458         // Intermediate results for getFields and getMethods
2459         volatile Field[] declaredPublicFields;
2460         volatile Method[] declaredPublicMethods;
2461         volatile Class<?>[] interfaces;
2462 
2463         // Value of classRedefinedCount when we created this ReflectionData instance
2464         final int redefinedCount;
2465 
2466         ReflectionData(int redefinedCount) {
2467             this.redefinedCount = redefinedCount;
2468         }
2469     }
2470 
2471     private volatile transient SoftReference<ReflectionData<T>> reflectionData;
2472 
2473     // Incremented by the VM on each call to JVM TI RedefineClasses()
2474     // that redefines this class or a superclass.
2475     private volatile transient int classRedefinedCount = 0;
2476 
2477     // Lazily create and cache ReflectionData
2478     private ReflectionData<T> reflectionData() {
2479         SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
2480         int classRedefinedCount = this.classRedefinedCount;
2481         ReflectionData<T> rd;
2482         if (useCaches &&
2483             reflectionData != null &&
2484             (rd = reflectionData.get()) != null &&
2485             rd.redefinedCount == classRedefinedCount) {
2486             return rd;
2487         }
2488         // else no SoftReference or cleared SoftReference or stale ReflectionData
2489         // -> create and replace new instance
2490         return newReflectionData(reflectionData, classRedefinedCount);
2491     }
2492 
2493     private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
2494                                                 int classRedefinedCount) {
2495         if (!useCaches) return null;
2496 
2497         while (true) {
2498             ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
2499             // try to CAS it...
2500             if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
2501                 return rd;
2502             }
2503             // else retry
2504             oldReflectionData = this.reflectionData;
2505             classRedefinedCount = this.classRedefinedCount;
2506             if (oldReflectionData != null &&
2507                 (rd = oldReflectionData.get()) != null &&
2508                 rd.redefinedCount == classRedefinedCount) {
2509                 return rd;
2510             }
2511         }
2512     }
2513 
2514     // Generic signature handling
2515     private native String getGenericSignature0();
2516 
2517     // Generic info repository; lazily initialized
2518     private volatile transient ClassRepository genericInfo;
2519 
2520     // accessor for factory
2521     private GenericsFactory getFactory() {
2522         // create scope and factory
2523         return CoreReflectionFactory.make(this, ClassScope.make(this));
2524     }
2525 
2526     // accessor for generic info repository;
2527     // generic info is lazily initialized
2528     private ClassRepository getGenericInfo() {
2529         ClassRepository genericInfo = this.genericInfo;
2530         if (genericInfo == null) {
2531             String signature = getGenericSignature0();
2532             if (signature == null) {
2533                 genericInfo = ClassRepository.NONE;
2534             } else {
2535                 genericInfo = ClassRepository.make(signature, getFactory());
2536             }
2537             this.genericInfo = genericInfo;
2538         }
2539         return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
2540     }
2541 
2542     // Annotations handling
2543     native byte[] getRawAnnotations();
2544     // Since 1.8
2545     native byte[] getRawTypeAnnotations();
2546     static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
2547         return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
2548     }
2549 
2550     native ConstantPool getConstantPool();
2551 
2552     //
2553     //
2554     // java.lang.reflect.Field handling
2555     //
2556     //
2557 
2558     // Returns an array of "root" fields. These Field objects must NOT
2559     // be propagated to the outside world, but must instead be copied
2560     // via ReflectionFactory.copyField.
2561     private Field[] privateGetDeclaredFields(boolean publicOnly) {
2562         checkInitted();
2563         Field[] res;
2564         ReflectionData<T> rd = reflectionData();
2565         if (rd != null) {
2566             res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
2567             if (res != null) return res;
2568         }
2569         // No cached value available; request value from VM
2570         res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
2571         if (rd != null) {
2572             if (publicOnly) {
2573                 rd.declaredPublicFields = res;
2574             } else {
2575                 rd.declaredFields = res;
2576             }
2577         }
2578         return res;
2579     }
2580 
2581     // Returns an array of "root" fields. These Field objects must NOT
2582     // be propagated to the outside world, but must instead be copied
2583     // via ReflectionFactory.copyField.
2584     private Field[] privateGetPublicFields(Set<Class<?>> traversedInterfaces) {
2585         checkInitted();
2586         Field[] res;
2587         ReflectionData<T> rd = reflectionData();
2588         if (rd != null) {
2589             res = rd.publicFields;
2590             if (res != null) return res;
2591         }
2592 
2593         // No cached value available; compute value recursively.
2594         // Traverse in correct order for getField().
2595         List<Field> fields = new ArrayList<>();
2596         if (traversedInterfaces == null) {
2597             traversedInterfaces = new HashSet<>();
2598         }
2599 
2600         // Local fields
2601         Field[] tmp = privateGetDeclaredFields(true);
2602         addAll(fields, tmp);
2603 
2604         // Direct superinterfaces, recursively
2605         for (Class<?> c : getInterfaces()) {
2606             if (!traversedInterfaces.contains(c)) {
2607                 traversedInterfaces.add(c);
2608                 addAll(fields, c.privateGetPublicFields(traversedInterfaces));
2609             }
2610         }
2611 
2612         // Direct superclass, recursively
2613         if (!isInterface()) {
2614             Class<?> c = getSuperclass();
2615             if (c != null) {
2616                 addAll(fields, c.privateGetPublicFields(traversedInterfaces));
2617             }
2618         }
2619 
2620         res = new Field[fields.size()];
2621         fields.toArray(res);
2622         if (rd != null) {
2623             rd.publicFields = res;
2624         }
2625         return res;
2626     }
2627 
2628     private static void addAll(Collection<Field> c, Field[] o) {
2629         for (int i = 0; i < o.length; i++) {
2630             c.add(o[i]);
2631         }
2632     }
2633 
2634 
2635     //
2636     //
2637     // java.lang.reflect.Constructor handling
2638     //
2639     //
2640 
2641     // Returns an array of "root" constructors. These Constructor
2642     // objects must NOT be propagated to the outside world, but must
2643     // instead be copied via ReflectionFactory.copyConstructor.
2644     private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
2645         checkInitted();
2646         Constructor<T>[] res;
2647         ReflectionData<T> rd = reflectionData();
2648         if (rd != null) {
2649             res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
2650             if (res != null) return res;
2651         }
2652         // No cached value available; request value from VM
2653         if (isInterface()) {
2654             @SuppressWarnings("unchecked")
2655             Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
2656             res = temporaryRes;
2657         } else {
2658             res = getDeclaredConstructors0(publicOnly);
2659         }
2660         if (rd != null) {
2661             if (publicOnly) {
2662                 rd.publicConstructors = res;
2663             } else {
2664                 rd.declaredConstructors = res;
2665             }
2666         }
2667         return res;
2668     }
2669 
2670     //
2671     //
2672     // java.lang.reflect.Method handling
2673     //
2674     //
2675 
2676     // Returns an array of "root" methods. These Method objects must NOT
2677     // be propagated to the outside world, but must instead be copied
2678     // via ReflectionFactory.copyMethod.
2679     private Method[] privateGetDeclaredMethods(boolean publicOnly) {
2680         checkInitted();
2681         Method[] res;
2682         ReflectionData<T> rd = reflectionData();
2683         if (rd != null) {
2684             res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
2685             if (res != null) return res;
2686         }
2687         // No cached value available; request value from VM
2688         res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
2689         if (rd != null) {
2690             if (publicOnly) {
2691                 rd.declaredPublicMethods = res;
2692             } else {
2693                 rd.declaredMethods = res;
2694             }
2695         }
2696         return res;
2697     }
2698 
2699     static class MethodArray {
2700         private Method[] methods;
2701         private int length;
2702 
2703         MethodArray() {
2704             methods = new Method[20];
2705             length = 0;
2706         }
2707 
2708         void add(Method m) {
2709             if (length == methods.length) {
2710                 methods = Arrays.copyOf(methods, 2 * methods.length);
2711             }
2712             methods[length++] = m;
2713         }
2714 
2715         void addAll(Method[] ma) {
2716             for (int i = 0; i < ma.length; i++) {
2717                 add(ma[i]);
2718             }
2719         }
2720 
2721         void addAll(MethodArray ma) {
2722             for (int i = 0; i < ma.length(); i++) {
2723                 add(ma.get(i));
2724             }
2725         }
2726 
2727         void addIfNotPresent(Method newMethod) {
2728             for (int i = 0; i < length; i++) {
2729                 Method m = methods[i];
2730                 if (m == newMethod || (m != null && m.equals(newMethod))) {
2731                     return;
2732                 }
2733             }
2734             add(newMethod);
2735         }
2736 
2737         void addAllIfNotPresent(MethodArray newMethods) {
2738             for (int i = 0; i < newMethods.length(); i++) {
2739                 Method m = newMethods.get(i);
2740                 if (m != null) {
2741                     addIfNotPresent(m);
2742                 }
2743             }
2744         }
2745 
2746         void addAllNonStatic(Method[] methods) {
2747             for (Method candidate : methods) {
2748                 if (!Modifier.isStatic(candidate.getModifiers())) {
2749                     add(candidate);
2750                 }
2751             }
2752         }
2753 
2754         int length() {
2755             return length;
2756         }
2757 
2758         Method get(int i) {
2759             return methods[i];
2760         }
2761 
2762         void removeByNameAndSignature(Method toRemove) {
2763             for (int i = 0; i < length; i++) {
2764                 Method m = methods[i];
2765                 if (m != null &&
2766                     m.getReturnType() == toRemove.getReturnType() &&
2767                     m.getName() == toRemove.getName() &&
2768                     arrayContentsEq(m.getParameterTypes(),
2769                                     toRemove.getParameterTypes())) {
2770                     methods[i] = null;
2771                 }
2772             }
2773         }
2774 
2775         void compactAndTrim() {
2776             int newPos = 0;
2777             // Get rid of null slots
2778             for (int pos = 0; pos < length; pos++) {
2779                 Method m = methods[pos];
2780                 if (m != null) {
2781                     if (pos != newPos) {
2782                         methods[newPos] = m;
2783                     }
2784                     newPos++;
2785                 }
2786             }
2787             if (newPos != methods.length) {
2788                 methods = Arrays.copyOf(methods, newPos);
2789             }
2790         }
2791 
2792         Method[] getArray() {
2793             return methods;
2794         }
2795     }
2796 
2797 
2798     // Returns an array of "root" methods. These Method objects must NOT
2799     // be propagated to the outside world, but must instead be copied
2800     // via ReflectionFactory.copyMethod.
2801     private Method[] privateGetPublicMethods() {
2802         checkInitted();
2803         Method[] res;
2804         ReflectionData<T> rd = reflectionData();
2805         if (rd != null) {
2806             res = rd.publicMethods;
2807             if (res != null) return res;
2808         }
2809 
2810         // No cached value available; compute value recursively.
2811         // Start by fetching public declared methods
2812         MethodArray methods = new MethodArray();
2813         {
2814             Method[] tmp = privateGetDeclaredMethods(true);
2815             methods.addAll(tmp);
2816         }
2817         // Now recur over superclass and direct superinterfaces.
2818         // Go over superinterfaces first so we can more easily filter
2819         // out concrete implementations inherited from superclasses at
2820         // the end.
2821         MethodArray inheritedMethods = new MethodArray();
2822         Class<?>[] interfaces = getInterfaces();
2823         for (int i = 0; i < interfaces.length; i++) {
2824             inheritedMethods.addAllNonStatic(interfaces[i].privateGetPublicMethods());
2825         }
2826         if (!isInterface()) {
2827             Class<?> c = getSuperclass();
2828             if (c != null) {
2829                 MethodArray supers = new MethodArray();
2830                 supers.addAll(c.privateGetPublicMethods());
2831                 // Filter out concrete implementations of any
2832                 // interface methods
2833                 for (int i = 0; i < supers.length(); i++) {
2834                     Method m = supers.get(i);
2835                     if (m != null && !Modifier.isAbstract(m.getModifiers())) {
2836                         inheritedMethods.removeByNameAndSignature(m);
2837                     }
2838                 }
2839                 // Insert superclass's inherited methods before
2840                 // superinterfaces' to satisfy getMethod's search
2841                 // order
2842                 supers.addAll(inheritedMethods);
2843                 inheritedMethods = supers;
2844             }
2845         }
2846         // Filter out all local methods from inherited ones
2847         for (int i = 0; i < methods.length(); i++) {
2848             Method m = methods.get(i);
2849             inheritedMethods.removeByNameAndSignature(m);
2850         }
2851         methods.addAllIfNotPresent(inheritedMethods);
2852         methods.compactAndTrim();
2853         res = methods.getArray();
2854         if (rd != null) {
2855             rd.publicMethods = res;
2856         }
2857         return res;
2858     }
2859 
2860 
2861     //
2862     // Helpers for fetchers of one field, method, or constructor
2863     //
2864 
2865     private static Field searchFields(Field[] fields, String name) {
2866         String internedName = name.intern();
2867         for (int i = 0; i < fields.length; i++) {
2868             if (fields[i].getName() == internedName) {
2869                 return getReflectionFactory().copyField(fields[i]);
2870             }
2871         }
2872         return null;
2873     }
2874 
2875     private Field getField0(String name) throws NoSuchFieldException {
2876         // Note: the intent is that the search algorithm this routine
2877         // uses be equivalent to the ordering imposed by
2878         // privateGetPublicFields(). It fetches only the declared
2879         // public fields for each class, however, to reduce the number
2880         // of Field objects which have to be created for the common
2881         // case where the field being requested is declared in the
2882         // class which is being queried.
2883         Field res;
2884         // Search declared public fields
2885         if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
2886             return res;
2887         }
2888         // Direct superinterfaces, recursively
2889         Class<?>[] interfaces = getInterfaces();
2890         for (int i = 0; i < interfaces.length; i++) {
2891             Class<?> c = interfaces[i];
2892             if ((res = c.getField0(name)) != null) {
2893                 return res;
2894             }
2895         }
2896         // Direct superclass, recursively
2897         if (!isInterface()) {
2898             Class<?> c = getSuperclass();
2899             if (c != null) {
2900                 if ((res = c.getField0(name)) != null) {
2901                     return res;
2902                 }
2903             }
2904         }
2905         return null;
2906     }
2907 
2908     private static Method searchMethods(Method[] methods,
2909                                         String name,
2910                                         Class<?>[] parameterTypes)
2911     {
2912         Method res = null;
2913         String internedName = name.intern();
2914         for (int i = 0; i < methods.length; i++) {
2915             Method m = methods[i];
2916             if (m.getName() == internedName
2917                 && arrayContentsEq(parameterTypes, m.getParameterTypes())
2918                 && (res == null
2919                     || res.getReturnType().isAssignableFrom(m.getReturnType())))
2920                 res = m;
2921         }
2922 
2923         return (res == null ? res : getReflectionFactory().copyMethod(res));
2924     }
2925 
2926 
2927     private Method getMethod0(String name, Class<?>[] parameterTypes, boolean includeStaticMethods) {
2928         // Note: the intent is that the search algorithm this routine
2929         // uses be equivalent to the ordering imposed by
2930         // privateGetPublicMethods(). It fetches only the declared
2931         // public methods for each class, however, to reduce the
2932         // number of Method objects which have to be created for the
2933         // common case where the method being requested is declared in
2934         // the class which is being queried.
2935         Method res;
2936         // Search declared public methods
2937         if ((res = searchMethods(privateGetDeclaredMethods(true),
2938                                  name,
2939                                  parameterTypes)) != null) {
2940             if (includeStaticMethods || !Modifier.isStatic(res.getModifiers()))
2941                 return res;
2942         }
2943         // Search superclass's methods
2944         if (!isInterface()) {
2945             Class<? super T> c = getSuperclass();
2946             if (c != null) {
2947                 if ((res = c.getMethod0(name, parameterTypes, true)) != null) {
2948                     return res;
2949                 }
2950             }
2951         }
2952         // Search superinterfaces' methods
2953         Class<?>[] interfaces = getInterfaces();
2954         for (Class<?> c : interfaces)
2955             if ((res = c.getMethod0(name, parameterTypes, false)) != null)
2956                 return res;
2957         // Not found
2958         return null;
2959     }
2960 
2961     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
2962                                         int which) throws NoSuchMethodException
2963     {
2964         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
2965         for (Constructor<T> constructor : constructors) {
2966             if (arrayContentsEq(parameterTypes,
2967                                 constructor.getParameterTypes())) {
2968                 return getReflectionFactory().copyConstructor(constructor);
2969             }
2970         }
2971         throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
2972     }
2973 
2974     //
2975     // Other helpers and base implementation
2976     //
2977 
2978     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
2979         if (a1 == null) {
2980             return a2 == null || a2.length == 0;
2981         }
2982 
2983         if (a2 == null) {
2984             return a1.length == 0;
2985         }
2986 
2987         if (a1.length != a2.length) {
2988             return false;
2989         }
2990 
2991         for (int i = 0; i < a1.length; i++) {
2992             if (a1[i] != a2[i]) {
2993                 return false;
2994             }
2995         }
2996 
2997         return true;
2998     }
2999 
3000     private static Field[] copyFields(Field[] arg) {
3001         Field[] out = new Field[arg.length];
3002         ReflectionFactory fact = getReflectionFactory();
3003         for (int i = 0; i < arg.length; i++) {
3004             out[i] = fact.copyField(arg[i]);
3005         }
3006         return out;
3007     }
3008 
3009     private static Method[] copyMethods(Method[] arg) {
3010         Method[] out = new Method[arg.length];
3011         ReflectionFactory fact = getReflectionFactory();
3012         for (int i = 0; i < arg.length; i++) {
3013             out[i] = fact.copyMethod(arg[i]);
3014         }
3015         return out;
3016     }
3017 
3018     private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
3019         Constructor<U>[] out = arg.clone();
3020         ReflectionFactory fact = getReflectionFactory();
3021         for (int i = 0; i < out.length; i++) {
3022             out[i] = fact.copyConstructor(out[i]);
3023         }
3024         return out;
3025     }
3026 
3027     private native Field[]       getDeclaredFields0(boolean publicOnly);
3028     private native Method[]      getDeclaredMethods0(boolean publicOnly);
3029     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3030     private native Class<?>[]   getDeclaredClasses0();
3031 
3032     private static String        argumentTypesToString(Class<?>[] argTypes) {
3033         StringBuilder buf = new StringBuilder();
3034         buf.append("(");
3035         if (argTypes != null) {
3036             for (int i = 0; i < argTypes.length; i++) {
3037                 if (i > 0) {
3038                     buf.append(", ");
3039                 }
3040                 Class<?> c = argTypes[i];
3041                 buf.append((c == null) ? "null" : c.getName());
3042             }
3043         }
3044         buf.append(")");
3045         return buf.toString();
3046     }
3047 
3048     /** use serialVersionUID from JDK 1.1 for interoperability */
3049     private static final long serialVersionUID = 3206093459760846163L;
3050 
3051 
3052     /**
3053      * Class Class is special cased within the Serialization Stream Protocol.
3054      *
3055      * A Class instance is written initially into an ObjectOutputStream in the
3056      * following format:
3057      * <pre>
3058      *      {@code TC_CLASS} ClassDescriptor
3059      *      A ClassDescriptor is a special cased serialization of
3060      *      a {@code java.io.ObjectStreamClass} instance.
3061      * </pre>
3062      * A new handle is generated for the initial time the class descriptor
3063      * is written into the stream. Future references to the class descriptor
3064      * are written as references to the initial class descriptor instance.
3065      *
3066      * @see java.io.ObjectStreamClass
3067      */
3068     private static final ObjectStreamField[] serialPersistentFields =
3069         new ObjectStreamField[0];
3070 
3071 
3072     /**
3073      * Returns the assertion status that would be assigned to this
3074      * class if it were to be initialized at the time this method is invoked.
3075      * If this class has had its assertion status set, the most recent
3076      * setting will be returned; otherwise, if any package default assertion
3077      * status pertains to this class, the most recent setting for the most
3078      * specific pertinent package default assertion status is returned;
3079      * otherwise, if this class is not a system class (i.e., it has a
3080      * class loader) its class loader's default assertion status is returned;
3081      * otherwise, the system class default assertion status is returned.
3082      * <p>
3083      * Few programmers will have any need for this method; it is provided
3084      * for the benefit of the JRE itself.  (It allows a class to determine at
3085      * the time that it is initialized whether assertions should be enabled.)
3086      * Note that this method is not guaranteed to return the actual
3087      * assertion status that was (or will be) associated with the specified
3088      * class when it was (or will be) initialized.
3089      *
3090      * @return the desired assertion status of the specified class.
3091      * @see    java.lang.ClassLoader#setClassAssertionStatus
3092      * @see    java.lang.ClassLoader#setPackageAssertionStatus
3093      * @see    java.lang.ClassLoader#setDefaultAssertionStatus
3094      * @since  1.4
3095      */
3096     public boolean desiredAssertionStatus() {
3097         ClassLoader loader = getClassLoader();
3098         // If the loader is null this is a system class, so ask the VM
3099         if (loader == null)
3100             return desiredAssertionStatus0(this);
3101 
3102         // If the classloader has been initialized with the assertion
3103         // directives, ask it. Otherwise, ask the VM.
3104         synchronized(loader.assertionLock) {
3105             if (loader.classAssertionStatus != null) {
3106                 return loader.desiredAssertionStatus(getName());
3107             }
3108         }
3109         return desiredAssertionStatus0(this);
3110     }
3111 
3112     // Retrieves the desired assertion status of this class from the VM
3113     private static native boolean desiredAssertionStatus0(Class<?> clazz);
3114 
3115     /**
3116      * Returns true if and only if this class was declared as an enum in the
3117      * source code.
3118      *
3119      * @return true if and only if this class was declared as an enum in the
3120      *     source code
3121      * @since 1.5
3122      */
3123     public boolean isEnum() {
3124         // An enum must both directly extend java.lang.Enum and have
3125         // the ENUM bit set; classes for specialized enum constants
3126         // don't do the former.
3127         return (this.getModifiers() & ENUM) != 0 &&
3128         this.getSuperclass() == java.lang.Enum.class;
3129     }
3130 
3131     // Fetches the factory for reflective objects
3132     private static ReflectionFactory getReflectionFactory() {
3133         if (reflectionFactory == null) {
3134             reflectionFactory =
3135                 java.security.AccessController.doPrivileged
3136                     (new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());
3137         }
3138         return reflectionFactory;
3139     }
3140     private static ReflectionFactory reflectionFactory;
3141 
3142     // To be able to query system properties as soon as they're available
3143     private static boolean initted = false;
3144     private static void checkInitted() {
3145         if (initted) return;
3146         AccessController.doPrivileged(new PrivilegedAction<Void>() {
3147                 public Void run() {
3148                     // Tests to ensure the system properties table is fully
3149                     // initialized. This is needed because reflection code is
3150                     // called very early in the initialization process (before
3151                     // command-line arguments have been parsed and therefore
3152                     // these user-settable properties installed.) We assume that
3153                     // if System.out is non-null then the System class has been
3154                     // fully initialized and that the bulk of the startup code
3155                     // has been run.
3156 
3157                     if (System.out == null) {
3158                         // java.lang.System not yet fully initialized
3159                         return null;
3160                     }
3161 
3162                     // Doesn't use Boolean.getBoolean to avoid class init.
3163                     String val =
3164                         System.getProperty("sun.reflect.noCaches");
3165                     if (val != null && val.equals("true")) {
3166                         useCaches = false;
3167                     }
3168 
3169                     initted = true;
3170                     return null;
3171                 }
3172             });
3173     }
3174 
3175     /**
3176      * Returns the elements of this enum class or null if this
3177      * Class object does not represent an enum type.
3178      *
3179      * @return an array containing the values comprising the enum class
3180      *     represented by this Class object in the order they're
3181      *     declared, or null if this Class object does not
3182      *     represent an enum type
3183      * @since 1.5
3184      */
3185     public T[] getEnumConstants() {
3186         T[] values = getEnumConstantsShared();
3187         return (values != null) ? values.clone() : null;
3188     }
3189 
3190     /**
3191      * Returns the elements of this enum class or null if this
3192      * Class object does not represent an enum type;
3193      * identical to getEnumConstants except that the result is
3194      * uncloned, cached, and shared by all callers.
3195      */
3196     T[] getEnumConstantsShared() {
3197         if (enumConstants == null) {
3198             if (!isEnum()) return null;
3199             try {
3200                 final Method values = getMethod("values");
3201                 java.security.AccessController.doPrivileged(
3202                     new java.security.PrivilegedAction<Void>() {
3203                         public Void run() {
3204                                 values.setAccessible(true);
3205                                 return null;
3206                             }
3207                         });
3208                 @SuppressWarnings("unchecked")
3209                 T[] temporaryConstants = (T[])values.invoke(null);
3210                 enumConstants = temporaryConstants;
3211             }
3212             // These can happen when users concoct enum-like classes
3213             // that don't comply with the enum spec.
3214             catch (InvocationTargetException | NoSuchMethodException |
3215                    IllegalAccessException ex) { return null; }
3216         }
3217         return enumConstants;
3218     }
3219     private volatile transient T[] enumConstants = null;
3220 
3221     /**
3222      * Returns a map from simple name to enum constant.  This package-private
3223      * method is used internally by Enum to implement
3224      * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}
3225      * efficiently.  Note that the map is returned by this method is
3226      * created lazily on first use.  Typically it won't ever get created.
3227      */
3228     Map<String, T> enumConstantDirectory() {
3229         if (enumConstantDirectory == null) {
3230             T[] universe = getEnumConstantsShared();
3231             if (universe == null)
3232                 throw new IllegalArgumentException(
3233                     getName() + " is not an enum type");
3234             Map<String, T> m = new HashMap<>(2 * universe.length);
3235             for (T constant : universe)
3236                 m.put(((Enum<?>)constant).name(), constant);
3237             enumConstantDirectory = m;
3238         }
3239         return enumConstantDirectory;
3240     }
3241     private volatile transient Map<String, T> enumConstantDirectory = null;
3242 
3243     /**
3244      * Casts an object to the class or interface represented
3245      * by this {@code Class} object.
3246      *
3247      * @param obj the object to be cast
3248      * @return the object after casting, or null if obj is null
3249      *
3250      * @throws ClassCastException if the object is not
3251      * null and is not assignable to the type T.
3252      *
3253      * @since 1.5
3254      */
3255     @SuppressWarnings("unchecked")
3256     public T cast(Object obj) {
3257         if (obj != null && !isInstance(obj))
3258             throw new ClassCastException(cannotCastMsg(obj));
3259         return (T) obj;
3260     }
3261 
3262     private String cannotCastMsg(Object obj) {
3263         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3264     }
3265 
3266     /**
3267      * Casts this {@code Class} object to represent a subclass of the class
3268      * represented by the specified class object.  Checks that the cast
3269      * is valid, and throws a {@code ClassCastException} if it is not.  If
3270      * this method succeeds, it always returns a reference to this class object.
3271      *
3272      * <p>This method is useful when a client needs to "narrow" the type of
3273      * a {@code Class} object to pass it to an API that restricts the
3274      * {@code Class} objects that it is willing to accept.  A cast would
3275      * generate a compile-time warning, as the correctness of the cast
3276      * could not be checked at runtime (because generic types are implemented
3277      * by erasure).
3278      *
3279      * @param <U> the type to cast this class object to
3280      * @param clazz the class of the type to cast this class object to
3281      * @return this {@code Class} object, cast to represent a subclass of
3282      *    the specified class object.
3283      * @throws ClassCastException if this {@code Class} object does not
3284      *    represent a subclass of the specified class (here "subclass" includes
3285      *    the class itself).
3286      * @since 1.5
3287      */
3288     @SuppressWarnings("unchecked")
3289     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
3290         if (clazz.isAssignableFrom(this))
3291             return (Class<? extends U>) this;
3292         else
3293             throw new ClassCastException(this.toString());
3294     }
3295 
3296     /**
3297      * @throws NullPointerException {@inheritDoc}
3298      * @since 1.5
3299      */
3300     @SuppressWarnings("unchecked")
3301     public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
3302         Objects.requireNonNull(annotationClass);
3303 
3304         return (A) annotationData().annotations.get(annotationClass);
3305     }
3306 
3307     /**
3308      * {@inheritDoc}
3309      * @throws NullPointerException {@inheritDoc}
3310      * @since 1.5
3311      */
3312     @Override
3313     public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
3314         return GenericDeclaration.super.isAnnotationPresent(annotationClass);
3315     }
3316 
3317     /**
3318      * @throws NullPointerException {@inheritDoc}
3319      * @since 1.8
3320      */
3321     @Override
3322     public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {
3323         Objects.requireNonNull(annotationClass);
3324 
3325         AnnotationData annotationData = annotationData();
3326         return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations,
3327                                                           this,
3328                                                           annotationClass);
3329     }
3330 
3331     /**
3332      * @since 1.5
3333      */
3334     public Annotation[] getAnnotations() {
3335         return AnnotationParser.toArray(annotationData().annotations);
3336     }
3337 
3338     /**
3339      * @throws NullPointerException {@inheritDoc}
3340      * @since 1.8
3341      */
3342     @Override
3343     @SuppressWarnings("unchecked")
3344     public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
3345         Objects.requireNonNull(annotationClass);
3346 
3347         return (A) annotationData().declaredAnnotations.get(annotationClass);
3348     }
3349 
3350     /**
3351      * @throws NullPointerException {@inheritDoc}
3352      * @since 1.8
3353      */
3354     @Override
3355     public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {
3356         Objects.requireNonNull(annotationClass);
3357 
3358         return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,
3359                                                                  annotationClass);
3360     }
3361 
3362     /**
3363      * @since 1.5
3364      */
3365     public Annotation[] getDeclaredAnnotations()  {
3366         return AnnotationParser.toArray(annotationData().declaredAnnotations);
3367     }
3368 
3369     // annotation data that might get invalidated when JVM TI RedefineClasses() is called
3370     private static class AnnotationData {
3371         final Map<Class<? extends Annotation>, Annotation> annotations;
3372         final Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
3373 
3374         // Value of classRedefinedCount when we created this AnnotationData instance
3375         final int redefinedCount;
3376 
3377         AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations,
3378                        Map<Class<? extends Annotation>, Annotation> declaredAnnotations,
3379                        int redefinedCount) {
3380             this.annotations = annotations;
3381             this.declaredAnnotations = declaredAnnotations;
3382             this.redefinedCount = redefinedCount;
3383         }
3384     }
3385 
3386     // Annotations cache
3387     @SuppressWarnings("UnusedDeclaration")
3388     private volatile transient AnnotationData annotationData;
3389 
3390     private AnnotationData annotationData() {
3391         while (true) { // retry loop
3392             AnnotationData annotationData = this.annotationData;
3393             int classRedefinedCount = this.classRedefinedCount;
3394             if (annotationData != null &&
3395                 annotationData.redefinedCount == classRedefinedCount) {
3396                 return annotationData;
3397             }
3398             // null or stale annotationData -> optimistically create new instance
3399             AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount);
3400             // try to install it
3401             if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) {
3402                 // successfully installed new AnnotationData
3403                 return newAnnotationData;
3404             }
3405         }
3406     }
3407 
3408     private AnnotationData createAnnotationData(int classRedefinedCount) {
3409         Map<Class<? extends Annotation>, Annotation> declaredAnnotations =
3410             AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this);
3411         Class<?> superClass = getSuperclass();
3412         Map<Class<? extends Annotation>, Annotation> annotations = null;
3413         if (superClass != null) {
3414             Map<Class<? extends Annotation>, Annotation> superAnnotations =
3415                 superClass.annotationData().annotations;
3416             for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) {
3417                 Class<? extends Annotation> annotationClass = e.getKey();
3418                 if (AnnotationType.getInstance(annotationClass).isInherited()) {
3419                     if (annotations == null) { // lazy construction
3420                         annotations = new LinkedHashMap<>((Math.max(
3421                                 declaredAnnotations.size(),
3422                                 Math.min(12, declaredAnnotations.size() + superAnnotations.size())
3423                             ) * 4 + 2) / 3
3424                         );
3425                     }
3426                     annotations.put(annotationClass, e.getValue());
3427                 }
3428             }
3429         }
3430         if (annotations == null) {
3431             // no inherited annotations -> share the Map with declaredAnnotations
3432             annotations = declaredAnnotations;
3433         } else {
3434             // at least one inherited annotation -> declared may override inherited
3435             annotations.putAll(declaredAnnotations);
3436         }
3437         return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount);
3438     }
3439 
3440     // Annotation types cache their internal (AnnotationType) form
3441 
3442     @SuppressWarnings("UnusedDeclaration")
3443     private volatile transient AnnotationType annotationType;
3444 
3445     boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {
3446         return Atomic.casAnnotationType(this, oldType, newType);
3447     }
3448 
3449     AnnotationType getAnnotationType() {
3450         return annotationType;
3451     }
3452 
3453     Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() {
3454         return annotationData().declaredAnnotations;
3455     }
3456 
3457     /* Backing store of user-defined values pertaining to this class.
3458      * Maintained by the ClassValue class.
3459      */
3460     transient ClassValue.ClassValueMap classValueMap;
3461 
3462     /**
3463      * Returns an {@code AnnotatedType} object that represents the use of a
3464      * type to specify the superclass of the entity represented by this {@code
3465      * Class} object. (The <em>use</em> of type Foo to specify the superclass
3466      * in '...  extends Foo' is distinct from the <em>declaration</em> of type
3467      * Foo.)
3468      *
3469      * <p> If this {@code Class} object represents a type whose declaration
3470      * does not explicitly indicate an annotated superclass, then the return
3471      * value is an {@code AnnotatedType} object representing an element with no
3472      * annotations.
3473      *
3474      * <p> If this {@code Class} represents either the {@code Object} class, an
3475      * interface type, an array type, a primitive type, or void, the return
3476      * value is {@code null}.
3477      *
3478      * @return an object representing the superclass
3479      * @since 1.8
3480      */
3481     public AnnotatedType getAnnotatedSuperclass() {
3482         if (this == Object.class ||
3483                 isInterface() ||
3484                 isArray() ||
3485                 isPrimitive() ||
3486                 this == Void.TYPE) {
3487             return null;
3488         }
3489 
3490         return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
3491     }
3492 
3493     /**
3494      * Returns an array of {@code AnnotatedType} objects that represent the use
3495      * of types to specify superinterfaces of the entity represented by this
3496      * {@code Class} object. (The <em>use</em> of type Foo to specify a
3497      * superinterface in '... implements Foo' is distinct from the
3498      * <em>declaration</em> of type Foo.)
3499      *
3500      * <p> If this {@code Class} object represents a class, the return value is
3501      * an array containing objects representing the uses of interface types to
3502      * specify interfaces implemented by the class. The order of the objects in
3503      * the array corresponds to the order of the interface types used in the
3504      * 'implements' clause of the declaration of this {@code Class} object.
3505      *
3506      * <p> If this {@code Class} object represents an interface, the return
3507      * value is an array containing objects representing the uses of interface
3508      * types to specify interfaces directly extended by the interface. The
3509      * order of the objects in the array corresponds to the order of the
3510      * interface types used in the 'extends' clause of the declaration of this
3511      * {@code Class} object.
3512      *
3513      * <p> If this {@code Class} object represents a class or interface whose
3514      * declaration does not explicitly indicate any annotated superinterfaces,
3515      * the return value is an array of length 0.
3516      *
3517      * <p> If this {@code Class} object represents either the {@code Object}
3518      * class, an array type, a primitive type, or void, the return value is an
3519      * array of length 0.
3520      *
3521      * @return an array representing the superinterfaces
3522      * @since 1.8
3523      */
3524     public AnnotatedType[] getAnnotatedInterfaces() {
3525          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3526     }
3527 }