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>&#64;</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<>() {
 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<>() {
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<>() {
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.7.7: 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         return simpleName;
1361     }
1362 
1363     /**
1364      * Return an informative string for the name of this type.
1365      *
1366      * @return an informative string for the name of this type
1367      * @since 1.8
1368      */
1369     public String getTypeName() {
1370         if (isArray()) {
1371             try {
1372                 Class<?> cl = this;
1373                 int dimensions = 0;
1374                 while (cl.isArray()) {
1375                     dimensions++;
1376                     cl = cl.getComponentType();
1377                 }
1378                 StringBuilder sb = new StringBuilder();
1379                 sb.append(cl.getName());
1380                 for (int i = 0; i < dimensions; i++) {
1381                     sb.append("[]");
1382                 }
1383                 return sb.toString();
1384             } catch (Throwable e) { /*FALLTHRU*/ }
1385         }
1386         return getName();
1387     }
1388 
1389     /**
1390      * Character.isDigit answers {@code true} to some non-ascii
1391      * digits.  This one does not.
1392      */
1393     private static boolean isAsciiDigit(char c) {
1394         return '0' <= c && c <= '9';
1395     }
1396 
1397     /**
1398      * Returns the canonical name of the underlying class as
1399      * defined by the Java Language Specification.  Returns null if
1400      * the underlying class does not have a canonical name (i.e., if
1401      * it is a local or anonymous class or an array whose component
1402      * type does not have a canonical name).
1403      * @return the canonical name of the underlying class if it exists, and
1404      * {@code null} otherwise.
1405      * @since 1.5
1406      */
1407     public String getCanonicalName() {
1408         if (isArray()) {
1409             String canonicalName = getComponentType().getCanonicalName();
1410             if (canonicalName != null)
1411                 return canonicalName + "[]";
1412             else
1413                 return null;
1414         }
1415         if (isLocalOrAnonymousClass())
1416             return null;
1417         Class<?> enclosingClass = getEnclosingClass();
1418         if (enclosingClass == null) { // top level class
1419             return getName();
1420         } else {
1421             String enclosingName = enclosingClass.getCanonicalName();
1422             if (enclosingName == null)
1423                 return null;
1424             return enclosingName + "." + getSimpleName();
1425         }
1426     }
1427 
1428     /**
1429      * Returns {@code true} if and only if the underlying class
1430      * is an anonymous class.
1431      *
1432      * @return {@code true} if and only if this class is an anonymous class.
1433      * @since 1.5
1434      */
1435     public boolean isAnonymousClass() {
1436         return "".equals(getSimpleName());
1437     }
1438 
1439     /**
1440      * Returns {@code true} if and only if the underlying class
1441      * is a local class.
1442      *
1443      * @return {@code true} if and only if this class is a local class.
1444      * @since 1.5
1445      */
1446     public boolean isLocalClass() {
1447         return isLocalOrAnonymousClass() && !isAnonymousClass();
1448     }
1449 
1450     /**
1451      * Returns {@code true} if and only if the underlying class
1452      * is a member class.
1453      *
1454      * @return {@code true} if and only if this class is a member class.
1455      * @since 1.5
1456      */
1457     public boolean isMemberClass() {
1458         return getSimpleBinaryName() != null && !isLocalOrAnonymousClass();
1459     }
1460 
1461     /**
1462      * Returns the "simple binary name" of the underlying class, i.e.,
1463      * the binary name without the leading enclosing class name.
1464      * Returns {@code null} if the underlying class is a top level
1465      * class.
1466      */
1467     private String getSimpleBinaryName() {
1468         Class<?> enclosingClass = getEnclosingClass();
1469         if (enclosingClass == null) // top level class
1470             return null;
1471         String name = getSimpleBinaryName0();
1472         if (name == null) // anonymous class
1473             return "";
1474         return name;
1475     }
1476 
1477     private native String getSimpleBinaryName0();
1478 
1479     /**
1480      * Returns {@code true} if this is a local class or an anonymous
1481      * class.  Returns {@code false} otherwise.
1482      */
1483     private boolean isLocalOrAnonymousClass() {
1484         // JVM Spec 4.7.7: A class must have an EnclosingMethod
1485         // attribute if and only if it is a local class or an
1486         // anonymous class.
1487         return getEnclosingMethodInfo() != null;
1488     }
1489 
1490     /**
1491      * Returns an array containing {@code Class} objects representing all
1492      * the public classes and interfaces that are members of the class
1493      * represented by this {@code Class} object.  This includes public
1494      * class and interface members inherited from superclasses and public class
1495      * and interface members declared by the class.  This method returns an
1496      * array of length 0 if this {@code Class} object has no public member
1497      * classes or interfaces.  This method also returns an array of length 0 if
1498      * this {@code Class} object represents a primitive type, an array
1499      * class, or void.
1500      *
1501      * @return the array of {@code Class} objects representing the public
1502      *         members of this class
1503      * @throws SecurityException
1504      *         If a security manager, <i>s</i>, is present and
1505      *         the caller's class loader is not the same as or an
1506      *         ancestor of the class loader for the current class and
1507      *         invocation of {@link SecurityManager#checkPackageAccess
1508      *         s.checkPackageAccess()} denies access to the package
1509      *         of this class.
1510      *
1511      * @since 1.1
1512      */
1513     @CallerSensitive
1514     public Class<?>[] getClasses() {
1515         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
1516 
1517         // Privileged so this implementation can look at DECLARED classes,
1518         // something the caller might not have privilege to do.  The code here
1519         // is allowed to look at DECLARED classes because (1) it does not hand
1520         // out anything other than public members and (2) public member access
1521         // has already been ok'd by the SecurityManager.
1522 
1523         return java.security.AccessController.doPrivileged(
1524             new java.security.PrivilegedAction<>() {
1525                 public Class<?>[] run() {
1526                     List<Class<?>> list = new ArrayList<>();
1527                     Class<?> currentClass = Class.this;
1528                     while (currentClass != null) {
1529                         for (Class<?> m : currentClass.getDeclaredClasses()) {
1530                             if (Modifier.isPublic(m.getModifiers())) {
1531                                 list.add(m);
1532                             }
1533                         }
1534                         currentClass = currentClass.getSuperclass();
1535                     }
1536                     return list.toArray(new Class<?>[0]);
1537                 }
1538             });
1539     }
1540 
1541 
1542     /**
1543      * Returns an array containing {@code Field} objects reflecting all
1544      * the accessible public fields of the class or interface represented by
1545      * this {@code Class} object.
1546      *
1547      * <p> If this {@code Class} object represents a class or interface with
1548      * no accessible public fields, then this method returns an array of length
1549      * 0.
1550      *
1551      * <p> If this {@code Class} object represents a class, then this method
1552      * returns the public fields of the class and of all its superclasses and
1553      * superinterfaces.
1554      *
1555      * <p> If this {@code Class} object represents an interface, then this
1556      * method returns the fields of the interface and of all its
1557      * superinterfaces.
1558      *
1559      * <p> If this {@code Class} object represents an array type, a primitive
1560      * type, or void, then this method returns an array of length 0.
1561      *
1562      * <p> The elements in the returned array are not sorted and are not in any
1563      * particular order.
1564      *
1565      * @return the array of {@code Field} objects representing the
1566      *         public fields
1567      * @throws SecurityException
1568      *         If a security manager, <i>s</i>, is present and
1569      *         the caller's class loader is not the same as or an
1570      *         ancestor of the class loader for the current class and
1571      *         invocation of {@link SecurityManager#checkPackageAccess
1572      *         s.checkPackageAccess()} denies access to the package
1573      *         of this class.
1574      *
1575      * @since 1.1
1576      * @jls 8.2 Class Members
1577      * @jls 8.3 Field Declarations
1578      */
1579     @CallerSensitive
1580     public Field[] getFields() throws SecurityException {
1581         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1582         return copyFields(privateGetPublicFields(null));
1583     }
1584 
1585 
1586     /**
1587      * Returns an array containing {@code Method} objects reflecting all the
1588      * public methods of the class or interface represented by this {@code
1589      * Class} object, including those declared by the class or interface and
1590      * those inherited from superclasses and superinterfaces.
1591      *
1592      * <p> If this {@code Class} object represents a type that has multiple
1593      * public methods with the same name and parameter types, but different
1594      * return types, then the returned array has a {@code Method} object for
1595      * each such method.
1596      *
1597      * <p> If this {@code Class} object represents a type with a class
1598      * initialization method {@code <clinit>}, then the returned array does
1599      * <em>not</em> have a corresponding {@code Method} object.
1600      *
1601      * <p> If this {@code Class} object represents an array type, then the
1602      * returned array has a {@code Method} object for each of the public
1603      * methods inherited by the array type from {@code Object}. It does not
1604      * contain a {@code Method} object for {@code clone()}.
1605      *
1606      * <p> If this {@code Class} object represents an interface then the
1607      * returned array does not contain any implicitly declared methods from
1608      * {@code Object}. Therefore, if no methods are explicitly declared in
1609      * this interface or any of its superinterfaces then the returned array
1610      * has length 0. (Note that a {@code Class} object which represents a class
1611      * always has public methods, inherited from {@code Object}.)
1612      *
1613      * <p> If this {@code Class} object represents a primitive type or void,
1614      * then the returned array has length 0.
1615      *
1616      * <p> Static methods declared in superinterfaces of the class or interface
1617      * represented by this {@code Class} object are not considered members of
1618      * the class or interface.
1619      *
1620      * <p> The elements in the returned array are not sorted and are not in any
1621      * particular order.
1622      *
1623      * @return the array of {@code Method} objects representing the
1624      *         public methods of this class
1625      * @throws SecurityException
1626      *         If a security manager, <i>s</i>, is present and
1627      *         the caller's class loader is not the same as or an
1628      *         ancestor of the class loader for the current class and
1629      *         invocation of {@link SecurityManager#checkPackageAccess
1630      *         s.checkPackageAccess()} denies access to the package
1631      *         of this class.
1632      *
1633      * @jls 8.2 Class Members
1634      * @jls 8.4 Method Declarations
1635      * @since 1.1
1636      */
1637     @CallerSensitive
1638     public Method[] getMethods() throws SecurityException {
1639         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1640         return copyMethods(privateGetPublicMethods());
1641     }
1642 
1643 
1644     /**
1645      * Returns an array containing {@code Constructor} objects reflecting
1646      * all the public constructors of the class represented by this
1647      * {@code Class} object.  An array of length 0 is returned if the
1648      * class has no public constructors, or if the class is an array class, or
1649      * if the class reflects a primitive type or void.
1650      *
1651      * Note that while this method returns an array of {@code
1652      * Constructor<T>} objects (that is an array of constructors from
1653      * this class), the return type of this method is {@code
1654      * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
1655      * might be expected.  This less informative return type is
1656      * necessary since after being returned from this method, the
1657      * array could be modified to hold {@code Constructor} objects for
1658      * different classes, which would violate the type guarantees of
1659      * {@code Constructor<T>[]}.
1660      *
1661      * @return the array of {@code Constructor} objects representing the
1662      *         public constructors of this class
1663      * @throws SecurityException
1664      *         If a security manager, <i>s</i>, is present and
1665      *         the caller's class loader is not the same as or an
1666      *         ancestor of the class loader for the current class and
1667      *         invocation of {@link SecurityManager#checkPackageAccess
1668      *         s.checkPackageAccess()} denies access to the package
1669      *         of this class.
1670      *
1671      * @since 1.1
1672      */
1673     @CallerSensitive
1674     public Constructor<?>[] getConstructors() throws SecurityException {
1675         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1676         return copyConstructors(privateGetDeclaredConstructors(true));
1677     }
1678 
1679 
1680     /**
1681      * Returns a {@code Field} object that reflects the specified public member
1682      * field of the class or interface represented by this {@code Class}
1683      * object. The {@code name} parameter is a {@code String} specifying the
1684      * simple name of the desired field.
1685      *
1686      * <p> The field to be reflected is determined by the algorithm that
1687      * follows.  Let C be the class or interface represented by this object:
1688      *
1689      * <OL>
1690      * <LI> If C declares a public field with the name specified, that is the
1691      *      field to be reflected.</LI>
1692      * <LI> If no field was found in step 1 above, this algorithm is applied
1693      *      recursively to each direct superinterface of C. The direct
1694      *      superinterfaces are searched in the order they were declared.</LI>
1695      * <LI> If no field was found in steps 1 and 2 above, and C has a
1696      *      superclass S, then this algorithm is invoked recursively upon S.
1697      *      If C has no superclass, then a {@code NoSuchFieldException}
1698      *      is thrown.</LI>
1699      * </OL>
1700      *
1701      * <p> If this {@code Class} object represents an array type, then this
1702      * method does not find the {@code length} field of the array type.
1703      *
1704      * @param name the field name
1705      * @return the {@code Field} object of this class specified by
1706      *         {@code name}
1707      * @throws NoSuchFieldException if a field with the specified name is
1708      *         not found.
1709      * @throws NullPointerException if {@code name} is {@code null}
1710      * @throws SecurityException
1711      *         If a security manager, <i>s</i>, is present and
1712      *         the caller's class loader is not the same as or an
1713      *         ancestor of the class loader for the current class and
1714      *         invocation of {@link SecurityManager#checkPackageAccess
1715      *         s.checkPackageAccess()} denies access to the package
1716      *         of this class.
1717      *
1718      * @since 1.1
1719      * @jls 8.2 Class Members
1720      * @jls 8.3 Field Declarations
1721      */
1722     @CallerSensitive
1723     public Field getField(String name)
1724         throws NoSuchFieldException, SecurityException {
1725         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1726         Field field = getField0(name);
1727         if (field == null) {
1728             throw new NoSuchFieldException(name);
1729         }
1730         return field;
1731     }
1732 
1733 
1734     /**
1735      * Returns a {@code Method} object that reflects the specified public
1736      * member method of the class or interface represented by this
1737      * {@code Class} object. The {@code name} parameter is a
1738      * {@code String} specifying the simple name of the desired method. The
1739      * {@code parameterTypes} parameter is an array of {@code Class}
1740      * objects that identify the method's formal parameter types, in declared
1741      * order. If {@code parameterTypes} is {@code null}, it is
1742      * treated as if it were an empty array.
1743      *
1744      * <p> If the {@code name} is "{@code <init>}" or "{@code <clinit>}" a
1745      * {@code NoSuchMethodException} is raised. Otherwise, the method to
1746      * be reflected is determined by the algorithm that follows.  Let C be the
1747      * class or interface represented by this object:
1748      * <OL>
1749      * <LI> C is searched for a <I>matching method</I>, as defined below. If a
1750      *      matching method is found, it is reflected.</LI>
1751      * <LI> If no matching method is found by step 1 then:
1752      *   <OL TYPE="a">
1753      *   <LI> If C is a class other than {@code Object}, then this algorithm is
1754      *        invoked recursively on the superclass of C.</LI>
1755      *   <LI> If C is the class {@code Object}, or if C is an interface, then
1756      *        the superinterfaces of C (if any) are searched for a matching
1757      *        method. If any such method is found, it is reflected.</LI>
1758      *   </OL></LI>
1759      * </OL>
1760      *
1761      * <p> To find a matching method in a class or interface C:&nbsp; If C
1762      * declares exactly one public method with the specified name and exactly
1763      * the same formal parameter types, that is the method reflected. If more
1764      * than one such method is found in C, and one of these methods has a
1765      * return type that is more specific than any of the others, that method is
1766      * reflected; otherwise one of the methods is chosen arbitrarily.
1767      *
1768      * <p>Note that there may be more than one matching method in a
1769      * class because while the Java language forbids a class to
1770      * declare multiple methods with the same signature but different
1771      * return types, the Java virtual machine does not.  This
1772      * increased flexibility in the virtual machine can be used to
1773      * implement various language features.  For example, covariant
1774      * returns can be implemented with {@linkplain
1775      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
1776      * method and the method being overridden would have the same
1777      * signature but different return types.
1778      *
1779      * <p> If this {@code Class} object represents an array type, then this
1780      * method does not find the {@code clone()} method.
1781      *
1782      * <p> Static methods declared in superinterfaces of the class or interface
1783      * represented by this {@code Class} object are not considered members of
1784      * the class or interface.
1785      *
1786      * @param name the name of the method
1787      * @param parameterTypes the list of parameters
1788      * @return the {@code Method} object that matches the specified
1789      *         {@code name} and {@code parameterTypes}
1790      * @throws NoSuchMethodException if a matching method is not found
1791      *         or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
1792      * @throws NullPointerException if {@code name} is {@code null}
1793      * @throws SecurityException
1794      *         If a security manager, <i>s</i>, is present and
1795      *         the caller's class loader is not the same as or an
1796      *         ancestor of the class loader for the current class and
1797      *         invocation of {@link SecurityManager#checkPackageAccess
1798      *         s.checkPackageAccess()} denies access to the package
1799      *         of this class.
1800      *
1801      * @jls 8.2 Class Members
1802      * @jls 8.4 Method Declarations
1803      * @since 1.1
1804      */
1805     @CallerSensitive
1806     public Method getMethod(String name, Class<?>... parameterTypes)
1807         throws NoSuchMethodException, SecurityException {
1808         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1809         Method method = getMethod0(name, parameterTypes, true);
1810         if (method == null) {
1811             throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
1812         }
1813         return method;
1814     }
1815 
1816 
1817     /**
1818      * Returns a {@code Constructor} object that reflects the specified
1819      * public constructor of the class represented by this {@code Class}
1820      * object. The {@code parameterTypes} parameter is an array of
1821      * {@code Class} objects that identify the constructor's formal
1822      * parameter types, in declared order.
1823      *
1824      * If this {@code Class} object represents an inner class
1825      * declared in a non-static context, the formal parameter types
1826      * include the explicit enclosing instance as the first parameter.
1827      *
1828      * <p> The constructor to reflect is the public constructor of the class
1829      * represented by this {@code Class} object whose formal parameter
1830      * types match those specified by {@code parameterTypes}.
1831      *
1832      * @param parameterTypes the parameter array
1833      * @return the {@code Constructor} object of the public constructor that
1834      *         matches the specified {@code parameterTypes}
1835      * @throws NoSuchMethodException if a matching method is not found.
1836      * @throws SecurityException
1837      *         If a security manager, <i>s</i>, is present and
1838      *         the caller's class loader is not the same as or an
1839      *         ancestor of the class loader for the current class and
1840      *         invocation of {@link SecurityManager#checkPackageAccess
1841      *         s.checkPackageAccess()} denies access to the package
1842      *         of this class.
1843      *
1844      * @since 1.1
1845      */
1846     @CallerSensitive
1847     public Constructor<T> getConstructor(Class<?>... parameterTypes)
1848         throws NoSuchMethodException, SecurityException {
1849         checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
1850         return getConstructor0(parameterTypes, Member.PUBLIC);
1851     }
1852 
1853 
1854     /**
1855      * Returns an array of {@code Class} objects reflecting all the
1856      * classes and interfaces declared as members of the class represented by
1857      * this {@code Class} object. This includes public, protected, default
1858      * (package) access, and private classes and interfaces declared by the
1859      * class, but excludes inherited classes and interfaces.  This method
1860      * returns an array of length 0 if the class declares no classes or
1861      * interfaces as members, or if this {@code Class} object represents a
1862      * primitive type, an array class, or void.
1863      *
1864      * @return the array of {@code Class} objects representing all the
1865      *         declared members of this class
1866      * @throws SecurityException
1867      *         If a security manager, <i>s</i>, is present and any of the
1868      *         following conditions is met:
1869      *
1870      *         <ul>
1871      *
1872      *         <li> the caller's class loader is not the same as the
1873      *         class loader of this class and invocation of
1874      *         {@link SecurityManager#checkPermission
1875      *         s.checkPermission} method with
1876      *         {@code RuntimePermission("accessDeclaredMembers")}
1877      *         denies access to the declared classes within this class
1878      *
1879      *         <li> the caller's class loader is not the same as or an
1880      *         ancestor of the class loader for the current class and
1881      *         invocation of {@link SecurityManager#checkPackageAccess
1882      *         s.checkPackageAccess()} denies access to the package
1883      *         of this class
1884      *
1885      *         </ul>
1886      *
1887      * @since 1.1
1888      */
1889     @CallerSensitive
1890     public Class<?>[] getDeclaredClasses() throws SecurityException {
1891         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), false);
1892         return getDeclaredClasses0();
1893     }
1894 
1895 
1896     /**
1897      * Returns an array of {@code Field} objects reflecting all the fields
1898      * declared by the class or interface represented by this
1899      * {@code Class} object. This includes public, protected, default
1900      * (package) access, and private fields, but excludes inherited fields.
1901      *
1902      * <p> If this {@code Class} object represents a class or interface with no
1903      * declared fields, then this method returns an array of length 0.
1904      *
1905      * <p> If this {@code Class} object represents an array type, a primitive
1906      * type, or void, then this method returns an array of length 0.
1907      *
1908      * <p> The elements in the returned array are not sorted and are not in any
1909      * particular order.
1910      *
1911      * @return  the array of {@code Field} objects representing all the
1912      *          declared fields of this class
1913      * @throws  SecurityException
1914      *          If a security manager, <i>s</i>, is present and any of the
1915      *          following conditions is met:
1916      *
1917      *          <ul>
1918      *
1919      *          <li> the caller's class loader is not the same as the
1920      *          class loader of this class and invocation of
1921      *          {@link SecurityManager#checkPermission
1922      *          s.checkPermission} method with
1923      *          {@code RuntimePermission("accessDeclaredMembers")}
1924      *          denies access to the declared fields within this class
1925      *
1926      *          <li> the caller's class loader is not the same as or an
1927      *          ancestor of the class loader for the current class and
1928      *          invocation of {@link SecurityManager#checkPackageAccess
1929      *          s.checkPackageAccess()} denies access to the package
1930      *          of this class
1931      *
1932      *          </ul>
1933      *
1934      * @since 1.1
1935      * @jls 8.2 Class Members
1936      * @jls 8.3 Field Declarations
1937      */
1938     @CallerSensitive
1939     public Field[] getDeclaredFields() throws SecurityException {
1940         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
1941         return copyFields(privateGetDeclaredFields(false));
1942     }
1943 
1944 
1945     /**
1946      *
1947      * Returns an array containing {@code Method} objects reflecting all the
1948      * declared methods of the class or interface represented by this {@code
1949      * Class} object, including public, protected, default (package)
1950      * access, and private methods, but excluding inherited methods.
1951      *
1952      * <p> If this {@code Class} object represents a type that has multiple
1953      * declared methods with the same name and parameter types, but different
1954      * return types, then the returned array has a {@code Method} object for
1955      * each such method.
1956      *
1957      * <p> If this {@code Class} object represents a type that has a class
1958      * initialization method {@code <clinit>}, then the returned array does
1959      * <em>not</em> have a corresponding {@code Method} object.
1960      *
1961      * <p> If this {@code Class} object represents a class or interface with no
1962      * declared methods, then the returned array has length 0.
1963      *
1964      * <p> If this {@code Class} object represents an array type, a primitive
1965      * type, or void, then the returned array has length 0.
1966      *
1967      * <p> The elements in the returned array are not sorted and are not in any
1968      * particular order.
1969      *
1970      * @return  the array of {@code Method} objects representing all the
1971      *          declared methods of this class
1972      * @throws  SecurityException
1973      *          If a security manager, <i>s</i>, is present and any of the
1974      *          following conditions is met:
1975      *
1976      *          <ul>
1977      *
1978      *          <li> the caller's class loader is not the same as the
1979      *          class loader of this class and invocation of
1980      *          {@link SecurityManager#checkPermission
1981      *          s.checkPermission} method with
1982      *          {@code RuntimePermission("accessDeclaredMembers")}
1983      *          denies access to the declared methods within this class
1984      *
1985      *          <li> the caller's class loader is not the same as or an
1986      *          ancestor of the class loader for the current class and
1987      *          invocation of {@link SecurityManager#checkPackageAccess
1988      *          s.checkPackageAccess()} denies access to the package
1989      *          of this class
1990      *
1991      *          </ul>
1992      *
1993      * @jls 8.2 Class Members
1994      * @jls 8.4 Method Declarations
1995      * @since 1.1
1996      */
1997     @CallerSensitive
1998     public Method[] getDeclaredMethods() throws SecurityException {
1999         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2000         return copyMethods(privateGetDeclaredMethods(false));
2001     }
2002 
2003 
2004     /**
2005      * Returns an array of {@code Constructor} objects reflecting all the
2006      * constructors declared by the class represented by this
2007      * {@code Class} object. These are public, protected, default
2008      * (package) access, and private constructors.  The elements in the array
2009      * returned are not sorted and are not in any particular order.  If the
2010      * class has a default constructor, it is included in the returned array.
2011      * This method returns an array of length 0 if this {@code Class}
2012      * object represents an interface, a primitive type, an array class, or
2013      * void.
2014      *
2015      * <p> See <em>The Java Language Specification</em>, section 8.2.
2016      *
2017      * @return  the array of {@code Constructor} objects representing all the
2018      *          declared constructors of this class
2019      * @throws  SecurityException
2020      *          If a security manager, <i>s</i>, is present and any of the
2021      *          following conditions is met:
2022      *
2023      *          <ul>
2024      *
2025      *          <li> the caller's class loader is not the same as the
2026      *          class loader of this class and invocation of
2027      *          {@link SecurityManager#checkPermission
2028      *          s.checkPermission} method with
2029      *          {@code RuntimePermission("accessDeclaredMembers")}
2030      *          denies access to the declared constructors within this class
2031      *
2032      *          <li> the caller's class loader is not the same as or an
2033      *          ancestor of the class loader for the current class and
2034      *          invocation of {@link SecurityManager#checkPackageAccess
2035      *          s.checkPackageAccess()} denies access to the package
2036      *          of this class
2037      *
2038      *          </ul>
2039      *
2040      * @since 1.1
2041      */
2042     @CallerSensitive
2043     public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
2044         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2045         return copyConstructors(privateGetDeclaredConstructors(false));
2046     }
2047 
2048 
2049     /**
2050      * Returns a {@code Field} object that reflects the specified declared
2051      * field of the class or interface represented by this {@code Class}
2052      * object. The {@code name} parameter is a {@code String} that specifies
2053      * the simple name of the desired field.
2054      *
2055      * <p> If this {@code Class} object represents an array type, then this
2056      * method does not find the {@code length} field of the array type.
2057      *
2058      * @param name the name of the field
2059      * @return  the {@code Field} object for the specified field in this
2060      *          class
2061      * @throws  NoSuchFieldException if a field with the specified name is
2062      *          not found.
2063      * @throws  NullPointerException if {@code name} is {@code null}
2064      * @throws  SecurityException
2065      *          If a security manager, <i>s</i>, is present and any of the
2066      *          following conditions is met:
2067      *
2068      *          <ul>
2069      *
2070      *          <li> the caller's class loader is not the same as the
2071      *          class loader of this class and invocation of
2072      *          {@link SecurityManager#checkPermission
2073      *          s.checkPermission} method with
2074      *          {@code RuntimePermission("accessDeclaredMembers")}
2075      *          denies access to the declared field
2076      *
2077      *          <li> the caller's class loader is not the same as or an
2078      *          ancestor of the class loader for the current class and
2079      *          invocation of {@link SecurityManager#checkPackageAccess
2080      *          s.checkPackageAccess()} denies access to the package
2081      *          of this class
2082      *
2083      *          </ul>
2084      *
2085      * @since 1.1
2086      * @jls 8.2 Class Members
2087      * @jls 8.3 Field Declarations
2088      */
2089     @CallerSensitive
2090     public Field getDeclaredField(String name)
2091         throws NoSuchFieldException, SecurityException {
2092         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2093         Field field = searchFields(privateGetDeclaredFields(false), name);
2094         if (field == null) {
2095             throw new NoSuchFieldException(name);
2096         }
2097         return field;
2098     }
2099 
2100 
2101     /**
2102      * Returns a {@code Method} object that reflects the specified
2103      * declared method of the class or interface represented by this
2104      * {@code Class} object. The {@code name} parameter is a
2105      * {@code String} that specifies the simple name of the desired
2106      * method, and the {@code parameterTypes} parameter is an array of
2107      * {@code Class} objects that identify the method's formal parameter
2108      * types, in declared order.  If more than one method with the same
2109      * parameter types is declared in a class, and one of these methods has a
2110      * return type that is more specific than any of the others, that method is
2111      * returned; otherwise one of the methods is chosen arbitrarily.  If the
2112      * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
2113      * is raised.
2114      *
2115      * <p> If this {@code Class} object represents an array type, then this
2116      * method does not find the {@code clone()} method.
2117      *
2118      * @param name the name of the method
2119      * @param parameterTypes the parameter array
2120      * @return  the {@code Method} object for the method of this class
2121      *          matching the specified name and parameters
2122      * @throws  NoSuchMethodException if a matching method is not found.
2123      * @throws  NullPointerException if {@code name} is {@code null}
2124      * @throws  SecurityException
2125      *          If a security manager, <i>s</i>, is present and any of the
2126      *          following conditions is met:
2127      *
2128      *          <ul>
2129      *
2130      *          <li> the caller's class loader is not the same as the
2131      *          class loader of this class and invocation of
2132      *          {@link SecurityManager#checkPermission
2133      *          s.checkPermission} method with
2134      *          {@code RuntimePermission("accessDeclaredMembers")}
2135      *          denies access to the declared method
2136      *
2137      *          <li> the caller's class loader is not the same as or an
2138      *          ancestor of the class loader for the current class and
2139      *          invocation of {@link SecurityManager#checkPackageAccess
2140      *          s.checkPackageAccess()} denies access to the package
2141      *          of this class
2142      *
2143      *          </ul>
2144      *
2145      * @jls 8.2 Class Members
2146      * @jls 8.4 Method Declarations
2147      * @since 1.1
2148      */
2149     @CallerSensitive
2150     public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2151         throws NoSuchMethodException, SecurityException {
2152         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2153         Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
2154         if (method == null) {
2155             throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));
2156         }
2157         return method;
2158     }
2159 
2160 
2161     /**
2162      * Returns a {@code Constructor} object that reflects the specified
2163      * constructor of the class or interface represented by this
2164      * {@code Class} object.  The {@code parameterTypes} parameter is
2165      * an array of {@code Class} objects that identify the constructor's
2166      * formal parameter types, in declared order.
2167      *
2168      * If this {@code Class} object represents an inner class
2169      * declared in a non-static context, the formal parameter types
2170      * include the explicit enclosing instance as the first parameter.
2171      *
2172      * @param parameterTypes the parameter array
2173      * @return  The {@code Constructor} object for the constructor with the
2174      *          specified parameter list
2175      * @throws  NoSuchMethodException if a matching method is not found.
2176      * @throws  SecurityException
2177      *          If a security manager, <i>s</i>, is present and any of the
2178      *          following conditions is met:
2179      *
2180      *          <ul>
2181      *
2182      *          <li> the caller's class loader is not the same as the
2183      *          class loader of this class and invocation of
2184      *          {@link SecurityManager#checkPermission
2185      *          s.checkPermission} method with
2186      *          {@code RuntimePermission("accessDeclaredMembers")}
2187      *          denies access to the declared constructor
2188      *
2189      *          <li> the caller's class loader is not the same as or an
2190      *          ancestor of the class loader for the current class and
2191      *          invocation of {@link SecurityManager#checkPackageAccess
2192      *          s.checkPackageAccess()} denies access to the package
2193      *          of this class
2194      *
2195      *          </ul>
2196      *
2197      * @since 1.1
2198      */
2199     @CallerSensitive
2200     public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
2201         throws NoSuchMethodException, SecurityException {
2202         checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
2203         return getConstructor0(parameterTypes, Member.DECLARED);
2204     }
2205 
2206     /**
2207      * Finds a resource with a given name.  The rules for searching resources
2208      * associated with a given class are implemented by the defining
2209      * {@linkplain ClassLoader class loader} of the class.  This method
2210      * delegates to this object's class loader.  If this object was loaded by
2211      * the bootstrap class loader, the method delegates to {@link
2212      * ClassLoader#getSystemResourceAsStream}.
2213      *
2214      * <p> Before delegation, an absolute resource name is constructed from the
2215      * given resource name using this algorithm:
2216      *
2217      * <ul>
2218      *
2219      * <li> If the {@code name} begins with a {@code '/'}
2220      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
2221      * portion of the {@code name} following the {@code '/'}.
2222      *
2223      * <li> Otherwise, the absolute name is of the following form:
2224      *
2225      * <blockquote>
2226      *   {@code modified_package_name/name}
2227      * </blockquote>
2228      *
2229      * <p> Where the {@code modified_package_name} is the package name of this
2230      * object with {@code '/'} substituted for {@code '.'}
2231      * (<tt>'&#92;u002e'</tt>).
2232      *
2233      * </ul>
2234      *
2235      * @param  name name of the desired resource
2236      * @return      A {@link java.io.InputStream} object or {@code null} if
2237      *              no resource with this name is found
2238      * @throws  NullPointerException If {@code name} is {@code null}
2239      * @since  1.1
2240      */
2241      public InputStream getResourceAsStream(String name) {
2242         name = resolveName(name);
2243         ClassLoader cl = getClassLoader0();
2244         if (cl==null) {
2245             // A system class.
2246             return ClassLoader.getSystemResourceAsStream(name);
2247         }
2248         return cl.getResourceAsStream(name);
2249     }
2250 
2251     /**
2252      * Finds a resource with a given name.  The rules for searching resources
2253      * associated with a given class are implemented by the defining
2254      * {@linkplain ClassLoader class loader} of the class.  This method
2255      * delegates to this object's class loader.  If this object was loaded by
2256      * the bootstrap class loader, the method delegates to {@link
2257      * ClassLoader#getSystemResource}.
2258      *
2259      * <p> Before delegation, an absolute resource name is constructed from the
2260      * given resource name using this algorithm:
2261      *
2262      * <ul>
2263      *
2264      * <li> If the {@code name} begins with a {@code '/'}
2265      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
2266      * portion of the {@code name} following the {@code '/'}.
2267      *
2268      * <li> Otherwise, the absolute name is of the following form:
2269      *
2270      * <blockquote>
2271      *   {@code modified_package_name/name}
2272      * </blockquote>
2273      *
2274      * <p> Where the {@code modified_package_name} is the package name of this
2275      * object with {@code '/'} substituted for {@code '.'}
2276      * (<tt>'&#92;u002e'</tt>).
2277      *
2278      * </ul>
2279      *
2280      * @param  name name of the desired resource
2281      * @return      A  {@link java.net.URL} object or {@code null} if no
2282      *              resource with this name is found
2283      * @since  1.1
2284      */
2285     public java.net.URL getResource(String name) {
2286         name = resolveName(name);
2287         ClassLoader cl = getClassLoader0();
2288         if (cl==null) {
2289             // A system class.
2290             return ClassLoader.getSystemResource(name);
2291         }
2292         return cl.getResource(name);
2293     }
2294 
2295 
2296 
2297     /** protection domain returned when the internal domain is null */
2298     private static java.security.ProtectionDomain allPermDomain;
2299 
2300 
2301     /**
2302      * Returns the {@code ProtectionDomain} of this class.  If there is a
2303      * security manager installed, this method first calls the security
2304      * manager's {@code checkPermission} method with a
2305      * {@code RuntimePermission("getProtectionDomain")} permission to
2306      * ensure it's ok to get the
2307      * {@code ProtectionDomain}.
2308      *
2309      * @return the ProtectionDomain of this class
2310      *
2311      * @throws SecurityException
2312      *        if a security manager exists and its
2313      *        {@code checkPermission} method doesn't allow
2314      *        getting the ProtectionDomain.
2315      *
2316      * @see java.security.ProtectionDomain
2317      * @see SecurityManager#checkPermission
2318      * @see java.lang.RuntimePermission
2319      * @since 1.2
2320      */
2321     public java.security.ProtectionDomain getProtectionDomain() {
2322         SecurityManager sm = System.getSecurityManager();
2323         if (sm != null) {
2324             sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
2325         }
2326         java.security.ProtectionDomain pd = getProtectionDomain0();
2327         if (pd == null) {
2328             if (allPermDomain == null) {
2329                 java.security.Permissions perms =
2330                     new java.security.Permissions();
2331                 perms.add(SecurityConstants.ALL_PERMISSION);
2332                 allPermDomain =
2333                     new java.security.ProtectionDomain(null, perms);
2334             }
2335             pd = allPermDomain;
2336         }
2337         return pd;
2338     }
2339 
2340 
2341     /**
2342      * Returns the ProtectionDomain of this class.
2343      */
2344     private native java.security.ProtectionDomain getProtectionDomain0();
2345 
2346     /*
2347      * Return the Virtual Machine's Class object for the named
2348      * primitive type.
2349      */
2350     static native Class<?> getPrimitiveClass(String name);
2351 
2352     /*
2353      * Check if client is allowed to access members.  If access is denied,
2354      * throw a SecurityException.
2355      *
2356      * This method also enforces package access.
2357      *
2358      * <p> Default policy: allow all clients access with normal Java access
2359      * control.
2360      */
2361     private void checkMemberAccess(int which, Class<?> caller, boolean checkProxyInterfaces) {
2362         final SecurityManager s = System.getSecurityManager();
2363         if (s != null) {
2364             /* Default policy allows access to all {@link Member#PUBLIC} members,
2365              * as well as access to classes that have the same class loader as the caller.
2366              * In all other cases, it requires RuntimePermission("accessDeclaredMembers")
2367              * permission.
2368              */
2369             final ClassLoader ccl = ClassLoader.getClassLoader(caller);
2370             final ClassLoader cl = getClassLoader0();
2371             if (which != Member.PUBLIC) {
2372                 if (ccl != cl) {
2373                     s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
2374                 }
2375             }
2376             this.checkPackageAccess(ccl, checkProxyInterfaces);
2377         }
2378     }
2379 
2380     /*
2381      * Checks if a client loaded in ClassLoader ccl is allowed to access this
2382      * class under the current package access policy. If access is denied,
2383      * throw a SecurityException.
2384      */
2385     private void checkPackageAccess(final ClassLoader ccl, boolean checkProxyInterfaces) {
2386         final SecurityManager s = System.getSecurityManager();
2387         if (s != null) {
2388             final ClassLoader cl = getClassLoader0();
2389 
2390             if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
2391                 String name = this.getName();
2392                 int i = name.lastIndexOf('.');
2393                 if (i != -1) {
2394                     // skip the package access check on a proxy class in default proxy package
2395                     String pkg = name.substring(0, i);
2396                     if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {
2397                         s.checkPackageAccess(pkg);
2398                     }
2399                 }
2400             }
2401             // check package access on the proxy interfaces
2402             if (checkProxyInterfaces && Proxy.isProxyClass(this)) {
2403                 ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());
2404             }
2405         }
2406     }
2407 
2408     /**
2409      * Add a package name prefix if the name is not absolute Remove leading "/"
2410      * if name is absolute
2411      */
2412     private String resolveName(String name) {
2413         if (name == null) {
2414             return name;
2415         }
2416         if (!name.startsWith("/")) {
2417             Class<?> c = this;
2418             while (c.isArray()) {
2419                 c = c.getComponentType();
2420             }
2421             String baseName = c.getName();
2422             int index = baseName.lastIndexOf('.');
2423             if (index != -1) {
2424                 name = baseName.substring(0, index).replace('.', '/')
2425                     +"/"+name;
2426             }
2427         } else {
2428             name = name.substring(1);
2429         }
2430         return name;
2431     }
2432 
2433     /**
2434      * Atomic operations support.
2435      */
2436     private static class Atomic {
2437         // initialize Unsafe machinery here, since we need to call Class.class instance method
2438         // and have to avoid calling it in the static initializer of the Class class...
2439         private static final Unsafe unsafe = Unsafe.getUnsafe();
2440         // offset of Class.reflectionData instance field
2441         private static final long reflectionDataOffset;
2442         // offset of Class.annotationType instance field
2443         private static final long annotationTypeOffset;
2444         // offset of Class.annotationData instance field
2445         private static final long annotationDataOffset;
2446 
2447         static {
2448             Field[] fields = Class.class.getDeclaredFields0(false); // bypass caches
2449             reflectionDataOffset = objectFieldOffset(fields, "reflectionData");
2450             annotationTypeOffset = objectFieldOffset(fields, "annotationType");
2451             annotationDataOffset = objectFieldOffset(fields, "annotationData");
2452         }
2453 
2454         private static long objectFieldOffset(Field[] fields, String fieldName) {
2455             Field field = searchFields(fields, fieldName);
2456             if (field == null) {
2457                 throw new Error("No " + fieldName + " field found in java.lang.Class");
2458             }
2459             return unsafe.objectFieldOffset(field);
2460         }
2461 
2462         static <T> boolean casReflectionData(Class<?> clazz,
2463                                              SoftReference<ReflectionData<T>> oldData,
2464                                              SoftReference<ReflectionData<T>> newData) {
2465             return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData);
2466         }
2467 
2468         static <T> boolean casAnnotationType(Class<?> clazz,
2469                                              AnnotationType oldType,
2470                                              AnnotationType newType) {
2471             return unsafe.compareAndSwapObject(clazz, annotationTypeOffset, oldType, newType);
2472         }
2473 
2474         static <T> boolean casAnnotationData(Class<?> clazz,
2475                                              AnnotationData oldData,
2476                                              AnnotationData newData) {
2477             return unsafe.compareAndSwapObject(clazz, annotationDataOffset, oldData, newData);
2478         }
2479     }
2480 
2481     /**
2482      * Reflection support.
2483      */
2484 
2485     // Caches for certain reflective results
2486     private static boolean useCaches = true;
2487 
2488     // reflection data that might get invalidated when JVM TI RedefineClasses() is called
2489     private static class ReflectionData<T> {
2490         volatile Field[] declaredFields;
2491         volatile Field[] publicFields;
2492         volatile Method[] declaredMethods;
2493         volatile Method[] publicMethods;
2494         volatile Constructor<T>[] declaredConstructors;
2495         volatile Constructor<T>[] publicConstructors;
2496         // Intermediate results for getFields and getMethods
2497         volatile Field[] declaredPublicFields;
2498         volatile Method[] declaredPublicMethods;
2499         volatile Class<?>[] interfaces;
2500 
2501         // Value of classRedefinedCount when we created this ReflectionData instance
2502         final int redefinedCount;
2503 
2504         ReflectionData(int redefinedCount) {
2505             this.redefinedCount = redefinedCount;
2506         }
2507     }
2508 
2509     private volatile transient SoftReference<ReflectionData<T>> reflectionData;
2510 
2511     // Incremented by the VM on each call to JVM TI RedefineClasses()
2512     // that redefines this class or a superclass.
2513     private volatile transient int classRedefinedCount = 0;
2514 
2515     // Lazily create and cache ReflectionData
2516     private ReflectionData<T> reflectionData() {
2517         SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
2518         int classRedefinedCount = this.classRedefinedCount;
2519         ReflectionData<T> rd;
2520         if (useCaches &&
2521             reflectionData != null &&
2522             (rd = reflectionData.get()) != null &&
2523             rd.redefinedCount == classRedefinedCount) {
2524             return rd;
2525         }
2526         // else no SoftReference or cleared SoftReference or stale ReflectionData
2527         // -> create and replace new instance
2528         return newReflectionData(reflectionData, classRedefinedCount);
2529     }
2530 
2531     private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
2532                                                 int classRedefinedCount) {
2533         if (!useCaches) return null;
2534 
2535         while (true) {
2536             ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
2537             // try to CAS it...
2538             if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
2539                 return rd;
2540             }
2541             // else retry
2542             oldReflectionData = this.reflectionData;
2543             classRedefinedCount = this.classRedefinedCount;
2544             if (oldReflectionData != null &&
2545                 (rd = oldReflectionData.get()) != null &&
2546                 rd.redefinedCount == classRedefinedCount) {
2547                 return rd;
2548             }
2549         }
2550     }
2551 
2552     // Generic signature handling
2553     private native String getGenericSignature0();
2554 
2555     // Generic info repository; lazily initialized
2556     private volatile transient ClassRepository genericInfo;
2557 
2558     // accessor for factory
2559     private GenericsFactory getFactory() {
2560         // create scope and factory
2561         return CoreReflectionFactory.make(this, ClassScope.make(this));
2562     }
2563 
2564     // accessor for generic info repository;
2565     // generic info is lazily initialized
2566     private ClassRepository getGenericInfo() {
2567         ClassRepository genericInfo = this.genericInfo;
2568         if (genericInfo == null) {
2569             String signature = getGenericSignature0();
2570             if (signature == null) {
2571                 genericInfo = ClassRepository.NONE;
2572             } else {
2573                 genericInfo = ClassRepository.make(signature, getFactory());
2574             }
2575             this.genericInfo = genericInfo;
2576         }
2577         return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
2578     }
2579 
2580     // Annotations handling
2581     native byte[] getRawAnnotations();
2582     // Since 1.8
2583     native byte[] getRawTypeAnnotations();
2584     static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
2585         return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
2586     }
2587 
2588     native ConstantPool getConstantPool();
2589 
2590     //
2591     //
2592     // java.lang.reflect.Field handling
2593     //
2594     //
2595 
2596     // Returns an array of "root" fields. These Field objects must NOT
2597     // be propagated to the outside world, but must instead be copied
2598     // via ReflectionFactory.copyField.
2599     private Field[] privateGetDeclaredFields(boolean publicOnly) {
2600         checkInitted();
2601         Field[] res;
2602         ReflectionData<T> rd = reflectionData();
2603         if (rd != null) {
2604             res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
2605             if (res != null) return res;
2606         }
2607         // No cached value available; request value from VM
2608         res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
2609         if (rd != null) {
2610             if (publicOnly) {
2611                 rd.declaredPublicFields = res;
2612             } else {
2613                 rd.declaredFields = res;
2614             }
2615         }
2616         return res;
2617     }
2618 
2619     // Returns an array of "root" fields. These Field objects must NOT
2620     // be propagated to the outside world, but must instead be copied
2621     // via ReflectionFactory.copyField.
2622     private Field[] privateGetPublicFields(Set<Class<?>> traversedInterfaces) {
2623         checkInitted();
2624         Field[] res;
2625         ReflectionData<T> rd = reflectionData();
2626         if (rd != null) {
2627             res = rd.publicFields;
2628             if (res != null) return res;
2629         }
2630 
2631         // No cached value available; compute value recursively.
2632         // Traverse in correct order for getField().
2633         List<Field> fields = new ArrayList<>();
2634         if (traversedInterfaces == null) {
2635             traversedInterfaces = new HashSet<>();
2636         }
2637 
2638         // Local fields
2639         Field[] tmp = privateGetDeclaredFields(true);
2640         addAll(fields, tmp);
2641 
2642         // Direct superinterfaces, recursively
2643         for (Class<?> c : getInterfaces()) {
2644             if (!traversedInterfaces.contains(c)) {
2645                 traversedInterfaces.add(c);
2646                 addAll(fields, c.privateGetPublicFields(traversedInterfaces));
2647             }
2648         }
2649 
2650         // Direct superclass, recursively
2651         if (!isInterface()) {
2652             Class<?> c = getSuperclass();
2653             if (c != null) {
2654                 addAll(fields, c.privateGetPublicFields(traversedInterfaces));
2655             }
2656         }
2657 
2658         res = new Field[fields.size()];
2659         fields.toArray(res);
2660         if (rd != null) {
2661             rd.publicFields = res;
2662         }
2663         return res;
2664     }
2665 
2666     private static void addAll(Collection<Field> c, Field[] o) {
2667         for (Field f : o) {
2668             c.add(f);
2669         }
2670     }
2671 
2672 
2673     //
2674     //
2675     // java.lang.reflect.Constructor handling
2676     //
2677     //
2678 
2679     // Returns an array of "root" constructors. These Constructor
2680     // objects must NOT be propagated to the outside world, but must
2681     // instead be copied via ReflectionFactory.copyConstructor.
2682     private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
2683         checkInitted();
2684         Constructor<T>[] res;
2685         ReflectionData<T> rd = reflectionData();
2686         if (rd != null) {
2687             res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
2688             if (res != null) return res;
2689         }
2690         // No cached value available; request value from VM
2691         if (isInterface()) {
2692             @SuppressWarnings("unchecked")
2693             Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
2694             res = temporaryRes;
2695         } else {
2696             res = getDeclaredConstructors0(publicOnly);
2697         }
2698         if (rd != null) {
2699             if (publicOnly) {
2700                 rd.publicConstructors = res;
2701             } else {
2702                 rd.declaredConstructors = res;
2703             }
2704         }
2705         return res;
2706     }
2707 
2708     //
2709     //
2710     // java.lang.reflect.Method handling
2711     //
2712     //
2713 
2714     // Returns an array of "root" methods. These Method objects must NOT
2715     // be propagated to the outside world, but must instead be copied
2716     // via ReflectionFactory.copyMethod.
2717     private Method[] privateGetDeclaredMethods(boolean publicOnly) {
2718         checkInitted();
2719         Method[] res;
2720         ReflectionData<T> rd = reflectionData();
2721         if (rd != null) {
2722             res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
2723             if (res != null) return res;
2724         }
2725         // No cached value available; request value from VM
2726         res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
2727         if (rd != null) {
2728             if (publicOnly) {
2729                 rd.declaredPublicMethods = res;
2730             } else {
2731                 rd.declaredMethods = res;
2732             }
2733         }
2734         return res;
2735     }
2736 
2737     static class MethodArray {
2738         // Don't add or remove methods except by add() or remove() calls.
2739         private Method[] methods;
2740         private int length;
2741         private int defaults;
2742 
2743         MethodArray() {
2744             this(20);
2745         }
2746 
2747         MethodArray(int initialSize) {
2748             if (initialSize < 2)
2749                 throw new IllegalArgumentException("Size should be 2 or more");
2750 
2751             methods = new Method[initialSize];
2752             length = 0;
2753             defaults = 0;
2754         }
2755 
2756         boolean hasDefaults() {
2757             return defaults != 0;
2758         }
2759 
2760         void add(Method m) {
2761             if (length == methods.length) {
2762                 methods = Arrays.copyOf(methods, 2 * methods.length);
2763             }
2764             methods[length++] = m;
2765 
2766             if (m != null && m.isDefault())
2767                 defaults++;
2768         }
2769 
2770         void addAll(Method[] ma) {
2771             for (Method m : ma) {
2772                 add(m);
2773             }
2774         }
2775 
2776         void addAll(MethodArray ma) {
2777             for (int i = 0; i < ma.length(); i++) {
2778                 add(ma.get(i));
2779             }
2780         }
2781 
2782         void addIfNotPresent(Method newMethod) {
2783             for (int i = 0; i < length; i++) {
2784                 Method m = methods[i];
2785                 if (m == newMethod || (m != null && m.equals(newMethod))) {
2786                     return;
2787                 }
2788             }
2789             add(newMethod);
2790         }
2791 
2792         void addAllIfNotPresent(MethodArray newMethods) {
2793             for (int i = 0; i < newMethods.length(); i++) {
2794                 Method m = newMethods.get(i);
2795                 if (m != null) {
2796                     addIfNotPresent(m);
2797                 }
2798             }
2799         }
2800 
2801         /* Add Methods declared in an interface to this MethodArray.
2802          * Static methods declared in interfaces are not inherited.
2803          */
2804         void addInterfaceMethods(Method[] methods) {
2805             for (Method candidate : methods) {
2806                 if (!Modifier.isStatic(candidate.getModifiers())) {
2807                     add(candidate);
2808                 }
2809             }
2810         }
2811 
2812         int length() {
2813             return length;
2814         }
2815 
2816         Method get(int i) {
2817             return methods[i];
2818         }
2819 
2820         Method getFirst() {
2821             for (Method m : methods)
2822                 if (m != null)
2823                     return m;
2824             return null;
2825         }
2826 
2827         void removeByNameAndDescriptor(Method toRemove) {
2828             for (int i = 0; i < length; i++) {
2829                 Method m = methods[i];
2830                 if (m != null && matchesNameAndDescriptor(m, toRemove)) {
2831                     remove(i);
2832                 }
2833             }
2834         }
2835 
2836         private void remove(int i) {
2837             if (methods[i] != null && methods[i].isDefault())
2838                 defaults--;
2839             methods[i] = null;
2840         }
2841 
2842         private boolean matchesNameAndDescriptor(Method m1, Method m2) {
2843             return m1.getReturnType() == m2.getReturnType() &&
2844                    m1.getName() == m2.getName() && // name is guaranteed to be interned
2845                    arrayContentsEq(m1.getParameterTypes(),
2846                            m2.getParameterTypes());
2847         }
2848 
2849         void compactAndTrim() {
2850             int newPos = 0;
2851             // Get rid of null slots
2852             for (int pos = 0; pos < length; pos++) {
2853                 Method m = methods[pos];
2854                 if (m != null) {
2855                     if (pos != newPos) {
2856                         methods[newPos] = m;
2857                     }
2858                     newPos++;
2859                 }
2860             }
2861             if (newPos != methods.length) {
2862                 methods = Arrays.copyOf(methods, newPos);
2863             }
2864         }
2865 
2866         /* Removes all Methods from this MethodArray that have a more specific
2867          * default Method in this MethodArray.
2868          *
2869          * Users of MethodArray are responsible for pruning Methods that have
2870          * a more specific <em>concrete</em> Method.
2871          */
2872         void removeLessSpecifics() {
2873             if (!hasDefaults())
2874                 return;
2875 
2876             for (int i = 0; i < length; i++) {
2877                 Method m = get(i);
2878                 if  (m == null || !m.isDefault())
2879                     continue;
2880 
2881                 for (int j  = 0; j < length; j++) {
2882                     if (i == j)
2883                         continue;
2884 
2885                     Method candidate = get(j);
2886                     if (candidate == null)
2887                         continue;
2888 
2889                     if (!matchesNameAndDescriptor(m, candidate))
2890                         continue;
2891 
2892                     if (hasMoreSpecificClass(m, candidate))
2893                         remove(j);
2894                 }
2895             }
2896         }
2897 
2898         Method[] getArray() {
2899             return methods;
2900         }
2901 
2902         // Returns true if m1 is more specific than m2
2903         static boolean hasMoreSpecificClass(Method m1, Method m2) {
2904             Class<?> m1Class = m1.getDeclaringClass();
2905             Class<?> m2Class = m2.getDeclaringClass();
2906             return m1Class != m2Class && m2Class.isAssignableFrom(m1Class);
2907         }
2908     }
2909 
2910 
2911     // Returns an array of "root" methods. These Method objects must NOT
2912     // be propagated to the outside world, but must instead be copied
2913     // via ReflectionFactory.copyMethod.
2914     private Method[] privateGetPublicMethods() {
2915         checkInitted();
2916         Method[] res;
2917         ReflectionData<T> rd = reflectionData();
2918         if (rd != null) {
2919             res = rd.publicMethods;
2920             if (res != null) return res;
2921         }
2922 
2923         // No cached value available; compute value recursively.
2924         // Start by fetching public declared methods
2925         MethodArray methods = new MethodArray();
2926         {
2927             Method[] tmp = privateGetDeclaredMethods(true);
2928             methods.addAll(tmp);
2929         }
2930         // Now recur over superclass and direct superinterfaces.
2931         // Go over superinterfaces first so we can more easily filter
2932         // out concrete implementations inherited from superclasses at
2933         // the end.
2934         MethodArray inheritedMethods = new MethodArray();
2935         for (Class<?> i : getInterfaces()) {
2936             inheritedMethods.addInterfaceMethods(i.privateGetPublicMethods());
2937         }
2938         if (!isInterface()) {
2939             Class<?> c = getSuperclass();
2940             if (c != null) {
2941                 MethodArray supers = new MethodArray();
2942                 supers.addAll(c.privateGetPublicMethods());
2943                 // Filter out concrete implementations of any
2944                 // interface methods
2945                 for (int i = 0; i < supers.length(); i++) {
2946                     Method m = supers.get(i);
2947                     if (m != null &&
2948                             !Modifier.isAbstract(m.getModifiers()) &&
2949                             !m.isDefault()) {
2950                         inheritedMethods.removeByNameAndDescriptor(m);
2951                     }
2952                 }
2953                 // Insert superclass's inherited methods before
2954                 // superinterfaces' to satisfy getMethod's search
2955                 // order
2956                 supers.addAll(inheritedMethods);
2957                 inheritedMethods = supers;
2958             }
2959         }
2960         // Filter out all local methods from inherited ones
2961         for (int i = 0; i < methods.length(); i++) {
2962             Method m = methods.get(i);
2963             inheritedMethods.removeByNameAndDescriptor(m);
2964         }
2965         methods.addAllIfNotPresent(inheritedMethods);
2966         methods.removeLessSpecifics();
2967         methods.compactAndTrim();
2968         res = methods.getArray();
2969         if (rd != null) {
2970             rd.publicMethods = res;
2971         }
2972         return res;
2973     }
2974 
2975 
2976     //
2977     // Helpers for fetchers of one field, method, or constructor
2978     //
2979 
2980     private static Field searchFields(Field[] fields, String name) {
2981         String internedName = name.intern();
2982         for (Field field : fields) {
2983             if (field.getName() == internedName) {
2984                 return getReflectionFactory().copyField(field);
2985             }
2986         }
2987         return null;
2988     }
2989 
2990     private Field getField0(String name) throws NoSuchFieldException {
2991         // Note: the intent is that the search algorithm this routine
2992         // uses be equivalent to the ordering imposed by
2993         // privateGetPublicFields(). It fetches only the declared
2994         // public fields for each class, however, to reduce the number
2995         // of Field objects which have to be created for the common
2996         // case where the field being requested is declared in the
2997         // class which is being queried.
2998         Field res;
2999         // Search declared public fields
3000         if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
3001             return res;
3002         }
3003         // Direct superinterfaces, recursively
3004         Class<?>[] interfaces = getInterfaces();
3005         for (Class<?> c : interfaces) {
3006             if ((res = c.getField0(name)) != null) {
3007                 return res;
3008             }
3009         }
3010         // Direct superclass, recursively
3011         if (!isInterface()) {
3012             Class<?> c = getSuperclass();
3013             if (c != null) {
3014                 if ((res = c.getField0(name)) != null) {
3015                     return res;
3016                 }
3017             }
3018         }
3019         return null;
3020     }
3021 
3022     private static Method searchMethods(Method[] methods,
3023                                         String name,
3024                                         Class<?>[] parameterTypes)
3025     {
3026         Method res = null;
3027         String internedName = name.intern();
3028         for (Method m : methods) {
3029             if (m.getName() == internedName
3030                 && arrayContentsEq(parameterTypes, m.getParameterTypes())
3031                 && (res == null
3032                     || res.getReturnType().isAssignableFrom(m.getReturnType())))
3033                 res = m;
3034         }
3035 
3036         return (res == null ? res : getReflectionFactory().copyMethod(res));
3037     }
3038 
3039     private Method getMethod0(String name, Class<?>[] parameterTypes, boolean includeStaticMethods) {
3040         MethodArray interfaceCandidates = new MethodArray(2);
3041         Method res =  privateGetMethodRecursive(name, parameterTypes, includeStaticMethods, interfaceCandidates);
3042         if (res != null)
3043             return res;
3044 
3045         // Not found on class or superclass directly
3046         interfaceCandidates.removeLessSpecifics();
3047         return interfaceCandidates.getFirst(); // may be null
3048     }
3049 
3050     private Method privateGetMethodRecursive(String name,
3051             Class<?>[] parameterTypes,
3052             boolean includeStaticMethods,
3053             MethodArray allInterfaceCandidates) {
3054         // Note: the intent is that the search algorithm this routine
3055         // uses be equivalent to the ordering imposed by
3056         // privateGetPublicMethods(). It fetches only the declared
3057         // public methods for each class, however, to reduce the
3058         // number of Method objects which have to be created for the
3059         // common case where the method being requested is declared in
3060         // the class which is being queried.
3061         //
3062         // Due to default methods, unless a method is found on a superclass,
3063         // methods declared in any superinterface needs to be considered.
3064         // Collect all candidates declared in superinterfaces in {@code
3065         // allInterfaceCandidates} and select the most specific if no match on
3066         // a superclass is found.
3067 
3068         // Must _not_ return root methods
3069         Method res;
3070         // Search declared public methods
3071         if ((res = searchMethods(privateGetDeclaredMethods(true),
3072                                  name,
3073                                  parameterTypes)) != null) {
3074             if (includeStaticMethods || !Modifier.isStatic(res.getModifiers()))
3075                 return res;
3076         }
3077         // Search superclass's methods
3078         if (!isInterface()) {
3079             Class<? super T> c = getSuperclass();
3080             if (c != null) {
3081                 if ((res = c.getMethod0(name, parameterTypes, true)) != null) {
3082                     return res;
3083                 }
3084             }
3085         }
3086         // Search superinterfaces' methods
3087         Class<?>[] interfaces = getInterfaces();
3088         for (Class<?> c : interfaces)
3089             if ((res = c.getMethod0(name, parameterTypes, false)) != null)
3090                 allInterfaceCandidates.add(res);
3091         // Not found
3092         return null;
3093     }
3094 
3095     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3096                                         int which) throws NoSuchMethodException
3097     {
3098         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3099         for (Constructor<T> constructor : constructors) {
3100             if (arrayContentsEq(parameterTypes,
3101                                 constructor.getParameterTypes())) {
3102                 return getReflectionFactory().copyConstructor(constructor);
3103             }
3104         }
3105         throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
3106     }
3107 
3108     //
3109     // Other helpers and base implementation
3110     //
3111 
3112     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3113         if (a1 == null) {
3114             return a2 == null || a2.length == 0;
3115         }
3116 
3117         if (a2 == null) {
3118             return a1.length == 0;
3119         }
3120 
3121         if (a1.length != a2.length) {
3122             return false;
3123         }
3124 
3125         for (int i = 0; i < a1.length; i++) {
3126             if (a1[i] != a2[i]) {
3127                 return false;
3128             }
3129         }
3130 
3131         return true;
3132     }
3133 
3134     private static Field[] copyFields(Field[] arg) {
3135         Field[] out = new Field[arg.length];
3136         ReflectionFactory fact = getReflectionFactory();
3137         for (int i = 0; i < arg.length; i++) {
3138             out[i] = fact.copyField(arg[i]);
3139         }
3140         return out;
3141     }
3142 
3143     private static Method[] copyMethods(Method[] arg) {
3144         Method[] out = new Method[arg.length];
3145         ReflectionFactory fact = getReflectionFactory();
3146         for (int i = 0; i < arg.length; i++) {
3147             out[i] = fact.copyMethod(arg[i]);
3148         }
3149         return out;
3150     }
3151 
3152     private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
3153         Constructor<U>[] out = arg.clone();
3154         ReflectionFactory fact = getReflectionFactory();
3155         for (int i = 0; i < out.length; i++) {
3156             out[i] = fact.copyConstructor(out[i]);
3157         }
3158         return out;
3159     }
3160 
3161     private native Field[]       getDeclaredFields0(boolean publicOnly);
3162     private native Method[]      getDeclaredMethods0(boolean publicOnly);
3163     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3164     private native Class<?>[]   getDeclaredClasses0();
3165 
3166     private static String        argumentTypesToString(Class<?>[] argTypes) {
3167         StringJoiner sj = new StringJoiner(", ", "(", ")");
3168         if (argTypes != null) {
3169             for (int i = 0; i < argTypes.length; i++) {
3170                 Class<?> c = argTypes[i];
3171                 sj.add((c == null) ? "null" : c.getName());
3172             }
3173         }
3174         return sj.toString();
3175     }
3176 
3177     /** use serialVersionUID from JDK 1.1 for interoperability */
3178     private static final long serialVersionUID = 3206093459760846163L;
3179 
3180 
3181     /**
3182      * Class Class is special cased within the Serialization Stream Protocol.
3183      *
3184      * A Class instance is written initially into an ObjectOutputStream in the
3185      * following format:
3186      * <pre>
3187      *      {@code TC_CLASS} ClassDescriptor
3188      *      A ClassDescriptor is a special cased serialization of
3189      *      a {@code java.io.ObjectStreamClass} instance.
3190      * </pre>
3191      * A new handle is generated for the initial time the class descriptor
3192      * is written into the stream. Future references to the class descriptor
3193      * are written as references to the initial class descriptor instance.
3194      *
3195      * @see java.io.ObjectStreamClass
3196      */
3197     private static final ObjectStreamField[] serialPersistentFields =
3198         new ObjectStreamField[0];
3199 
3200 
3201     /**
3202      * Returns the assertion status that would be assigned to this
3203      * class if it were to be initialized at the time this method is invoked.
3204      * If this class has had its assertion status set, the most recent
3205      * setting will be returned; otherwise, if any package default assertion
3206      * status pertains to this class, the most recent setting for the most
3207      * specific pertinent package default assertion status is returned;
3208      * otherwise, if this class is not a system class (i.e., it has a
3209      * class loader) its class loader's default assertion status is returned;
3210      * otherwise, the system class default assertion status is returned.
3211      * <p>
3212      * Few programmers will have any need for this method; it is provided
3213      * for the benefit of the JRE itself.  (It allows a class to determine at
3214      * the time that it is initialized whether assertions should be enabled.)
3215      * Note that this method is not guaranteed to return the actual
3216      * assertion status that was (or will be) associated with the specified
3217      * class when it was (or will be) initialized.
3218      *
3219      * @return the desired assertion status of the specified class.
3220      * @see    java.lang.ClassLoader#setClassAssertionStatus
3221      * @see    java.lang.ClassLoader#setPackageAssertionStatus
3222      * @see    java.lang.ClassLoader#setDefaultAssertionStatus
3223      * @since  1.4
3224      */
3225     public boolean desiredAssertionStatus() {
3226         ClassLoader loader = getClassLoader();
3227         // If the loader is null this is a system class, so ask the VM
3228         if (loader == null)
3229             return desiredAssertionStatus0(this);
3230 
3231         // If the classloader has been initialized with the assertion
3232         // directives, ask it. Otherwise, ask the VM.
3233         synchronized(loader.assertionLock) {
3234             if (loader.classAssertionStatus != null) {
3235                 return loader.desiredAssertionStatus(getName());
3236             }
3237         }
3238         return desiredAssertionStatus0(this);
3239     }
3240 
3241     // Retrieves the desired assertion status of this class from the VM
3242     private static native boolean desiredAssertionStatus0(Class<?> clazz);
3243 
3244     /**
3245      * Returns true if and only if this class was declared as an enum in the
3246      * source code.
3247      *
3248      * @return true if and only if this class was declared as an enum in the
3249      *     source code
3250      * @since 1.5
3251      */
3252     public boolean isEnum() {
3253         // An enum must both directly extend java.lang.Enum and have
3254         // the ENUM bit set; classes for specialized enum constants
3255         // don't do the former.
3256         return (this.getModifiers() & ENUM) != 0 &&
3257         this.getSuperclass() == java.lang.Enum.class;
3258     }
3259 
3260     // Fetches the factory for reflective objects
3261     private static ReflectionFactory getReflectionFactory() {
3262         if (reflectionFactory == null) {
3263             reflectionFactory =
3264                 java.security.AccessController.doPrivileged
3265                     (new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());
3266         }
3267         return reflectionFactory;
3268     }
3269     private static ReflectionFactory reflectionFactory;
3270 
3271     // To be able to query system properties as soon as they're available
3272     private static boolean initted = false;
3273     private static void checkInitted() {
3274         if (initted) return;
3275         AccessController.doPrivileged(new PrivilegedAction<>() {
3276                 public Void run() {
3277                     // Tests to ensure the system properties table is fully
3278                     // initialized. This is needed because reflection code is
3279                     // called very early in the initialization process (before
3280                     // command-line arguments have been parsed and therefore
3281                     // these user-settable properties installed.) We assume that
3282                     // if System.out is non-null then the System class has been
3283                     // fully initialized and that the bulk of the startup code
3284                     // has been run.
3285 
3286                     if (System.out == null) {
3287                         // java.lang.System not yet fully initialized
3288                         return null;
3289                     }
3290 
3291                     // Doesn't use Boolean.getBoolean to avoid class init.
3292                     String val =
3293                         System.getProperty("sun.reflect.noCaches");
3294                     if (val != null && val.equals("true")) {
3295                         useCaches = false;
3296                     }
3297 
3298                     initted = true;
3299                     return null;
3300                 }
3301             });
3302     }
3303 
3304     /**
3305      * Returns the elements of this enum class or null if this
3306      * Class object does not represent an enum type.
3307      *
3308      * @return an array containing the values comprising the enum class
3309      *     represented by this Class object in the order they're
3310      *     declared, or null if this Class object does not
3311      *     represent an enum type
3312      * @since 1.5
3313      */
3314     public T[] getEnumConstants() {
3315         T[] values = getEnumConstantsShared();
3316         return (values != null) ? values.clone() : null;
3317     }
3318 
3319     /**
3320      * Returns the elements of this enum class or null if this
3321      * Class object does not represent an enum type;
3322      * identical to getEnumConstants except that the result is
3323      * uncloned, cached, and shared by all callers.
3324      */
3325     T[] getEnumConstantsShared() {
3326         if (enumConstants == null) {
3327             if (!isEnum()) return null;
3328             try {
3329                 final Method values = getMethod("values");
3330                 java.security.AccessController.doPrivileged(
3331                     new java.security.PrivilegedAction<>() {
3332                         public Void run() {
3333                                 values.setAccessible(true);
3334                                 return null;
3335                             }
3336                         });
3337                 @SuppressWarnings("unchecked")
3338                 T[] temporaryConstants = (T[])values.invoke(null);
3339                 enumConstants = temporaryConstants;
3340             }
3341             // These can happen when users concoct enum-like classes
3342             // that don't comply with the enum spec.
3343             catch (InvocationTargetException | NoSuchMethodException |
3344                    IllegalAccessException ex) { return null; }
3345         }
3346         return enumConstants;
3347     }
3348     private volatile transient T[] enumConstants = null;
3349 
3350     /**
3351      * Returns a map from simple name to enum constant.  This package-private
3352      * method is used internally by Enum to implement
3353      * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}
3354      * efficiently.  Note that the map is returned by this method is
3355      * created lazily on first use.  Typically it won't ever get created.
3356      */
3357     Map<String, T> enumConstantDirectory() {
3358         if (enumConstantDirectory == null) {
3359             T[] universe = getEnumConstantsShared();
3360             if (universe == null)
3361                 throw new IllegalArgumentException(
3362                     getName() + " is not an enum type");
3363             Map<String, T> m = new HashMap<>(2 * universe.length);
3364             for (T constant : universe)
3365                 m.put(((Enum<?>)constant).name(), constant);
3366             enumConstantDirectory = m;
3367         }
3368         return enumConstantDirectory;
3369     }
3370     private volatile transient Map<String, T> enumConstantDirectory = null;
3371 
3372     /**
3373      * Casts an object to the class or interface represented
3374      * by this {@code Class} object.
3375      *
3376      * @param obj the object to be cast
3377      * @return the object after casting, or null if obj is null
3378      *
3379      * @throws ClassCastException if the object is not
3380      * null and is not assignable to the type T.
3381      *
3382      * @since 1.5
3383      */
3384     @SuppressWarnings("unchecked")
3385     public T cast(Object obj) {
3386         if (obj != null && !isInstance(obj))
3387             throw new ClassCastException(cannotCastMsg(obj));
3388         return (T) obj;
3389     }
3390 
3391     private String cannotCastMsg(Object obj) {
3392         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3393     }
3394 
3395     /**
3396      * Casts this {@code Class} object to represent a subclass of the class
3397      * represented by the specified class object.  Checks that the cast
3398      * is valid, and throws a {@code ClassCastException} if it is not.  If
3399      * this method succeeds, it always returns a reference to this class object.
3400      *
3401      * <p>This method is useful when a client needs to "narrow" the type of
3402      * a {@code Class} object to pass it to an API that restricts the
3403      * {@code Class} objects that it is willing to accept.  A cast would
3404      * generate a compile-time warning, as the correctness of the cast
3405      * could not be checked at runtime (because generic types are implemented
3406      * by erasure).
3407      *
3408      * @param <U> the type to cast this class object to
3409      * @param clazz the class of the type to cast this class object to
3410      * @return this {@code Class} object, cast to represent a subclass of
3411      *    the specified class object.
3412      * @throws ClassCastException if this {@code Class} object does not
3413      *    represent a subclass of the specified class (here "subclass" includes
3414      *    the class itself).
3415      * @since 1.5
3416      */
3417     @SuppressWarnings("unchecked")
3418     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
3419         if (clazz.isAssignableFrom(this))
3420             return (Class<? extends U>) this;
3421         else
3422             throw new ClassCastException(this.toString());
3423     }
3424 
3425     /**
3426      * @throws NullPointerException {@inheritDoc}
3427      * @since 1.5
3428      */
3429     @SuppressWarnings("unchecked")
3430     public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
3431         Objects.requireNonNull(annotationClass);
3432 
3433         return (A) annotationData().annotations.get(annotationClass);
3434     }
3435 
3436     /**
3437      * {@inheritDoc}
3438      * @throws NullPointerException {@inheritDoc}
3439      * @since 1.5
3440      */
3441     @Override
3442     public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
3443         return GenericDeclaration.super.isAnnotationPresent(annotationClass);
3444     }
3445 
3446     /**
3447      * @throws NullPointerException {@inheritDoc}
3448      * @since 1.8
3449      */
3450     @Override
3451     public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {
3452         Objects.requireNonNull(annotationClass);
3453 
3454         AnnotationData annotationData = annotationData();
3455         return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations,
3456                                                           this,
3457                                                           annotationClass);
3458     }
3459 
3460     /**
3461      * @since 1.5
3462      */
3463     public Annotation[] getAnnotations() {
3464         return AnnotationParser.toArray(annotationData().annotations);
3465     }
3466 
3467     /**
3468      * @throws NullPointerException {@inheritDoc}
3469      * @since 1.8
3470      */
3471     @Override
3472     @SuppressWarnings("unchecked")
3473     public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
3474         Objects.requireNonNull(annotationClass);
3475 
3476         return (A) annotationData().declaredAnnotations.get(annotationClass);
3477     }
3478 
3479     /**
3480      * @throws NullPointerException {@inheritDoc}
3481      * @since 1.8
3482      */
3483     @Override
3484     public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {
3485         Objects.requireNonNull(annotationClass);
3486 
3487         return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,
3488                                                                  annotationClass);
3489     }
3490 
3491     /**
3492      * @since 1.5
3493      */
3494     public Annotation[] getDeclaredAnnotations()  {
3495         return AnnotationParser.toArray(annotationData().declaredAnnotations);
3496     }
3497 
3498     // annotation data that might get invalidated when JVM TI RedefineClasses() is called
3499     private static class AnnotationData {
3500         final Map<Class<? extends Annotation>, Annotation> annotations;
3501         final Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
3502 
3503         // Value of classRedefinedCount when we created this AnnotationData instance
3504         final int redefinedCount;
3505 
3506         AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations,
3507                        Map<Class<? extends Annotation>, Annotation> declaredAnnotations,
3508                        int redefinedCount) {
3509             this.annotations = annotations;
3510             this.declaredAnnotations = declaredAnnotations;
3511             this.redefinedCount = redefinedCount;
3512         }
3513     }
3514 
3515     // Annotations cache
3516     @SuppressWarnings("UnusedDeclaration")
3517     private volatile transient AnnotationData annotationData;
3518 
3519     private AnnotationData annotationData() {
3520         while (true) { // retry loop
3521             AnnotationData annotationData = this.annotationData;
3522             int classRedefinedCount = this.classRedefinedCount;
3523             if (annotationData != null &&
3524                 annotationData.redefinedCount == classRedefinedCount) {
3525                 return annotationData;
3526             }
3527             // null or stale annotationData -> optimistically create new instance
3528             AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount);
3529             // try to install it
3530             if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) {
3531                 // successfully installed new AnnotationData
3532                 return newAnnotationData;
3533             }
3534         }
3535     }
3536 
3537     private AnnotationData createAnnotationData(int classRedefinedCount) {
3538         Map<Class<? extends Annotation>, Annotation> declaredAnnotations =
3539             AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this);
3540         Class<?> superClass = getSuperclass();
3541         Map<Class<? extends Annotation>, Annotation> annotations = null;
3542         if (superClass != null) {
3543             Map<Class<? extends Annotation>, Annotation> superAnnotations =
3544                 superClass.annotationData().annotations;
3545             for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) {
3546                 Class<? extends Annotation> annotationClass = e.getKey();
3547                 if (AnnotationType.getInstance(annotationClass).isInherited()) {
3548                     if (annotations == null) { // lazy construction
3549                         annotations = new LinkedHashMap<>((Math.max(
3550                                 declaredAnnotations.size(),
3551                                 Math.min(12, declaredAnnotations.size() + superAnnotations.size())
3552                             ) * 4 + 2) / 3
3553                         );
3554                     }
3555                     annotations.put(annotationClass, e.getValue());
3556                 }
3557             }
3558         }
3559         if (annotations == null) {
3560             // no inherited annotations -> share the Map with declaredAnnotations
3561             annotations = declaredAnnotations;
3562         } else {
3563             // at least one inherited annotation -> declared may override inherited
3564             annotations.putAll(declaredAnnotations);
3565         }
3566         return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount);
3567     }
3568 
3569     // Annotation types cache their internal (AnnotationType) form
3570 
3571     @SuppressWarnings("UnusedDeclaration")
3572     private volatile transient AnnotationType annotationType;
3573 
3574     boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {
3575         return Atomic.casAnnotationType(this, oldType, newType);
3576     }
3577 
3578     AnnotationType getAnnotationType() {
3579         return annotationType;
3580     }
3581 
3582     Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() {
3583         return annotationData().declaredAnnotations;
3584     }
3585 
3586     /* Backing store of user-defined values pertaining to this class.
3587      * Maintained by the ClassValue class.
3588      */
3589     transient ClassValue.ClassValueMap classValueMap;
3590 
3591     /**
3592      * Returns an {@code AnnotatedType} object that represents the use of a
3593      * type to specify the superclass of the entity represented by this {@code
3594      * Class} object. (The <em>use</em> of type Foo to specify the superclass
3595      * in '...  extends Foo' is distinct from the <em>declaration</em> of type
3596      * Foo.)
3597      *
3598      * <p> If this {@code Class} object represents a type whose declaration
3599      * does not explicitly indicate an annotated superclass, then the return
3600      * value is an {@code AnnotatedType} object representing an element with no
3601      * annotations.
3602      *
3603      * <p> If this {@code Class} represents either the {@code Object} class, an
3604      * interface type, an array type, a primitive type, or void, the return
3605      * value is {@code null}.
3606      *
3607      * @return an object representing the superclass
3608      * @since 1.8
3609      */
3610     public AnnotatedType getAnnotatedSuperclass() {
3611         if (this == Object.class ||
3612                 isInterface() ||
3613                 isArray() ||
3614                 isPrimitive() ||
3615                 this == Void.TYPE) {
3616             return null;
3617         }
3618 
3619         return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
3620     }
3621 
3622     /**
3623      * Returns an array of {@code AnnotatedType} objects that represent the use
3624      * of types to specify superinterfaces of the entity represented by this
3625      * {@code Class} object. (The <em>use</em> of type Foo to specify a
3626      * superinterface in '... implements Foo' is distinct from the
3627      * <em>declaration</em> of type Foo.)
3628      *
3629      * <p> If this {@code Class} object represents a class, the return value is
3630      * an array containing objects representing the uses of interface types to
3631      * specify interfaces implemented by the class. The order of the objects in
3632      * the array corresponds to the order of the interface types used in the
3633      * 'implements' clause of the declaration of this {@code Class} object.
3634      *
3635      * <p> If this {@code Class} object represents an interface, the return
3636      * value is an array containing objects representing the uses of interface
3637      * types to specify interfaces directly extended by the interface. The
3638      * order of the objects in the array corresponds to the order of the
3639      * interface types used in the 'extends' clause of the declaration of this
3640      * {@code Class} object.
3641      *
3642      * <p> If this {@code Class} object represents a class or interface whose
3643      * declaration does not explicitly indicate any annotated superinterfaces,
3644      * the return value is an array of length 0.
3645      *
3646      * <p> If this {@code Class} object represents either the {@code Object}
3647      * class, an array type, a primitive type, or void, the return value is an
3648      * array of length 0.
3649      *
3650      * @return an array representing the superinterfaces
3651      * @since 1.8
3652      */
3653     public AnnotatedType[] getAnnotatedInterfaces() {
3654          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3655     }
3656 }