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