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