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