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