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