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