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