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