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