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