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