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