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