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