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