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