1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1994, 2014, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package java.lang;
28 
29 import dalvik.annotation.optimization.FastNative;
30 
31 import java.io.InputStream;
32 import java.io.Serializable;
33 import java.lang.annotation.Annotation;
34 import java.lang.annotation.Inherited;
35 import java.lang.reflect.AnnotatedElement;
36 import java.lang.reflect.Array;
37 import java.lang.reflect.Constructor;
38 import java.lang.reflect.Field;
39 import java.lang.reflect.GenericDeclaration;
40 import java.lang.reflect.Member;
41 import java.lang.reflect.Method;
42 import java.lang.reflect.Modifier;
43 import java.lang.reflect.Type;
44 import java.lang.reflect.TypeVariable;
45 import java.util.ArrayList;
46 import java.util.Arrays;
47 import java.util.Collection;
48 import java.util.Collections;
49 import java.util.HashMap;
50 import java.util.List;
51 import java.util.Objects;
52 import libcore.reflect.GenericSignatureParser;
53 import libcore.reflect.InternalNames;
54 import libcore.reflect.Types;
55 import libcore.util.BasicLruCache;
56 import libcore.util.CollectionUtils;
57 import libcore.util.EmptyArray;
58 
59 import dalvik.system.ClassExt;
60 import dalvik.system.VMStack;
61 import sun.reflect.CallerSensitive;
62 
63 /**
64  * Instances of the class {@code Class} represent classes and
65  * interfaces in a running Java application.  An enum is a kind of
66  * class and an annotation is a kind of interface.  Every array also
67  * belongs to a class that is reflected as a {@code Class} object
68  * that is shared by all arrays with the same element type and number
69  * of dimensions.  The primitive Java types ({@code boolean},
70  * {@code byte}, {@code char}, {@code short},
71  * {@code int}, {@code long}, {@code float}, and
72  * {@code double}), and the keyword {@code void} are also
73  * represented as {@code Class} objects.
74  *
75  * <p> {@code Class} has no public constructor. Instead {@code Class}
76  * objects are constructed automatically by the Java Virtual Machine as classes
77  * are loaded and by calls to the {@code defineClass} method in the class
78  * loader.
79  *
80  * <p> The following example uses a {@code Class} object to print the
81  * class name of an object:
82  *
83  * <blockquote><pre>
84  *     void printClassName(Object obj) {
85  *         System.out.println("The class of " + obj +
86  *                            " is " + obj.getClass().getName());
87  *     }
88  * </pre></blockquote>
89  *
90  * <p> It is also possible to get the {@code Class} object for a named
91  * type (or for void) using a class literal.  See Section 15.8.2 of
92  * <cite>The Java&trade; Language Specification</cite>.
93  * For example:
94  *
95  * <blockquote>
96  *     {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
97  * </blockquote>
98  *
99  * @param <T> the type of the class modeled by this {@code Class}
100  * object.  For example, the type of {@code String.class} is {@code
101  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
102  * unknown.
103  *
104  * @author  unascribed
105  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
106  * @since   JDK1.0
107  */
108 public final class Class<T> implements java.io.Serializable,
109                               GenericDeclaration,
110                               Type,
111                               AnnotatedElement {
112     private static final int ANNOTATION= 0x00002000;
113     private static final int ENUM      = 0x00004000;
114     private static final int SYNTHETIC = 0x00001000;
115     private static final int FINALIZABLE = 0x80000000;
116 
117     /** defining class loader, or null for the "bootstrap" system loader. */
118     private transient ClassLoader classLoader;
119 
120     /**
121      * For array classes, the component class object for instanceof/checkcast (for String[][][],
122      * this will be String[][]). null for non-array classes.
123      */
124     private transient Class<?> componentType;
125 
126     /**
127      * DexCache of resolved constant pool entries. Will be null for certain runtime-generated classes
128      * e.g. arrays and primitive classes.
129      */
130     private transient Object dexCache;
131 
132     /**
133      * Extra data that only some classes possess. This is allocated lazily as needed.
134      */
135     private transient ClassExt extData;
136 
137     /**
138      * The interface table (iftable_) contains pairs of a interface class and an array of the
139      * interface methods. There is one pair per interface supported by this class.  That
140      * means one pair for each interface we support directly, indirectly via superclass, or
141      * indirectly via a superinterface.  This will be null if neither we nor our superclass
142      * implement any interfaces.
143      *
144      * Why we need this: given "class Foo implements Face", declare "Face faceObj = new Foo()".
145      * Invoke faceObj.blah(), where "blah" is part of the Face interface.  We can't easily use a
146      * single vtable.
147      *
148      * For every interface a concrete class implements, we create an array of the concrete vtable_
149      * methods for the methods in the interface.
150      */
151     private transient Object[] ifTable;
152 
153     /** Lazily computed name of this class; always prefer calling getName(). */
154     private transient String name;
155 
156     /** The superclass, or null if this is java.lang.Object, an interface or primitive type. */
157     private transient Class<? super T> superClass;
158 
159     /**
160      * Virtual method table (vtable), for use by "invoke-virtual". The vtable from the superclass
161      * is copied in, and virtual methods from our class either replace those from the super or are
162      * appended. For abstract classes, methods may be created in the vtable that aren't in
163      * virtual_ methods_ for miranda methods.
164      */
165     private transient Object vtable;
166 
167     /**
168      * Instance fields. These describe the layout of the contents of an Object. Note that only the
169      * fields directly declared by this class are listed in iFields; fields declared by a
170      * superclass are listed in the superclass's Class.iFields.
171      *
172      * All instance fields that refer to objects are guaranteed to be at the beginning of the field
173      * list.  {@link Class#numReferenceInstanceFields} specifies the number of reference fields.
174      */
175     private transient long iFields;
176 
177     /** All methods with this class as the base for virtual dispatch. */
178     private transient long methods;
179 
180     /** Static fields */
181     private transient long sFields;
182 
183     /** access flags; low 16 bits are defined by VM spec */
184     private transient int accessFlags;
185 
186     /** Class flags to help the GC with object scanning. */
187     private transient int classFlags;
188 
189     /**
190      * Total size of the Class instance; used when allocating storage on GC heap.
191      * See also {@link Class#objectSize}.
192      */
193     private transient int classSize;
194 
195     /**
196      * tid used to check for recursive static initializer invocation.
197      */
198     private transient int clinitThreadId;
199 
200     /**
201      * Class def index from dex file. An index of 65535 indicates that there is no class definition,
202      * for example for an array type.
203      * TODO: really 16bits as type indices are 16bit.
204      */
205     private transient int dexClassDefIndex;
206 
207     /**
208      * Class type index from dex file, lazily computed. An index of 65535 indicates that the type
209      * index isn't known. Volatile to avoid double-checked locking bugs.
210      * TODO: really 16bits as type indices are 16bit.
211      */
212     private transient volatile int dexTypeIndex;
213 
214     /** Number of instance fields that are object references. */
215     private transient int numReferenceInstanceFields;
216 
217     /** Number of static fields that are object references. */
218     private transient int numReferenceStaticFields;
219 
220     /**
221      * Total object size; used when allocating storage on GC heap. For interfaces and abstract
222      * classes this will be zero. See also {@link Class#classSize}.
223      */
224     private transient int objectSize;
225 
226     /**
227      * Aligned object size for allocation fast path. The value is max int if the object is
228      * uninitialized or finalizable, otherwise the aligned object size.
229      */
230     private transient int objectSizeAllocFastPath;
231 
232     /**
233      * The lower 16 bits is the primitive type value, or 0 if not a primitive type; set for
234      * generated primitive classes.
235      */
236     private transient int primitiveType;
237 
238     /** Bitmap of offsets of iFields. */
239     private transient int referenceInstanceOffsets;
240 
241     /** State of class initialization */
242     private transient int status;
243 
244     /** Offset of the first virtual method copied from an interface in the methods array. */
245     private transient short copiedMethodsOffset;
246 
247     /** Offset of the first virtual method defined in this class in the methods array. */
248     private transient short virtualMethodsOffset;
249 
250     /*
251      * Private constructor. Only the Java Virtual Machine creates Class objects.
252      * This constructor is not used and prevents the default constructor being
253      * generated.
254      */
Class()255     private Class() {}
256 
257 
258     /**
259      * Converts the object to a string. The string representation is the
260      * string "class" or "interface", followed by a space, and then by the
261      * fully qualified name of the class in the format returned by
262      * {@code getName}.  If this {@code Class} object represents a
263      * primitive type, this method returns the name of the primitive type.  If
264      * this {@code Class} object represents void this method returns
265      * "void".
266      *
267      * @return a string representation of this class object.
268      */
toString()269     public String toString() {
270         return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
271             + getName();
272     }
273 
274     /**
275      * Returns a string describing this {@code Class}, including
276      * information about modifiers and type parameters.
277      *
278      * The string is formatted as a list of type modifiers, if any,
279      * followed by the kind of type (empty string for primitive types
280      * and {@code class}, {@code enum}, {@code interface}, or
281      * <code>&#64;</code>{@code interface}, as appropriate), followed
282      * by the type's name, followed by an angle-bracketed
283      * comma-separated list of the type's type parameters, if any.
284      *
285      * A space is used to separate modifiers from one another and to
286      * separate any modifiers from the kind of type. The modifiers
287      * occur in canonical order. If there are no type parameters, the
288      * type parameter list is elided.
289      *
290      * <p>Note that since information about the runtime representation
291      * of a type is being generated, modifiers not present on the
292      * originating source code or illegal on the originating source
293      * code may be present.
294      *
295      * @return a string describing this {@code Class}, including
296      * information about modifiers and type parameters
297      *
298      * @since 1.8
299      */
toGenericString()300     public String toGenericString() {
301         if (isPrimitive()) {
302             return toString();
303         } else {
304             StringBuilder sb = new StringBuilder();
305 
306             // Class modifiers are a superset of interface modifiers
307             int modifiers = getModifiers() & Modifier.classModifiers();
308             if (modifiers != 0) {
309                 sb.append(Modifier.toString(modifiers));
310                 sb.append(' ');
311             }
312 
313             if (isAnnotation()) {
314                 sb.append('@');
315             }
316             if (isInterface()) { // Note: all annotation types are interfaces
317                 sb.append("interface");
318             } else {
319                 if (isEnum())
320                     sb.append("enum");
321                 else
322                     sb.append("class");
323             }
324             sb.append(' ');
325             sb.append(getName());
326 
327             TypeVariable<?>[] typeparms = getTypeParameters();
328             if (typeparms.length > 0) {
329                 boolean first = true;
330                 sb.append('<');
331                 for(TypeVariable<?> typeparm: typeparms) {
332                     if (!first)
333                         sb.append(',');
334                     sb.append(typeparm.getTypeName());
335                     first = false;
336                 }
337                 sb.append('>');
338             }
339 
340             return sb.toString();
341         }
342     }
343 
344     /**
345      * Returns the {@code Class} object associated with the class or
346      * interface with the given string name.  Invoking this method is
347      * equivalent to:
348      *
349      * <blockquote>
350      *  {@code Class.forName(className, true, currentLoader)}
351      * </blockquote>
352      *
353      * where {@code currentLoader} denotes the defining class loader of
354      * the current class.
355      *
356      * <p> For example, the following code fragment returns the
357      * runtime {@code Class} descriptor for the class named
358      * {@code java.lang.Thread}:
359      *
360      * <blockquote>
361      *   {@code Class t = Class.forName("java.lang.Thread")}
362      * </blockquote>
363      * <p>
364      * A call to {@code forName("X")} causes the class named
365      * {@code X} to be initialized.
366      *
367      * @param      className   the fully qualified name of the desired class.
368      * @return     the {@code Class} object for the class with the
369      *             specified name.
370      * @exception LinkageError if the linkage fails
371      * @exception ExceptionInInitializerError if the initialization provoked
372      *            by this method fails
373      * @exception ClassNotFoundException if the class cannot be located
374      */
375     @CallerSensitive
forName(String className)376     public static Class<?> forName(String className)
377                 throws ClassNotFoundException {
378         return forName(className, true, VMStack.getCallingClassLoader());
379     }
380 
381 
382     /**
383      * Returns the {@code Class} object associated with the class or
384      * interface with the given string name, using the given class loader.
385      * Given the fully qualified name for a class or interface (in the same
386      * format returned by {@code getName}) this method attempts to
387      * locate, load, and link the class or interface.  The specified class
388      * loader is used to load the class or interface.  If the parameter
389      * {@code loader} is null, the class is loaded through the bootstrap
390      * class loader.  The class is initialized only if the
391      * {@code initialize} parameter is {@code true} and if it has
392      * not been initialized earlier.
393      *
394      * <p> If {@code name} denotes a primitive type or void, an attempt
395      * will be made to locate a user-defined class in the unnamed package whose
396      * name is {@code name}. Therefore, this method cannot be used to
397      * obtain any of the {@code Class} objects representing primitive
398      * types or void.
399      *
400      * <p> If {@code name} denotes an array class, the component type of
401      * the array class is loaded but not initialized.
402      *
403      * <p> For example, in an instance method the expression:
404      *
405      * <blockquote>
406      *  {@code Class.forName("Foo")}
407      * </blockquote>
408      *
409      * is equivalent to:
410      *
411      * <blockquote>
412      *  {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
413      * </blockquote>
414      *
415      * Note that this method throws errors related to loading, linking or
416      * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
417      * Java Language Specification</em>.
418      * Note that this method does not check whether the requested class
419      * is accessible to its caller.
420      *
421      * <p> If the {@code loader} is {@code null}, and a security
422      * manager is present, and the caller's class loader is not null, then this
423      * method calls the security manager's {@code checkPermission} method
424      * with a {@code RuntimePermission("getClassLoader")} permission to
425      * ensure it's ok to access the bootstrap class loader.
426      *
427      * @param name       fully qualified name of the desired class
428      * @param initialize if {@code true} the class will be initialized.
429      *                   See Section 12.4 of <em>The Java Language Specification</em>.
430      * @param loader     class loader from which the class must be loaded
431      * @return           class object representing the desired class
432      *
433      * @exception LinkageError if the linkage fails
434      * @exception ExceptionInInitializerError if the initialization provoked
435      *            by this method fails
436      * @exception ClassNotFoundException if the class cannot be located by
437      *            the specified class loader
438      *
439      * @see       java.lang.Class#forName(String)
440      * @see       java.lang.ClassLoader
441      * @since     1.2
442      */
443     @CallerSensitive
forName(String name, boolean initialize, ClassLoader loader)444     public static Class<?> forName(String name, boolean initialize,
445                                    ClassLoader loader)
446         throws ClassNotFoundException
447     {
448         if (loader == null) {
449             loader = BootClassLoader.getInstance();
450         }
451         Class<?> result;
452         try {
453             result = classForName(name, initialize, loader);
454         } catch (ClassNotFoundException e) {
455             Throwable cause = e.getCause();
456             if (cause instanceof LinkageError) {
457                 throw (LinkageError) cause;
458             }
459             throw e;
460         }
461         return result;
462     }
463 
464     /** Called after security checks have been made. */
465     @FastNative
classForName(String className, boolean shouldInitialize, ClassLoader classLoader)466     static native Class<?> classForName(String className, boolean shouldInitialize,
467             ClassLoader classLoader) throws ClassNotFoundException;
468 
469     /**
470      * Creates a new instance of the class represented by this {@code Class}
471      * object.  The class is instantiated as if by a {@code new}
472      * expression with an empty argument list.  The class is initialized if it
473      * has not already been initialized.
474      *
475      * <p>Note that this method propagates any exception thrown by the
476      * nullary constructor, including a checked exception.  Use of
477      * this method effectively bypasses the compile-time exception
478      * checking that would otherwise be performed by the compiler.
479      * The {@link
480      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
481      * Constructor.newInstance} method avoids this problem by wrapping
482      * any exception thrown by the constructor in a (checked) {@link
483      * java.lang.reflect.InvocationTargetException}.
484      *
485      * @return  a newly allocated instance of the class represented by this
486      *          object.
487      * @throws  IllegalAccessException  if the class or its nullary
488      *          constructor is not accessible.
489      * @throws  InstantiationException
490      *          if this {@code Class} represents an abstract class,
491      *          an interface, an array class, a primitive type, or void;
492      *          or if the class has no nullary constructor;
493      *          or if the instantiation fails for some other reason.
494      * @throws  ExceptionInInitializerError if the initialization
495      *          provoked by this method fails.
496      * @throws  SecurityException
497      *          If a security manager, <i>s</i>, is present and
498      *          the caller's class loader is not the same as or an
499      *          ancestor of the class loader for the current class and
500      *          invocation of {@link SecurityManager#checkPackageAccess
501      *          s.checkPackageAccess()} denies access to the package
502      *          of this class.
503      */
504     @FastNative
newInstance()505     public native T newInstance() throws InstantiationException, IllegalAccessException;
506 
507     /**
508      * Determines if the specified {@code Object} is assignment-compatible
509      * with the object represented by this {@code Class}.  This method is
510      * the dynamic equivalent of the Java language {@code instanceof}
511      * operator. The method returns {@code true} if the specified
512      * {@code Object} argument is non-null and can be cast to the
513      * reference type represented by this {@code Class} object without
514      * raising a {@code ClassCastException.} It returns {@code false}
515      * otherwise.
516      *
517      * <p> Specifically, if this {@code Class} object represents a
518      * declared class, this method returns {@code true} if the specified
519      * {@code Object} argument is an instance of the represented class (or
520      * of any of its subclasses); it returns {@code false} otherwise. If
521      * this {@code Class} object represents an array class, this method
522      * returns {@code true} if the specified {@code Object} argument
523      * can be converted to an object of the array class by an identity
524      * conversion or by a widening reference conversion; it returns
525      * {@code false} otherwise. If this {@code Class} object
526      * represents an interface, this method returns {@code true} if the
527      * class or any superclass of the specified {@code Object} argument
528      * implements this interface; it returns {@code false} otherwise. If
529      * this {@code Class} object represents a primitive type, this method
530      * returns {@code false}.
531      *
532      * @param   obj the object to check
533      * @return  true if {@code obj} is an instance of this class
534      *
535      * @since JDK1.1
536      */
isInstance(Object obj)537     public boolean isInstance(Object obj) {
538         if (obj == null) {
539             return false;
540         }
541         return isAssignableFrom(obj.getClass());
542     }
543 
544 
545     /**
546      * Determines if the class or interface represented by this
547      * {@code Class} object is either the same as, or is a superclass or
548      * superinterface of, the class or interface represented by the specified
549      * {@code Class} parameter. It returns {@code true} if so;
550      * otherwise it returns {@code false}. If this {@code Class}
551      * object represents a primitive type, this method returns
552      * {@code true} if the specified {@code Class} parameter is
553      * exactly this {@code Class} object; otherwise it returns
554      * {@code false}.
555      *
556      * <p> Specifically, this method tests whether the type represented by the
557      * specified {@code Class} parameter can be converted to the type
558      * represented by this {@code Class} object via an identity conversion
559      * or via a widening reference conversion. See <em>The Java Language
560      * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
561      *
562      * @param cls the {@code Class} object to be checked
563      * @return the {@code boolean} value indicating whether objects of the
564      * type {@code cls} can be assigned to objects of this class
565      * @exception NullPointerException if the specified Class parameter is
566      *            null.
567      * @since JDK1.1
568      */
isAssignableFrom(Class<?> cls)569     public boolean isAssignableFrom(Class<?> cls) {
570         if (this == cls) {
571             return true;  // Can always assign to things of the same type.
572         } else if (this == Object.class) {
573             return !cls.isPrimitive();  // Can assign any reference to java.lang.Object.
574         } else if (isArray()) {
575             return cls.isArray() && componentType.isAssignableFrom(cls.componentType);
576         } else if (isInterface()) {
577             // Search iftable which has a flattened and uniqued list of interfaces.
578             Object[] iftable = cls.ifTable;
579             if (iftable != null) {
580                 for (int i = 0; i < iftable.length; i += 2) {
581                     if (iftable[i] == this) {
582                         return true;
583                     }
584                 }
585             }
586             return false;
587         } else {
588             if (!cls.isInterface()) {
589                 for (cls = cls.superClass; cls != null; cls = cls.superClass) {
590                     if (cls == this) {
591                         return true;
592                     }
593                 }
594             }
595             return false;
596         }
597     }
598 
599     /**
600      * Determines if the specified {@code Class} object represents an
601      * interface type.
602      *
603      * @return  {@code true} if this object represents an interface;
604      *          {@code false} otherwise.
605      */
isInterface()606     public boolean isInterface() {
607         return (accessFlags & Modifier.INTERFACE) != 0;
608     }
609 
610     /**
611      * Determines if this {@code Class} object represents an array class.
612      *
613      * @return  {@code true} if this object represents an array class;
614      *          {@code false} otherwise.
615      * @since   JDK1.1
616      */
isArray()617     public boolean isArray() {
618         return getComponentType() != null;
619     }
620 
621     /**
622      * Determines if the specified {@code Class} object represents a
623      * primitive type.
624      *
625      * <p> There are nine predefined {@code Class} objects to represent
626      * the eight primitive types and void.  These are created by the Java
627      * Virtual Machine, and have the same names as the primitive types that
628      * they represent, namely {@code boolean}, {@code byte},
629      * {@code char}, {@code short}, {@code int},
630      * {@code long}, {@code float}, and {@code double}.
631      *
632      * <p> These objects may only be accessed via the following public static
633      * final variables, and are the only {@code Class} objects for which
634      * this method returns {@code true}.
635      *
636      * @return true if and only if this class represents a primitive type
637      *
638      * @see     java.lang.Boolean#TYPE
639      * @see     java.lang.Character#TYPE
640      * @see     java.lang.Byte#TYPE
641      * @see     java.lang.Short#TYPE
642      * @see     java.lang.Integer#TYPE
643      * @see     java.lang.Long#TYPE
644      * @see     java.lang.Float#TYPE
645      * @see     java.lang.Double#TYPE
646      * @see     java.lang.Void#TYPE
647      * @since JDK1.1
648      */
isPrimitive()649     public boolean isPrimitive() {
650       return (primitiveType & 0xFFFF) != 0;
651     }
652 
653     /**
654      * Indicates whether this {@code Class} or its parents override finalize.
655      *
656      * @return {@code true} if and if this class or its parents override
657      *         finalize;
658      *
659      * @hide
660      */
isFinalizable()661     public boolean isFinalizable() {
662         return (getModifiers() & FINALIZABLE) != 0;
663     }
664 
665     /**
666      * Returns true if this {@code Class} object represents an annotation
667      * type.  Note that if this method returns true, {@link #isInterface()}
668      * would also return true, as all annotation types are also interfaces.
669      *
670      * @return {@code true} if this class object represents an annotation
671      *      type; {@code false} otherwise
672      * @since 1.5
673      */
isAnnotation()674     public boolean isAnnotation() {
675         return (getModifiers() & ANNOTATION) != 0;
676     }
677 
678     /**
679      * Returns {@code true} if this class is a synthetic class;
680      * returns {@code false} otherwise.
681      * @return {@code true} if and only if this class is a synthetic class as
682      *         defined by the Java Language Specification.
683      * @jls 13.1 The Form of a Binary
684      * @since 1.5
685      */
isSynthetic()686     public boolean isSynthetic() {
687         return (getModifiers() & SYNTHETIC) != 0;
688     }
689 
690     /**
691      * Returns the  name of the entity (class, interface, array class,
692      * primitive type, or void) represented by this {@code Class} object,
693      * as a {@code String}.
694      *
695      * <p> If this class object represents a reference type that is not an
696      * array type then the binary name of the class is returned, as specified
697      * by
698      * <cite>The Java&trade; Language Specification</cite>.
699      *
700      * <p> If this class object represents a primitive type or void, then the
701      * name returned is a {@code String} equal to the Java language
702      * keyword corresponding to the primitive type or void.
703      *
704      * <p> If this class object represents a class of arrays, then the internal
705      * form of the name consists of the name of the element type preceded by
706      * one or more '{@code [}' characters representing the depth of the array
707      * nesting.  The encoding of element type names is as follows:
708      *
709      * <blockquote><table summary="Element types and encodings">
710      * <tr><th> Element Type <th> &nbsp;&nbsp;&nbsp; <th> Encoding
711      * <tr><td> boolean      <td> &nbsp;&nbsp;&nbsp; <td align=center> Z
712      * <tr><td> byte         <td> &nbsp;&nbsp;&nbsp; <td align=center> B
713      * <tr><td> char         <td> &nbsp;&nbsp;&nbsp; <td align=center> C
714      * <tr><td> class or interface
715      *                       <td> &nbsp;&nbsp;&nbsp; <td align=center> L<i>classname</i>;
716      * <tr><td> double       <td> &nbsp;&nbsp;&nbsp; <td align=center> D
717      * <tr><td> float        <td> &nbsp;&nbsp;&nbsp; <td align=center> F
718      * <tr><td> int          <td> &nbsp;&nbsp;&nbsp; <td align=center> I
719      * <tr><td> long         <td> &nbsp;&nbsp;&nbsp; <td align=center> J
720      * <tr><td> short        <td> &nbsp;&nbsp;&nbsp; <td align=center> S
721      * </table></blockquote>
722      *
723      * <p> The class or interface name <i>classname</i> is the binary name of
724      * the class specified above.
725      *
726      * <p> Examples:
727      * <blockquote><pre>
728      * String.class.getName()
729      *     returns "java.lang.String"
730      * byte.class.getName()
731      *     returns "byte"
732      * (new Object[3]).getClass().getName()
733      *     returns "[Ljava.lang.Object;"
734      * (new int[3][4][5][6][7][8][9]).getClass().getName()
735      *     returns "[[[[[[[I"
736      * </pre></blockquote>
737      *
738      * @return  the name of the class or interface
739      *          represented by this object.
740      */
getName()741     public String getName() {
742         String name = this.name;
743         if (name == null)
744             this.name = name = getNameNative();
745         return name;
746     }
747 
748     @FastNative
getNameNative()749     private native String getNameNative();
750 
751     /**
752      * Returns the class loader for the class.  Some implementations may use
753      * null to represent the bootstrap class loader. This method will return
754      * null in such implementations if this class was loaded by the bootstrap
755      * class loader.
756      *
757      * <p> If a security manager is present, and the caller's class loader is
758      * not null and the caller's class loader is not the same as or an ancestor of
759      * the class loader for the class whose class loader is requested, then
760      * this method calls the security manager's {@code checkPermission}
761      * method with a {@code RuntimePermission("getClassLoader")}
762      * permission to ensure it's ok to access the class loader for the class.
763      *
764      * <p>If this object
765      * represents a primitive type or void, null is returned.
766      *
767      * @return  the class loader that loaded the class or interface
768      *          represented by this object.
769      * @throws SecurityException
770      *    if a security manager exists and its
771      *    {@code checkPermission} method denies
772      *    access to the class loader for the class.
773      * @see java.lang.ClassLoader
774      * @see SecurityManager#checkPermission
775      * @see java.lang.RuntimePermission
776      */
getClassLoader()777     public ClassLoader getClassLoader() {
778         if (isPrimitive()) {
779             return null;
780         }
781         return (classLoader == null) ? BootClassLoader.getInstance() : classLoader;
782     }
783 
784     /**
785      * Returns an array of {@code TypeVariable} objects that represent the
786      * type variables declared by the generic declaration represented by this
787      * {@code GenericDeclaration} object, in declaration order.  Returns an
788      * array of length 0 if the underlying generic declaration declares no type
789      * variables.
790      *
791      * @return an array of {@code TypeVariable} objects that represent
792      *     the type variables declared by this generic declaration
793      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
794      *     signature of this generic declaration does not conform to
795      *     the format specified in
796      *     <cite>The Java&trade; Virtual Machine Specification</cite>
797      * @since 1.5
798      */
799     @Override
getTypeParameters()800     public synchronized TypeVariable<Class<T>>[] getTypeParameters() {
801         String annotationSignature = getSignatureAttribute();
802         if (annotationSignature == null) {
803             return EmptyArray.TYPE_VARIABLE;
804         }
805         GenericSignatureParser parser = new GenericSignatureParser(getClassLoader());
806         parser.parseForClass(this, annotationSignature);
807         return parser.formalTypeParameters;
808     }
809 
810 
811     /**
812      * Returns the {@code Class} representing the superclass of the entity
813      * (class, interface, primitive type or void) represented by this
814      * {@code Class}.  If this {@code Class} represents either the
815      * {@code Object} class, an interface, a primitive type, or void, then
816      * null is returned.  If this object represents an array class then the
817      * {@code Class} object representing the {@code Object} class is
818      * returned.
819      *
820      * @return the superclass of the class represented by this object.
821      */
getSuperclass()822     public Class<? super T> getSuperclass() {
823         // For interfaces superClass is Object (which agrees with the JNI spec)
824         // but not with the expected behavior here.
825         if (isInterface()) {
826             return null;
827         } else {
828             return superClass;
829         }
830     }
831 
832     /**
833      * Returns the {@code Type} representing the direct superclass of
834      * the entity (class, interface, primitive type or void) represented by
835      * this {@code Class}.
836      *
837      * <p>If the superclass is a parameterized type, the {@code Type}
838      * object returned must accurately reflect the actual type
839      * parameters used in the source code. The parameterized type
840      * representing the superclass is created if it had not been
841      * created before. See the declaration of {@link
842      * java.lang.reflect.ParameterizedType ParameterizedType} for the
843      * semantics of the creation process for parameterized types.  If
844      * this {@code Class} represents either the {@code Object}
845      * class, an interface, a primitive type, or void, then null is
846      * returned.  If this object represents an array class then the
847      * {@code Class} object representing the {@code Object} class is
848      * returned.
849      *
850      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
851      *     class signature does not conform to the format specified in
852      *     <cite>The Java&trade; Virtual Machine Specification</cite>
853      * @throws TypeNotPresentException if the generic superclass
854      *     refers to a non-existent type declaration
855      * @throws java.lang.reflect.MalformedParameterizedTypeException if the
856      *     generic superclass refers to a parameterized type that cannot be
857      *     instantiated  for any reason
858      * @return the superclass of the class represented by this object
859      * @since 1.5
860      */
getGenericSuperclass()861     public Type getGenericSuperclass() {
862         Type genericSuperclass = getSuperclass();
863         // This method is specified to return null for all cases where getSuperclass
864         // returns null, i.e, for primitives, interfaces, void and java.lang.Object.
865         if (genericSuperclass == null) {
866             return null;
867         }
868 
869         String annotationSignature = getSignatureAttribute();
870         if (annotationSignature != null) {
871             GenericSignatureParser parser = new GenericSignatureParser(getClassLoader());
872             parser.parseForClass(this, annotationSignature);
873             genericSuperclass = parser.superclassType;
874         }
875         return Types.getType(genericSuperclass);
876     }
877 
878     /**
879      * Gets the package for this class.  The class loader of this class is used
880      * to find the package.  If the class was loaded by the bootstrap class
881      * loader the set of packages loaded from CLASSPATH is searched to find the
882      * package of the class. Null is returned if no package object was created
883      * by the class loader of this class.
884      *
885      * <p> Packages have attributes for versions and specifications only if the
886      * information was defined in the manifests that accompany the classes, and
887      * if the class loader created the package instance with the attributes
888      * from the manifest.
889      *
890      * @return the package of the class, or null if no package
891      *         information is available from the archive or codebase.
892      */
getPackage()893     public Package getPackage() {
894         ClassLoader loader = getClassLoader();
895         if (loader != null) {
896             String packageName = getPackageName$();
897             return packageName != null ? loader.getPackage(packageName) : null;
898         }
899         return null;
900     }
901 
902     /**
903      * Returns the package name of this class. This returns null for classes in
904      * the default package.
905      *
906      * @hide
907      */
getPackageName$()908     public String getPackageName$() {
909         String name = getName();
910         int last = name.lastIndexOf('.');
911         return last == -1 ? null : name.substring(0, last);
912     }
913 
914 
915     /**
916      * Determines the interfaces implemented by the class or interface
917      * represented by this object.
918      *
919      * <p> If this object represents a class, the return value is an array
920      * containing objects representing all interfaces implemented by the
921      * class. The order of the interface objects in the array corresponds to
922      * the order of the interface names in the {@code implements} clause
923      * of the declaration of the class represented by this object. For
924      * example, given the declaration:
925      * <blockquote>
926      * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
927      * </blockquote>
928      * suppose the value of {@code s} is an instance of
929      * {@code Shimmer}; the value of the expression:
930      * <blockquote>
931      * {@code s.getClass().getInterfaces()[0]}
932      * </blockquote>
933      * is the {@code Class} object that represents interface
934      * {@code FloorWax}; and the value of:
935      * <blockquote>
936      * {@code s.getClass().getInterfaces()[1]}
937      * </blockquote>
938      * is the {@code Class} object that represents interface
939      * {@code DessertTopping}.
940      *
941      * <p> If this object represents an interface, the array contains objects
942      * representing all interfaces extended by the interface. The order of the
943      * interface objects in the array corresponds to the order of the interface
944      * names in the {@code extends} clause of the declaration of the
945      * interface represented by this object.
946      *
947      * <p> If this object represents a class or interface that implements no
948      * interfaces, the method returns an array of length 0.
949      *
950      * <p> If this object represents a primitive type or void, the method
951      * returns an array of length 0.
952      *
953      * <p> If this {@code Class} object represents an array type, the
954      * interfaces {@code Cloneable} and {@code java.io.Serializable} are
955      * returned in that order.
956      *
957      * @return an array of interfaces implemented by this class.
958      */
getInterfaces()959     public Class<?>[] getInterfaces() {
960         if (isArray()) {
961             return new Class<?>[] { Cloneable.class, Serializable.class };
962         }
963 
964         final Class<?>[] ifaces = getInterfacesInternal();
965         if (ifaces == null) {
966             return EmptyArray.CLASS;
967         }
968 
969         return ifaces;
970     }
971 
972     @FastNative
getInterfacesInternal()973     private native Class<?>[] getInterfacesInternal();
974 
975 
976     /**
977      * Returns the {@code Type}s representing the interfaces
978      * directly implemented by the class or interface represented by
979      * this object.
980      *
981      * <p>If a superinterface is a parameterized type, the
982      * {@code Type} object returned for it must accurately reflect
983      * the actual type parameters used in the source code. The
984      * parameterized type representing each superinterface is created
985      * if it had not been created before. See the declaration of
986      * {@link java.lang.reflect.ParameterizedType ParameterizedType}
987      * for the semantics of the creation process for parameterized
988      * types.
989      *
990      * <p> If this object represents a class, the return value is an
991      * array containing objects representing all interfaces
992      * implemented by the class. The order of the interface objects in
993      * the array corresponds to the order of the interface names in
994      * the {@code implements} clause of the declaration of the class
995      * represented by this object.  In the case of an array class, the
996      * interfaces {@code Cloneable} and {@code Serializable} are
997      * returned in that order.
998      *
999      * <p>If this object represents an interface, the array contains
1000      * objects representing all interfaces directly extended by the
1001      * interface.  The order of the interface objects in the array
1002      * corresponds to the order of the interface names in the
1003      * {@code extends} clause of the declaration of the interface
1004      * represented by this object.
1005      *
1006      * <p>If this object represents a class or interface that
1007      * implements no interfaces, the method returns an array of length
1008      * 0.
1009      *
1010      * <p>If this object represents a primitive type or void, the
1011      * method returns an array of length 0.
1012      *
1013      * @throws java.lang.reflect.GenericSignatureFormatError
1014      *     if the generic class signature does not conform to the format
1015      *     specified in
1016      *     <cite>The Java&trade; Virtual Machine Specification</cite>
1017      * @throws TypeNotPresentException if any of the generic
1018      *     superinterfaces refers to a non-existent type declaration
1019      * @throws java.lang.reflect.MalformedParameterizedTypeException
1020      *     if any of the generic superinterfaces refer to a parameterized
1021      *     type that cannot be instantiated for any reason
1022      * @return an array of interfaces implemented by this class
1023      * @since 1.5
1024      */
getGenericInterfaces()1025     public Type[] getGenericInterfaces() {
1026         Type[] result;
1027         synchronized (Caches.genericInterfaces) {
1028             result = Caches.genericInterfaces.get(this);
1029             if (result == null) {
1030                 String annotationSignature = getSignatureAttribute();
1031                 if (annotationSignature == null) {
1032                     result = getInterfaces();
1033                 } else {
1034                     GenericSignatureParser parser = new GenericSignatureParser(getClassLoader());
1035                     parser.parseForClass(this, annotationSignature);
1036                     result = Types.getTypeArray(parser.interfaceTypes, false);
1037                 }
1038                 Caches.genericInterfaces.put(this, result);
1039             }
1040         }
1041         return (result.length == 0) ? result : result.clone();
1042     }
1043 
1044 
1045     /**
1046      * Returns the {@code Class} representing the component type of an
1047      * array.  If this class does not represent an array class this method
1048      * returns null.
1049      *
1050      * @return the {@code Class} representing the component type of this
1051      * class if this class is an array
1052      * @see     java.lang.reflect.Array
1053      * @since JDK1.1
1054      */
getComponentType()1055     public Class<?> getComponentType() {
1056       return componentType;
1057     }
1058 
1059     /**
1060      * Returns the Java language modifiers for this class or interface, encoded
1061      * in an integer. The modifiers consist of the Java Virtual Machine's
1062      * constants for {@code public}, {@code protected},
1063      * {@code private}, {@code final}, {@code static},
1064      * {@code abstract} and {@code interface}; they should be decoded
1065      * using the methods of class {@code Modifier}.
1066      *
1067      * <p> If the underlying class is an array class, then its
1068      * {@code public}, {@code private} and {@code protected}
1069      * modifiers are the same as those of its component type.  If this
1070      * {@code Class} represents a primitive type or void, its
1071      * {@code public} modifier is always {@code true}, and its
1072      * {@code protected} and {@code private} modifiers are always
1073      * {@code false}. If this object represents an array class, a
1074      * primitive type or void, then its {@code final} modifier is always
1075      * {@code true} and its interface modifier is always
1076      * {@code false}. The values of its other modifiers are not determined
1077      * by this specification.
1078      *
1079      * <p> The modifier encodings are defined in <em>The Java Virtual Machine
1080      * Specification</em>, table 4.1.
1081      *
1082      * @return the {@code int} representing the modifiers for this class
1083      * @see     java.lang.reflect.Modifier
1084      * @since JDK1.1
1085      */
getModifiers()1086     public int getModifiers() {
1087         // Array classes inherit modifiers from their component types, but in the case of arrays
1088         // of an inner class, the class file may contain "fake" access flags because it's not valid
1089         // for a top-level class to private, say. The real access flags are stored in the InnerClass
1090         // attribute, so we need to make sure we drill down to the inner class: the accessFlags
1091         // field is not the value we want to return, and the synthesized array class does not itself
1092         // have an InnerClass attribute. https://code.google.com/p/android/issues/detail?id=56267
1093         if (isArray()) {
1094             int componentModifiers = getComponentType().getModifiers();
1095             if ((componentModifiers & Modifier.INTERFACE) != 0) {
1096                 componentModifiers &= ~(Modifier.INTERFACE | Modifier.STATIC);
1097             }
1098             return Modifier.ABSTRACT | Modifier.FINAL | componentModifiers;
1099         }
1100         int JAVA_FLAGS_MASK = 0xffff;
1101         int modifiers = this.getInnerClassFlags(accessFlags & JAVA_FLAGS_MASK);
1102         return modifiers & JAVA_FLAGS_MASK;
1103     }
1104 
1105     /**
1106      * Gets the signers of this class.
1107      *
1108      * @return  the signers of this class, or null if there are no signers.  In
1109      *          particular, this method returns null if this object represents
1110      *          a primitive type or void.
1111      * @since   JDK1.1
1112      */
getSigners()1113     public Object[] getSigners() {
1114         return null;
1115     }
1116 
1117     @FastNative
getEnclosingMethodNative()1118     private native Method getEnclosingMethodNative();
1119 
1120     /**
1121      * If this {@code Class} object represents a local or anonymous
1122      * class within a method, returns a {@link
1123      * java.lang.reflect.Method Method} object representing the
1124      * immediately enclosing method of the underlying class. Returns
1125      * {@code null} otherwise.
1126      *
1127      * In particular, this method returns {@code null} if the underlying
1128      * class is a local or anonymous class immediately enclosed by a type
1129      * declaration, instance initializer or static initializer.
1130      *
1131      * @return the immediately enclosing method of the underlying class, if
1132      *     that class is a local or anonymous class; otherwise {@code null}.
1133      * @since 1.5
1134      */
1135     // Android-changed: Removed SecurityException
getEnclosingMethod()1136     public Method getEnclosingMethod() {
1137         if (classNameImpliesTopLevel()) {
1138             return null;
1139         }
1140         return getEnclosingMethodNative();
1141     }
1142 
1143     /**
1144      * If this {@code Class} object represents a local or anonymous
1145      * class within a constructor, returns a {@link
1146      * java.lang.reflect.Constructor Constructor} object representing
1147      * the immediately enclosing constructor of the underlying
1148      * class. Returns {@code null} otherwise.  In particular, this
1149      * method returns {@code null} if the underlying class is a local
1150      * or anonymous class immediately enclosed by a type declaration,
1151      * instance initializer or static initializer.
1152      *
1153      * @return the immediately enclosing constructor of the underlying class, if
1154      *     that class is a local or anonymous class; otherwise {@code null}.
1155      * @since 1.5
1156      */
1157     // Android-changed: Removed SecurityException
getEnclosingConstructor()1158     public Constructor<?> getEnclosingConstructor() {
1159         if (classNameImpliesTopLevel()) {
1160             return null;
1161         }
1162         return getEnclosingConstructorNative();
1163     }
1164 
1165     @FastNative
getEnclosingConstructorNative()1166     private native Constructor<?> getEnclosingConstructorNative();
1167 
classNameImpliesTopLevel()1168     private boolean classNameImpliesTopLevel() {
1169         return !getName().contains("$");
1170     }
1171 
1172 
1173     /**
1174      * If the class or interface represented by this {@code Class} object
1175      * is a member of another class, returns the {@code Class} object
1176      * representing the class in which it was declared.  This method returns
1177      * null if this class or interface is not a member of any other class.  If
1178      * this {@code Class} object represents an array class, a primitive
1179      * type, or void,then this method returns null.
1180      *
1181      * @return the declaring class for this class
1182      * @since JDK1.1
1183      */
1184     // Android-changed: Removed SecurityException
1185     @FastNative
getDeclaringClass()1186     public native Class<?> getDeclaringClass();
1187 
1188     /**
1189      * Returns the immediately enclosing class of the underlying
1190      * class.  If the underlying class is a top level class this
1191      * method returns {@code null}.
1192      * @return the immediately enclosing class of the underlying class
1193      * @since 1.5
1194      */
1195     // Android-changed: Removed SecurityException
1196     @FastNative
getEnclosingClass()1197     public native Class<?> getEnclosingClass();
1198 
1199     /**
1200      * Returns the simple name of the underlying class as given in the
1201      * source code. Returns an empty string if the underlying class is
1202      * anonymous.
1203      *
1204      * <p>The simple name of an array is the simple name of the
1205      * component type with "[]" appended.  In particular the simple
1206      * name of an array whose component type is anonymous is "[]".
1207      *
1208      * @return the simple name of the underlying class
1209      * @since 1.5
1210      */
getSimpleName()1211     public String getSimpleName() {
1212         if (isArray())
1213             return getComponentType().getSimpleName()+"[]";
1214 
1215         if (isAnonymousClass()) {
1216             return "";
1217         }
1218 
1219         if (isMemberClass() || isLocalClass()) {
1220             // Note that we obtain this information from getInnerClassName(), which uses
1221             // dex system annotations to obtain the name. It is possible for this information
1222             // to disagree with the actual enclosing class name. For example, if dex
1223             // manipulation tools have renamed the enclosing class without adjusting
1224             // the system annotation to match. See http://b/28800927.
1225             return getInnerClassName();
1226         }
1227 
1228         String simpleName = getName();
1229         final int dot = simpleName.lastIndexOf(".");
1230         if (dot > 0) {
1231             return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
1232         }
1233 
1234         return simpleName;
1235     }
1236 
1237     /**
1238      * Return an informative string for the name of this type.
1239      *
1240      * @return an informative string for the name of this type
1241      * @since 1.8
1242      */
getTypeName()1243     public String getTypeName() {
1244         if (isArray()) {
1245             try {
1246                 Class<?> cl = this;
1247                 int dimensions = 0;
1248                 while (cl.isArray()) {
1249                     dimensions++;
1250                     cl = cl.getComponentType();
1251                 }
1252                 StringBuilder sb = new StringBuilder();
1253                 sb.append(cl.getName());
1254                 for (int i = 0; i < dimensions; i++) {
1255                     sb.append("[]");
1256                 }
1257                 return sb.toString();
1258             } catch (Throwable e) { /*FALLTHRU*/ }
1259         }
1260         return getName();
1261     }
1262 
1263     /**
1264      * Returns the canonical name of the underlying class as
1265      * defined by the Java Language Specification.  Returns null if
1266      * the underlying class does not have a canonical name (i.e., if
1267      * it is a local or anonymous class or an array whose component
1268      * type does not have a canonical name).
1269      * @return the canonical name of the underlying class if it exists, and
1270      * {@code null} otherwise.
1271      * @since 1.5
1272      */
getCanonicalName()1273     public String getCanonicalName() {
1274         if (isArray()) {
1275             String canonicalName = getComponentType().getCanonicalName();
1276             if (canonicalName != null)
1277                 return canonicalName + "[]";
1278             else
1279                 return null;
1280         }
1281         if (isLocalOrAnonymousClass())
1282             return null;
1283         Class<?> enclosingClass = getEnclosingClass();
1284         if (enclosingClass == null) { // top level class
1285             return getName();
1286         } else {
1287             String enclosingName = enclosingClass.getCanonicalName();
1288             if (enclosingName == null)
1289                 return null;
1290             return enclosingName + "." + getSimpleName();
1291         }
1292     }
1293 
1294     /**
1295      * Returns {@code true} if and only if the underlying class
1296      * is an anonymous class.
1297      *
1298      * @return {@code true} if and only if this class is an anonymous class.
1299      * @since 1.5
1300      */
1301     @FastNative
isAnonymousClass()1302     public native boolean isAnonymousClass();
1303 
1304     /**
1305      * Returns {@code true} if and only if the underlying class
1306      * is a local class.
1307      *
1308      * @return {@code true} if and only if this class is a local class.
1309      * @since 1.5
1310      */
isLocalClass()1311     public boolean isLocalClass() {
1312         return (getEnclosingMethod() != null || getEnclosingConstructor() != null)
1313                 && !isAnonymousClass();
1314     }
1315 
1316     /**
1317      * Returns {@code true} if and only if the underlying class
1318      * is a member class.
1319      *
1320      * @return {@code true} if and only if this class is a member class.
1321      * @since 1.5
1322      */
isMemberClass()1323     public boolean isMemberClass() {
1324         return getDeclaringClass() != null;
1325     }
1326 
1327     /**
1328      * Returns {@code true} if this is a local class or an anonymous
1329      * class.  Returns {@code false} otherwise.
1330      */
isLocalOrAnonymousClass()1331     private boolean isLocalOrAnonymousClass() {
1332         // JVM Spec 4.8.6: A class must have an EnclosingMethod
1333         // attribute if and only if it is a local class or an
1334         // anonymous class.
1335         return isLocalClass() || isAnonymousClass();
1336     }
1337 
1338     /**
1339      * Returns an array containing {@code Class} objects representing all
1340      * the public classes and interfaces that are members of the class
1341      * represented by this {@code Class} object.  This includes public
1342      * class and interface members inherited from superclasses and public class
1343      * and interface members declared by the class.  This method returns an
1344      * array of length 0 if this {@code Class} object has no public member
1345      * classes or interfaces.  This method also returns an array of length 0 if
1346      * this {@code Class} object represents a primitive type, an array
1347      * class, or void.
1348      *
1349      * @return the array of {@code Class} objects representing the public
1350      *         members of this class
1351      *
1352      * @since JDK1.1
1353      */
1354     @CallerSensitive
getClasses()1355     public Class<?>[] getClasses() {
1356         List<Class<?>> result = new ArrayList<Class<?>>();
1357         for (Class<?> c = this; c != null; c = c.superClass) {
1358             for (Class<?> member : c.getDeclaredClasses()) {
1359                 if (Modifier.isPublic(member.getModifiers())) {
1360                     result.add(member);
1361                 }
1362             }
1363         }
1364         return result.toArray(new Class[result.size()]);
1365     }
1366 
1367 
1368     /**
1369      * Returns an array containing {@code Field} objects reflecting all
1370      * the accessible public fields of the class or interface represented by
1371      * this {@code Class} object.
1372      *
1373      * <p> If this {@code Class} object represents a class or interface with no
1374      * no accessible public fields, then this method returns an array of length
1375      * 0.
1376      *
1377      * <p> If this {@code Class} object represents a class, then this method
1378      * returns the public fields of the class and of all its superclasses.
1379      *
1380      * <p> If this {@code Class} object represents an interface, then this
1381      * method returns the fields of the interface and of all its
1382      * superinterfaces.
1383      *
1384      * <p> If this {@code Class} object represents an array type, a primitive
1385      * type, or void, then this method returns an array of length 0.
1386      *
1387      * <p> The elements in the returned array are not sorted and are not in any
1388      * particular order.
1389      *
1390      * @return the array of {@code Field} objects representing the
1391      *         public fields
1392      * @throws SecurityException
1393      *         If a security manager, <i>s</i>, is present and
1394      *         the caller's class loader is not the same as or an
1395      *         ancestor of the class loader for the current class and
1396      *         invocation of {@link SecurityManager#checkPackageAccess
1397      *         s.checkPackageAccess()} denies access to the package
1398      *         of this class.
1399      *
1400      * @since JDK1.1
1401      * @jls 8.2 Class Members
1402      * @jls 8.3 Field Declarations
1403      */
1404     @CallerSensitive
getFields()1405     public Field[] getFields() throws SecurityException {
1406         List<Field> fields = new ArrayList<Field>();
1407         getPublicFieldsRecursive(fields);
1408         return fields.toArray(new Field[fields.size()]);
1409     }
1410 
1411     /**
1412      * Populates {@code result} with public fields defined by this class, its
1413      * superclasses, and all implemented interfaces.
1414      */
getPublicFieldsRecursive(List<Field> result)1415     private void getPublicFieldsRecursive(List<Field> result) {
1416         // search superclasses
1417         for (Class<?> c = this; c != null; c = c.superClass) {
1418             Collections.addAll(result, c.getPublicDeclaredFields());
1419         }
1420 
1421         // search iftable which has a flattened and uniqued list of interfaces
1422         Object[] iftable = ifTable;
1423         if (iftable != null) {
1424             for (int i = 0; i < iftable.length; i += 2) {
1425                 Collections.addAll(result, ((Class<?>) iftable[i]).getPublicDeclaredFields());
1426             }
1427         }
1428     }
1429 
1430     /**
1431      * Returns an array containing {@code Method} objects reflecting all the
1432      * public methods of the class or interface represented by this {@code
1433      * Class} object, including those declared by the class or interface and
1434      * those inherited from superclasses and superinterfaces.
1435      *
1436      * <p> If this {@code Class} object represents a type that has multiple
1437      * public methods with the same name and parameter types, but different
1438      * return types, then the returned array has a {@code Method} object for
1439      * each such method.
1440      *
1441      * <p> If this {@code Class} object represents a type with a class
1442      * initialization method {@code <clinit>}, then the returned array does
1443      * <em>not</em> have a corresponding {@code Method} object.
1444      *
1445      * <p> If this {@code Class} object represents an array type, then the
1446      * returned array has a {@code Method} object for each of the public
1447      * methods inherited by the array type from {@code Object}. It does not
1448      * contain a {@code Method} object for {@code clone()}.
1449      *
1450      * <p> If this {@code Class} object represents an interface then the
1451      * returned array does not contain any implicitly declared methods from
1452      * {@code Object}. Therefore, if no methods are explicitly declared in
1453      * this interface or any of its superinterfaces then the returned array
1454      * has length 0. (Note that a {@code Class} object which represents a class
1455      * always has public methods, inherited from {@code Object}.)
1456      *
1457      * <p> If this {@code Class} object represents a primitive type or void,
1458      * then the returned array has length 0.
1459      *
1460      * <p> Static methods declared in superinterfaces of the class or interface
1461      * represented by this {@code Class} object are not considered members of
1462      * the class or interface.
1463      *
1464      * <p> The elements in the returned array are not sorted and are not in any
1465      * particular order.
1466      *
1467      * @return the array of {@code Method} objects representing the
1468      *         public methods of this class
1469      * @throws SecurityException
1470      *         If a security manager, <i>s</i>, is present and
1471      *         the caller's class loader is not the same as or an
1472      *         ancestor of the class loader for the current class and
1473      *         invocation of {@link SecurityManager#checkPackageAccess
1474      *         s.checkPackageAccess()} denies access to the package
1475      *         of this class.
1476      *
1477      * @jls 8.2 Class Members
1478      * @jls 8.4 Method Declarations
1479      * @since JDK1.1
1480      */
1481     @CallerSensitive
getMethods()1482     public Method[] getMethods() throws SecurityException {
1483         List<Method> methods = new ArrayList<Method>();
1484         getPublicMethodsInternal(methods);
1485         /*
1486          * Remove duplicate methods defined by superclasses and
1487          * interfaces, preferring to keep methods declared by derived
1488          * types.
1489          */
1490         CollectionUtils.removeDuplicates(methods, Method.ORDER_BY_SIGNATURE);
1491         return methods.toArray(new Method[methods.size()]);
1492     }
1493 
1494     /**
1495      * Populates {@code result} with public methods defined by this class, its
1496      * superclasses, and all implemented interfaces, including overridden methods.
1497      */
getPublicMethodsInternal(List<Method> result)1498     private void getPublicMethodsInternal(List<Method> result) {
1499         Collections.addAll(result, getDeclaredMethodsUnchecked(true));
1500         if (!isInterface()) {
1501             // Search superclasses, for interfaces don't search java.lang.Object.
1502             for (Class<?> c = superClass; c != null; c = c.superClass) {
1503                 Collections.addAll(result, c.getDeclaredMethodsUnchecked(true));
1504             }
1505         }
1506         // Search iftable which has a flattened and uniqued list of interfaces.
1507         Object[] iftable = ifTable;
1508         if (iftable != null) {
1509             for (int i = 0; i < iftable.length; i += 2) {
1510                 Class<?> ifc = (Class<?>) iftable[i];
1511                 Collections.addAll(result, ifc.getDeclaredMethodsUnchecked(true));
1512             }
1513         }
1514     }
1515 
1516     /**
1517      * Returns an array containing {@code Constructor} objects reflecting
1518      * all the public constructors of the class represented by this
1519      * {@code Class} object.  An array of length 0 is returned if the
1520      * class has no public constructors, or if the class is an array class, or
1521      * if the class reflects a primitive type or void.
1522      *
1523      * Note that while this method returns an array of {@code
1524      * Constructor<T>} objects (that is an array of constructors from
1525      * this class), the return type of this method is {@code
1526      * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
1527      * might be expected.  This less informative return type is
1528      * necessary since after being returned from this method, the
1529      * array could be modified to hold {@code Constructor} objects for
1530      * different classes, which would violate the type guarantees of
1531      * {@code Constructor<T>[]}.
1532      *
1533      * @return the array of {@code Constructor} objects representing the
1534      *         public constructors of this class
1535      * @throws SecurityException
1536      *         If a security manager, <i>s</i>, is present and
1537      *         the caller's class loader is not the same as or an
1538      *         ancestor of the class loader for the current class and
1539      *         invocation of {@link SecurityManager#checkPackageAccess
1540      *         s.checkPackageAccess()} denies access to the package
1541      *         of this class.
1542      *
1543      * @since JDK1.1
1544      */
1545     @CallerSensitive
getConstructors()1546     public Constructor<?>[] getConstructors() throws SecurityException {
1547         return getDeclaredConstructorsInternal(true);
1548     }
1549 
1550 
1551     /**
1552      * Returns a {@code Field} object that reflects the specified public member
1553      * field of the class or interface represented by this {@code Class}
1554      * object. The {@code name} parameter is a {@code String} specifying the
1555      * simple name of the desired field.
1556      *
1557      * <p> The field to be reflected is determined by the algorithm that
1558      * follows.  Let C be the class or interface represented by this object:
1559      *
1560      * <OL>
1561      * <LI> If C declares a public field with the name specified, that is the
1562      *      field to be reflected.</LI>
1563      * <LI> If no field was found in step 1 above, this algorithm is applied
1564      *      recursively to each direct superinterface of C. The direct
1565      *      superinterfaces are searched in the order they were declared.</LI>
1566      * <LI> If no field was found in steps 1 and 2 above, and C has a
1567      *      superclass S, then this algorithm is invoked recursively upon S.
1568      *      If C has no superclass, then a {@code NoSuchFieldException}
1569      *      is thrown.</LI>
1570      * </OL>
1571      *
1572      * <p> If this {@code Class} object represents an array type, then this
1573      * method does not find the {@code length} field of the array type.
1574      *
1575      * @param name the field name
1576      * @return the {@code Field} object of this class specified by
1577      *         {@code name}
1578      * @throws NoSuchFieldException if a field with the specified name is
1579      *         not found.
1580      * @throws NullPointerException if {@code name} is {@code null}
1581      * @throws SecurityException
1582      *         If a security manager, <i>s</i>, is present and
1583      *         the caller's class loader is not the same as or an
1584      *         ancestor of the class loader for the current class and
1585      *         invocation of {@link SecurityManager#checkPackageAccess
1586      *         s.checkPackageAccess()} denies access to the package
1587      *         of this class.
1588      *
1589      * @since JDK1.1
1590      * @jls 8.2 Class Members
1591      * @jls 8.3 Field Declarations
1592      */
1593     // Android-changed: Removed SecurityException
getField(String name)1594     public Field getField(String name)
1595         throws NoSuchFieldException {
1596         if (name == null) {
1597             throw new NullPointerException("name == null");
1598         }
1599         Field result = getPublicFieldRecursive(name);
1600         if (result == null) {
1601             throw new NoSuchFieldException(name);
1602         }
1603         return result;
1604     }
1605 
1606     /**
1607      * The native implementation of the {@code getField} method.
1608      *
1609      * @throws NullPointerException
1610      *            if name is null.
1611      * @see #getField(String)
1612      */
1613     @FastNative
getPublicFieldRecursive(String name)1614     private native Field getPublicFieldRecursive(String name);
1615 
1616     /**
1617      * Returns a {@code Method} object that reflects the specified public
1618      * member method of the class or interface represented by this
1619      * {@code Class} object. The {@code name} parameter is a
1620      * {@code String} specifying the simple name of the desired method. The
1621      * {@code parameterTypes} parameter is an array of {@code Class}
1622      * objects that identify the method's formal parameter types, in declared
1623      * order. If {@code parameterTypes} is {@code null}, it is
1624      * treated as if it were an empty array.
1625      *
1626      * <p> If the {@code name} is "{@code <init>}" or "{@code <clinit>}" a
1627      * {@code NoSuchMethodException} is raised. Otherwise, the method to
1628      * be reflected is determined by the algorithm that follows.  Let C be the
1629      * class or interface represented by this object:
1630      * <OL>
1631      * <LI> C is searched for a <I>matching method</I>, as defined below. If a
1632      *      matching method is found, it is reflected.</LI>
1633      * <LI> If no matching method is found by step 1 then:
1634      *   <OL TYPE="a">
1635      *   <LI> If C is a class other than {@code Object}, then this algorithm is
1636      *        invoked recursively on the superclass of C.</LI>
1637      *   <LI> If C is the class {@code Object}, or if C is an interface, then
1638      *        the superinterfaces of C (if any) are searched for a matching
1639      *        method. If any such method is found, it is reflected.</LI>
1640      *   </OL></LI>
1641      * </OL>
1642      *
1643      * <p> To find a matching method in a class or interface C:&nbsp; If C
1644      * declares exactly one public method with the specified name and exactly
1645      * the same formal parameter types, that is the method reflected. If more
1646      * than one such method is found in C, and one of these methods has a
1647      * return type that is more specific than any of the others, that method is
1648      * reflected; otherwise one of the methods is chosen arbitrarily.
1649      *
1650      * <p>Note that there may be more than one matching method in a
1651      * class because while the Java language forbids a class to
1652      * declare multiple methods with the same signature but different
1653      * return types, the Java virtual machine does not.  This
1654      * increased flexibility in the virtual machine can be used to
1655      * implement various language features.  For example, covariant
1656      * returns can be implemented with {@linkplain
1657      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
1658      * method and the method being overridden would have the same
1659      * signature but different return types.
1660      *
1661      * <p> If this {@code Class} object represents an array type, then this
1662      * method does not find the {@code clone()} method.
1663      *
1664      * <p> Static methods declared in superinterfaces of the class or interface
1665      * represented by this {@code Class} object are not considered members of
1666      * the class or interface.
1667      *
1668      * @param name the name of the method
1669      * @param parameterTypes the list of parameters
1670      * @return the {@code Method} object that matches the specified
1671      *         {@code name} and {@code parameterTypes}
1672      * @throws NoSuchMethodException if a matching method is not found
1673      *         or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
1674      * @throws NullPointerException if {@code name} is {@code null}
1675      * @throws SecurityException
1676      *         If a security manager, <i>s</i>, is present and
1677      *         the caller's class loader is not the same as or an
1678      *         ancestor of the class loader for the current class and
1679      *         invocation of {@link SecurityManager#checkPackageAccess
1680      *         s.checkPackageAccess()} denies access to the package
1681      *         of this class.
1682      *
1683      * @jls 8.2 Class Members
1684      * @jls 8.4 Method Declarations
1685      * @since JDK1.1
1686      */
1687     @CallerSensitive
getMethod(String name, Class<?>... parameterTypes)1688     public Method getMethod(String name, Class<?>... parameterTypes)
1689         throws NoSuchMethodException, SecurityException {
1690         return getMethod(name, parameterTypes, true);
1691     }
1692 
1693 
1694     /**
1695      * Returns a {@code Constructor} object that reflects the specified
1696      * public constructor of the class represented by this {@code Class}
1697      * object. The {@code parameterTypes} parameter is an array of
1698      * {@code Class} objects that identify the constructor's formal
1699      * parameter types, in declared order.
1700      *
1701      * If this {@code Class} object represents an inner class
1702      * declared in a non-static context, the formal parameter types
1703      * include the explicit enclosing instance as the first parameter.
1704      *
1705      * <p> The constructor to reflect is the public constructor of the class
1706      * represented by this {@code Class} object whose formal parameter
1707      * types match those specified by {@code parameterTypes}.
1708      *
1709      * @param parameterTypes the parameter array
1710      * @return the {@code Constructor} object of the public constructor that
1711      *         matches the specified {@code parameterTypes}
1712      * @throws NoSuchMethodException if a matching method is not found.
1713      * @throws SecurityException
1714      *         If a security manager, <i>s</i>, is present and
1715      *         the caller's class loader is not the same as or an
1716      *         ancestor of the class loader for the current class and
1717      *         invocation of {@link SecurityManager#checkPackageAccess
1718      *         s.checkPackageAccess()} denies access to the package
1719      *         of this class.
1720      *
1721      * @since JDK1.1
1722      */
getConstructor(Class<?>.... parameterTypes)1723     public Constructor<T> getConstructor(Class<?>... parameterTypes)
1724         throws NoSuchMethodException, SecurityException {
1725         return getConstructor0(parameterTypes, Member.PUBLIC);
1726     }
1727 
1728 
1729     /**
1730      * Returns an array of {@code Class} objects reflecting all the
1731      * classes and interfaces declared as members of the class represented by
1732      * this {@code Class} object. This includes public, protected, default
1733      * (package) access, and private classes and interfaces declared by the
1734      * class, but excludes inherited classes and interfaces.  This method
1735      * returns an array of length 0 if the class declares no classes or
1736      * interfaces as members, or if this {@code Class} object represents a
1737      * primitive type, an array class, or void.
1738      *
1739      * @return the array of {@code Class} objects representing all the
1740      *         declared members of this class
1741      * @throws SecurityException
1742      *         If a security manager, <i>s</i>, is present and any of the
1743      *         following conditions is met:
1744      *
1745      *         <ul>
1746      *
1747      *         <li> the caller's class loader is not the same as the
1748      *         class loader of this class and invocation of
1749      *         {@link SecurityManager#checkPermission
1750      *         s.checkPermission} method with
1751      *         {@code RuntimePermission("accessDeclaredMembers")}
1752      *         denies access to the declared classes within this class
1753      *
1754      *         <li> the caller's class loader is not the same as or an
1755      *         ancestor of the class loader for the current class and
1756      *         invocation of {@link SecurityManager#checkPackageAccess
1757      *         s.checkPackageAccess()} denies access to the package
1758      *         of this class
1759      *
1760      *         </ul>
1761      *
1762      * @since JDK1.1
1763      */
1764     // Android-changed: Removed SecurityException
1765     @FastNative
getDeclaredClasses()1766     public native Class<?>[] getDeclaredClasses();
1767 
1768     /**
1769      * Returns an array of {@code Field} objects reflecting all the fields
1770      * declared by the class or interface represented by this
1771      * {@code Class} object. This includes public, protected, default
1772      * (package) access, and private fields, but excludes inherited fields.
1773      *
1774      * <p> If this {@code Class} object represents a class or interface with no
1775      * declared fields, then this method returns an array of length 0.
1776      *
1777      * <p> If this {@code Class} object represents an array type, a primitive
1778      * type, or void, then this method returns an array of length 0.
1779      *
1780      * <p> The elements in the returned array are not sorted and are not in any
1781      * particular order.
1782      *
1783      * @return  the array of {@code Field} objects representing all the
1784      *          declared fields of this class
1785      * @throws  SecurityException
1786      *          If a security manager, <i>s</i>, is present and any of the
1787      *          following conditions is met:
1788      *
1789      *          <ul>
1790      *
1791      *          <li> the caller's class loader is not the same as the
1792      *          class loader of this class and invocation of
1793      *          {@link SecurityManager#checkPermission
1794      *          s.checkPermission} method with
1795      *          {@code RuntimePermission("accessDeclaredMembers")}
1796      *          denies access to the declared fields within this class
1797      *
1798      *          <li> the caller's class loader is not the same as or an
1799      *          ancestor of the class loader for the current class and
1800      *          invocation of {@link SecurityManager#checkPackageAccess
1801      *          s.checkPackageAccess()} denies access to the package
1802      *          of this class
1803      *
1804      *          </ul>
1805      *
1806      * @since JDK1.1
1807      * @jls 8.2 Class Members
1808      * @jls 8.3 Field Declarations
1809      */
1810     // Android-changed: Removed SecurityException
1811     @FastNative
getDeclaredFields()1812     public native Field[] getDeclaredFields();
1813 
1814     /**
1815      * Populates a list of fields without performing any security or type
1816      * resolution checks first. If no fields exist, the list is not modified.
1817      *
1818      * @param publicOnly Whether to return only public fields.
1819      * @hide
1820      */
1821     @FastNative
getDeclaredFieldsUnchecked(boolean publicOnly)1822     public native Field[] getDeclaredFieldsUnchecked(boolean publicOnly);
1823 
1824     /**
1825      *
1826      * Returns an array containing {@code Method} objects reflecting all the
1827      * declared methods of the class or interface represented by this {@code
1828      * Class} object, including public, protected, default (package)
1829      * access, and private methods, but excluding inherited methods.
1830      *
1831      * <p> If this {@code Class} object represents a type that has multiple
1832      * declared methods with the same name and parameter types, but different
1833      * return types, then the returned array has a {@code Method} object for
1834      * each such method.
1835      *
1836      * <p> If this {@code Class} object represents a type that has a class
1837      * initialization method {@code <clinit>}, then the returned array does
1838      * <em>not</em> have a corresponding {@code Method} object.
1839      *
1840      * <p> If this {@code Class} object represents a class or interface with no
1841      * declared methods, then the returned array has length 0.
1842      *
1843      * <p> If this {@code Class} object represents an array type, a primitive
1844      * type, or void, then the returned array has length 0.
1845      *
1846      * <p> The elements in the returned array are not sorted and are not in any
1847      * particular order.
1848      *
1849      * @return  the array of {@code Method} objects representing all the
1850      *          declared methods of this class
1851      * @throws  SecurityException
1852      *          If a security manager, <i>s</i>, is present and any of the
1853      *          following conditions is met:
1854      *
1855      *          <ul>
1856      *
1857      *          <li> the caller's class loader is not the same as the
1858      *          class loader of this class and invocation of
1859      *          {@link SecurityManager#checkPermission
1860      *          s.checkPermission} method with
1861      *          {@code RuntimePermission("accessDeclaredMembers")}
1862      *          denies access to the declared methods within this class
1863      *
1864      *          <li> the caller's class loader is not the same as or an
1865      *          ancestor of the class loader for the current class and
1866      *          invocation of {@link SecurityManager#checkPackageAccess
1867      *          s.checkPackageAccess()} denies access to the package
1868      *          of this class
1869      *
1870      *          </ul>
1871      *
1872      * @jls 8.2 Class Members
1873      * @jls 8.4 Method Declarations
1874      * @since JDK1.1
1875      */
getDeclaredMethods()1876     public Method[] getDeclaredMethods() throws SecurityException {
1877         Method[] result = getDeclaredMethodsUnchecked(false);
1878         for (Method m : result) {
1879             // Throw NoClassDefFoundError if types cannot be resolved.
1880             m.getReturnType();
1881             m.getParameterTypes();
1882         }
1883         return result;
1884     }
1885 
1886     /**
1887      * Populates a list of methods without performing any security or type
1888      * resolution checks first. If no methods exist, the list is not modified.
1889      *
1890      * @param publicOnly Whether to return only public methods.
1891      * @hide
1892      */
1893     @FastNative
getDeclaredMethodsUnchecked(boolean publicOnly)1894     public native Method[] getDeclaredMethodsUnchecked(boolean publicOnly);
1895 
1896     /**
1897      * Returns an array of {@code Constructor} objects reflecting all the
1898      * constructors declared by the class represented by this
1899      * {@code Class} object. These are public, protected, default
1900      * (package) access, and private constructors.  The elements in the array
1901      * returned are not sorted and are not in any particular order.  If the
1902      * class has a default constructor, it is included in the returned array.
1903      * This method returns an array of length 0 if this {@code Class}
1904      * object represents an interface, a primitive type, an array class, or
1905      * void.
1906      *
1907      * <p> See <em>The Java Language Specification</em>, section 8.2.
1908      *
1909      * @return  the array of {@code Constructor} objects representing all the
1910      *          declared constructors of this class
1911      * @throws  SecurityException
1912      *          If a security manager, <i>s</i>, is present and any of the
1913      *          following conditions is met:
1914      *
1915      *          <ul>
1916      *
1917      *          <li> the caller's class loader is not the same as the
1918      *          class loader of this class and invocation of
1919      *          {@link SecurityManager#checkPermission
1920      *          s.checkPermission} method with
1921      *          {@code RuntimePermission("accessDeclaredMembers")}
1922      *          denies access to the declared constructors within this class
1923      *
1924      *          <li> the caller's class loader is not the same as or an
1925      *          ancestor of the class loader for the current class and
1926      *          invocation of {@link SecurityManager#checkPackageAccess
1927      *          s.checkPackageAccess()} denies access to the package
1928      *          of this class
1929      *
1930      *          </ul>
1931      *
1932      * @since JDK1.1
1933      */
getDeclaredConstructors()1934     public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
1935         return getDeclaredConstructorsInternal(false);
1936     }
1937 
1938 
1939     /**
1940      * Returns the constructor with the given parameters if it is defined by this class;
1941      * {@code null} otherwise. This may return a non-public member.
1942      */
1943     @FastNative
getDeclaredConstructorsInternal(boolean publicOnly)1944     private native Constructor<?>[] getDeclaredConstructorsInternal(boolean publicOnly);
1945 
1946     /**
1947      * Returns a {@code Field} object that reflects the specified declared
1948      * field of the class or interface represented by this {@code Class}
1949      * object. The {@code name} parameter is a {@code String} that specifies
1950      * the simple name of the desired field.
1951      *
1952      * <p> If this {@code Class} object represents an array type, then this
1953      * method does not find the {@code length} field of the array type.
1954      *
1955      * @param name the name of the field
1956      * @return  the {@code Field} object for the specified field in this
1957      *          class
1958      * @throws  NoSuchFieldException if a field with the specified name is
1959      *          not found.
1960      * @throws  NullPointerException if {@code name} is {@code null}
1961      * @throws  SecurityException
1962      *          If a security manager, <i>s</i>, is present and any of the
1963      *          following conditions is met:
1964      *
1965      *          <ul>
1966      *
1967      *          <li> the caller's class loader is not the same as the
1968      *          class loader of this class and invocation of
1969      *          {@link SecurityManager#checkPermission
1970      *          s.checkPermission} method with
1971      *          {@code RuntimePermission("accessDeclaredMembers")}
1972      *          denies access to the declared field
1973      *
1974      *          <li> the caller's class loader is not the same as or an
1975      *          ancestor of the class loader for the current class and
1976      *          invocation of {@link SecurityManager#checkPackageAccess
1977      *          s.checkPackageAccess()} denies access to the package
1978      *          of this class
1979      *
1980      *          </ul>
1981      *
1982      * @since JDK1.1
1983      * @jls 8.2 Class Members
1984      * @jls 8.3 Field Declarations
1985      */
1986     // Android-changed: Removed SecurityException
1987     @FastNative
getDeclaredField(String name)1988     public native Field getDeclaredField(String name) throws NoSuchFieldException;
1989 
1990     /**
1991      * Returns the subset of getDeclaredFields which are public.
1992      */
1993     @FastNative
getPublicDeclaredFields()1994     private native Field[] getPublicDeclaredFields();
1995 
1996     /**
1997      * Returns a {@code Method} object that reflects the specified
1998      * declared method of the class or interface represented by this
1999      * {@code Class} object. The {@code name} parameter is a
2000      * {@code String} that specifies the simple name of the desired
2001      * method, and the {@code parameterTypes} parameter is an array of
2002      * {@code Class} objects that identify the method's formal parameter
2003      * types, in declared order.  If more than one method with the same
2004      * parameter types is declared in a class, and one of these methods has a
2005      * return type that is more specific than any of the others, that method is
2006      * returned; otherwise one of the methods is chosen arbitrarily.  If the
2007      * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
2008      * is raised.
2009      *
2010      * <p> If this {@code Class} object represents an array type, then this
2011      * method does not find the {@code clone()} method.
2012      *
2013      * @param name the name of the method
2014      * @param parameterTypes the parameter array
2015      * @return  the {@code Method} object for the method of this class
2016      *          matching the specified name and parameters
2017      * @throws  NoSuchMethodException if a matching method is not found.
2018      * @throws  NullPointerException if {@code name} is {@code null}
2019      * @throws  SecurityException
2020      *          If a security manager, <i>s</i>, is present and any of the
2021      *          following conditions is met:
2022      *
2023      *          <ul>
2024      *
2025      *          <li> the caller's class loader is not the same as the
2026      *          class loader of this class and invocation of
2027      *          {@link SecurityManager#checkPermission
2028      *          s.checkPermission} method with
2029      *          {@code RuntimePermission("accessDeclaredMembers")}
2030      *          denies access to the declared method
2031      *
2032      *          <li> the caller's class loader is not the same as or an
2033      *          ancestor of the class loader for the current class and
2034      *          invocation of {@link SecurityManager#checkPackageAccess
2035      *          s.checkPackageAccess()} denies access to the package
2036      *          of this class
2037      *
2038      *          </ul>
2039      *
2040      * @jls 8.2 Class Members
2041      * @jls 8.4 Method Declarations
2042      * @since JDK1.1
2043      */
2044     @CallerSensitive
getDeclaredMethod(String name, Class<?>... parameterTypes)2045     public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2046         throws NoSuchMethodException, SecurityException {
2047         return getMethod(name, parameterTypes, false);
2048     }
2049 
getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods)2050     private Method getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods)
2051             throws NoSuchMethodException {
2052         if (name == null) {
2053             throw new NullPointerException("name == null");
2054         }
2055         if (parameterTypes == null) {
2056             parameterTypes = EmptyArray.CLASS;
2057         }
2058         for (Class<?> c : parameterTypes) {
2059             if (c == null) {
2060                 throw new NoSuchMethodException("parameter type is null");
2061             }
2062         }
2063         Method result = recursivePublicMethods ? getPublicMethodRecursive(name, parameterTypes)
2064                                                : getDeclaredMethodInternal(name, parameterTypes);
2065         // Fail if we didn't find the method or it was expected to be public.
2066         if (result == null ||
2067             (recursivePublicMethods && !Modifier.isPublic(result.getAccessFlags()))) {
2068             throw new NoSuchMethodException(name + " " + Arrays.toString(parameterTypes));
2069         }
2070         return result;
2071     }
getPublicMethodRecursive(String name, Class<?>[] parameterTypes)2072     private Method getPublicMethodRecursive(String name, Class<?>[] parameterTypes) {
2073         // search superclasses
2074         for (Class<?> c = this; c != null; c = c.getSuperclass()) {
2075             Method result = c.getDeclaredMethodInternal(name, parameterTypes);
2076             if (result != null && Modifier.isPublic(result.getAccessFlags())) {
2077                 return result;
2078             }
2079         }
2080 
2081         return findInterfaceMethod(name, parameterTypes);
2082     }
2083 
2084     /**
2085      * Returns an instance method that's defined on this class or any super classes, regardless
2086      * of its access flags. Constructors are excluded.
2087      *
2088      * This function does not perform access checks and its semantics don't match any dex byte code
2089      * instruction or public reflection API. This is used by {@code MethodHandles.findVirtual}
2090      * which will perform access checks on the returned method.
2091      *
2092      * @hide
2093      */
getInstanceMethod(String name, Class<?>[] parameterTypes)2094     public Method getInstanceMethod(String name, Class<?>[] parameterTypes)
2095             throws NoSuchMethodException, IllegalAccessException {
2096         for (Class<?> c = this; c != null; c = c.getSuperclass()) {
2097             Method result = c.getDeclaredMethodInternal(name, parameterTypes);
2098             if (result != null && !Modifier.isStatic(result.getModifiers())) {
2099                 return result;
2100             }
2101         }
2102 
2103         return findInterfaceMethod(name, parameterTypes);
2104     }
2105 
findInterfaceMethod(String name, Class<?>[] parameterTypes)2106     private Method findInterfaceMethod(String name, Class<?>[] parameterTypes) {
2107         Object[] iftable = ifTable;
2108         if (iftable != null) {
2109             // Search backwards so more specific interfaces are searched first. This ensures that
2110             // the method we return is not overridden by one of it's subtypes that this class also
2111             // implements.
2112             for (int i = iftable.length - 2; i >= 0; i -= 2) {
2113                 Class<?> ifc = (Class<?>) iftable[i];
2114                 Method result = ifc.getPublicMethodRecursive(name, parameterTypes);
2115                 if (result != null && Modifier.isPublic(result.getAccessFlags())) {
2116                     return result;
2117                 }
2118             }
2119         }
2120 
2121         return null;
2122     }
2123 
2124 
2125     /**
2126      * Returns a {@code Constructor} object that reflects the specified
2127      * constructor of the class or interface represented by this
2128      * {@code Class} object.  The {@code parameterTypes} parameter is
2129      * an array of {@code Class} objects that identify the constructor's
2130      * formal parameter types, in declared order.
2131      *
2132      * If this {@code Class} object represents an inner class
2133      * declared in a non-static context, the formal parameter types
2134      * include the explicit enclosing instance as the first parameter.
2135      *
2136      * @param parameterTypes the parameter array
2137      * @return  The {@code Constructor} object for the constructor with the
2138      *          specified parameter list
2139      * @throws  NoSuchMethodException if a matching method is not found.
2140      * @throws  SecurityException
2141      *          If a security manager, <i>s</i>, is present and any of the
2142      *          following conditions is met:
2143      *
2144      *          <ul>
2145      *
2146      *          <li> the caller's class loader is not the same as the
2147      *          class loader of this class and invocation of
2148      *          {@link SecurityManager#checkPermission
2149      *          s.checkPermission} method with
2150      *          {@code RuntimePermission("accessDeclaredMembers")}
2151      *          denies access to the declared constructor
2152      *
2153      *          <li> the caller's class loader is not the same as or an
2154      *          ancestor of the class loader for the current class and
2155      *          invocation of {@link SecurityManager#checkPackageAccess
2156      *          s.checkPackageAccess()} denies access to the package
2157      *          of this class
2158      *
2159      *          </ul>
2160      *
2161      * @since JDK1.1
2162      */
2163     @CallerSensitive
getDeclaredConstructor(Class<?>.... parameterTypes)2164     public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
2165         throws NoSuchMethodException, SecurityException {
2166         return getConstructor0(parameterTypes, Member.DECLARED);
2167     }
2168 
2169     /**
2170      * Finds a resource with a given name.  The rules for searching resources
2171      * associated with a given class are implemented by the defining
2172      * {@linkplain ClassLoader class loader} of the class.  This method
2173      * delegates to this object's class loader.  If this object was loaded by
2174      * the bootstrap class loader, the method delegates to {@link
2175      * ClassLoader#getSystemResourceAsStream}.
2176      *
2177      * <p> Before delegation, an absolute resource name is constructed from the
2178      * given resource name using this algorithm:
2179      *
2180      * <ul>
2181      *
2182      * <li> If the {@code name} begins with a {@code '/'}
2183      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
2184      * portion of the {@code name} following the {@code '/'}.
2185      *
2186      * <li> Otherwise, the absolute name is of the following form:
2187      *
2188      * <blockquote>
2189      *   {@code modified_package_name/name}
2190      * </blockquote>
2191      *
2192      * <p> Where the {@code modified_package_name} is the package name of this
2193      * object with {@code '/'} substituted for {@code '.'}
2194      * (<tt>'&#92;u002e'</tt>).
2195      *
2196      * </ul>
2197      *
2198      * @param  name name of the desired resource
2199      * @return      A {@link java.io.InputStream} object or {@code null} if
2200      *              no resource with this name is found
2201      * @throws  NullPointerException If {@code name} is {@code null}
2202      * @since  JDK1.1
2203      */
getResourceAsStream(String name)2204      public InputStream getResourceAsStream(String name) {
2205         name = resolveName(name);
2206         ClassLoader cl = getClassLoader();
2207         if (cl==null) {
2208             // A system class.
2209             return ClassLoader.getSystemResourceAsStream(name);
2210         }
2211         return cl.getResourceAsStream(name);
2212     }
2213 
2214     /**
2215      * Finds a resource with a given name.  The rules for searching resources
2216      * associated with a given class are implemented by the defining
2217      * {@linkplain ClassLoader class loader} of the class.  This method
2218      * delegates to this object's class loader.  If this object was loaded by
2219      * the bootstrap class loader, the method delegates to {@link
2220      * ClassLoader#getSystemResource}.
2221      *
2222      * <p> Before delegation, an absolute resource name is constructed from the
2223      * given resource name using this algorithm:
2224      *
2225      * <ul>
2226      *
2227      * <li> If the {@code name} begins with a {@code '/'}
2228      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
2229      * portion of the {@code name} following the {@code '/'}.
2230      *
2231      * <li> Otherwise, the absolute name is of the following form:
2232      *
2233      * <blockquote>
2234      *   {@code modified_package_name/name}
2235      * </blockquote>
2236      *
2237      * <p> Where the {@code modified_package_name} is the package name of this
2238      * object with {@code '/'} substituted for {@code '.'}
2239      * (<tt>'&#92;u002e'</tt>).
2240      *
2241      * </ul>
2242      *
2243      * @param  name name of the desired resource
2244      * @return      A  {@link java.net.URL} object or {@code null} if no
2245      *              resource with this name is found
2246      * @since  JDK1.1
2247      */
getResource(String name)2248     public java.net.URL getResource(String name) {
2249         name = resolveName(name);
2250         ClassLoader cl = getClassLoader();
2251         if (cl==null) {
2252             // A system class.
2253             return ClassLoader.getSystemResource(name);
2254         }
2255         return cl.getResource(name);
2256     }
2257 
2258     /**
2259      * Returns the {@code ProtectionDomain} of this class.  If there is a
2260      * security manager installed, this method first calls the security
2261      * manager's {@code checkPermission} method with a
2262      * {@code RuntimePermission("getProtectionDomain")} permission to
2263      * ensure it's ok to get the
2264      * {@code ProtectionDomain}.
2265      *
2266      * @return the ProtectionDomain of this class
2267      *
2268      * @throws SecurityException
2269      *        if a security manager exists and its
2270      *        {@code checkPermission} method doesn't allow
2271      *        getting the ProtectionDomain.
2272      *
2273      * @see java.security.ProtectionDomain
2274      * @see SecurityManager#checkPermission
2275      * @see java.lang.RuntimePermission
2276      * @since 1.2
2277      */
getProtectionDomain()2278     public java.security.ProtectionDomain getProtectionDomain() {
2279         return null;
2280     }
2281 
2282     /**
2283      * Add a package name prefix if the name is not absolute Remove leading "/"
2284      * if name is absolute
2285      */
resolveName(String name)2286     private String resolveName(String name) {
2287         if (name == null) {
2288             return name;
2289         }
2290         if (!name.startsWith("/")) {
2291             Class<?> c = this;
2292             while (c.isArray()) {
2293                 c = c.getComponentType();
2294             }
2295             String baseName = c.getName();
2296             int index = baseName.lastIndexOf('.');
2297             if (index != -1) {
2298                 name = baseName.substring(0, index).replace('.', '/')
2299                     +"/"+name;
2300             }
2301         } else {
2302             name = name.substring(1);
2303         }
2304         return name;
2305     }
2306 
getConstructor0(Class<?>[] parameterTypes, int which)2307     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
2308                                         int which) throws NoSuchMethodException
2309     {
2310         if (parameterTypes == null) {
2311             parameterTypes = EmptyArray.CLASS;
2312         }
2313         for (Class<?> c : parameterTypes) {
2314             if (c == null) {
2315                 throw new NoSuchMethodException("parameter type is null");
2316             }
2317         }
2318         Constructor<T> result = getDeclaredConstructorInternal(parameterTypes);
2319         if (result == null || which == Member.PUBLIC && !Modifier.isPublic(result.getAccessFlags())) {
2320             throw new NoSuchMethodException("<init> " + Arrays.toString(parameterTypes));
2321         }
2322         return result;
2323     }
2324 
2325     /** use serialVersionUID from JDK 1.1 for interoperability */
2326     private static final long serialVersionUID = 3206093459760846163L;
2327 
2328 
2329     /**
2330      * Returns the constructor with the given parameters if it is defined by this class;
2331      * {@code null} otherwise. This may return a non-public member.
2332      *
2333      * @param args the types of the parameters to the constructor.
2334      */
2335     @FastNative
getDeclaredConstructorInternal(Class<?>[] args)2336     private native Constructor<T> getDeclaredConstructorInternal(Class<?>[] args);
2337 
2338     /**
2339      * Returns the assertion status that would be assigned to this
2340      * class if it were to be initialized at the time this method is invoked.
2341      * If this class has had its assertion status set, the most recent
2342      * setting will be returned; otherwise, if any package default assertion
2343      * status pertains to this class, the most recent setting for the most
2344      * specific pertinent package default assertion status is returned;
2345      * otherwise, if this class is not a system class (i.e., it has a
2346      * class loader) its class loader's default assertion status is returned;
2347      * otherwise, the system class default assertion status is returned.
2348      * <p>
2349      * Few programmers will have any need for this method; it is provided
2350      * for the benefit of the JRE itself.  (It allows a class to determine at
2351      * the time that it is initialized whether assertions should be enabled.)
2352      * Note that this method is not guaranteed to return the actual
2353      * assertion status that was (or will be) associated with the specified
2354      * class when it was (or will be) initialized.
2355      *
2356      * @return the desired assertion status of the specified class.
2357      * @see    java.lang.ClassLoader#setClassAssertionStatus
2358      * @see    java.lang.ClassLoader#setPackageAssertionStatus
2359      * @see    java.lang.ClassLoader#setDefaultAssertionStatus
2360      * @since  1.4
2361      */
desiredAssertionStatus()2362     public boolean desiredAssertionStatus() {
2363         return false;
2364     }
2365 
2366     /**
2367      * Returns the simple name of a member or local class, or {@code null} otherwise.
2368      */
2369     @FastNative
getInnerClassName()2370     private native String getInnerClassName();
2371 
2372     @FastNative
getInnerClassFlags(int defaultValue)2373     private native int getInnerClassFlags(int defaultValue);
2374 
2375     /**
2376      * Returns true if and only if this class was declared as an enum in the
2377      * source code.
2378      *
2379      * @return true if and only if this class was declared as an enum in the
2380      *     source code
2381      * @since 1.5
2382      */
isEnum()2383     public boolean isEnum() {
2384         // An enum must both directly extend java.lang.Enum and have
2385         // the ENUM bit set; classes for specialized enum constants
2386         // don't do the former.
2387         return (this.getModifiers() & ENUM) != 0 &&
2388         this.getSuperclass() == java.lang.Enum.class;
2389     }
2390 
2391     /**
2392      * Returns the elements of this enum class or null if this
2393      * Class object does not represent an enum type.
2394      *
2395      * @return an array containing the values comprising the enum class
2396      *     represented by this Class object in the order they're
2397      *     declared, or null if this Class object does not
2398      *     represent an enum type
2399      * @since 1.5
2400      */
getEnumConstants()2401     public T[] getEnumConstants() {
2402         T[] values = getEnumConstantsShared();
2403         return (values != null) ? values.clone() : null;
2404     }
2405 
2406     /**
2407      * Returns the elements of this enum class or null if this
2408      * Class object does not represent an enum type;
2409      * identical to getEnumConstants except that the result is
2410      * uncloned, cached, and shared by all callers.
2411      */
getEnumConstantsShared()2412     T[] getEnumConstantsShared() {
2413         if (!isEnum()) return null;
2414         return (T[]) Enum.getSharedConstants((Class) this);
2415     }
2416 
2417     /**
2418      * Casts an object to the class or interface represented
2419      * by this {@code Class} object.
2420      *
2421      * @param obj the object to be cast
2422      * @return the object after casting, or null if obj is null
2423      *
2424      * @throws ClassCastException if the object is not
2425      * null and is not assignable to the type T.
2426      *
2427      * @since 1.5
2428      */
2429     @SuppressWarnings("unchecked")
cast(Object obj)2430     public T cast(Object obj) {
2431         if (obj != null && !isInstance(obj))
2432             throw new ClassCastException(cannotCastMsg(obj));
2433         return (T) obj;
2434     }
2435 
cannotCastMsg(Object obj)2436     private String cannotCastMsg(Object obj) {
2437         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
2438     }
2439 
2440     /**
2441      * Casts this {@code Class} object to represent a subclass of the class
2442      * represented by the specified class object.  Checks that the cast
2443      * is valid, and throws a {@code ClassCastException} if it is not.  If
2444      * this method succeeds, it always returns a reference to this class object.
2445      *
2446      * <p>This method is useful when a client needs to "narrow" the type of
2447      * a {@code Class} object to pass it to an API that restricts the
2448      * {@code Class} objects that it is willing to accept.  A cast would
2449      * generate a compile-time warning, as the correctness of the cast
2450      * could not be checked at runtime (because generic types are implemented
2451      * by erasure).
2452      *
2453      * @param <U> the type to cast this class object to
2454      * @param clazz the class of the type to cast this class object to
2455      * @return this {@code Class} object, cast to represent a subclass of
2456      *    the specified class object.
2457      * @throws ClassCastException if this {@code Class} object does not
2458      *    represent a subclass of the specified class (here "subclass" includes
2459      *    the class itself).
2460      * @since 1.5
2461      */
2462     @SuppressWarnings("unchecked")
asSubclass(Class<U> clazz)2463     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
2464         if (clazz.isAssignableFrom(this))
2465             return (Class<? extends U>) this;
2466         else
2467             throw new ClassCastException(this.toString() +
2468                 " cannot be cast to " + clazz.getName());
2469     }
2470 
2471     /**
2472      * @throws NullPointerException {@inheritDoc}
2473      * @since 1.5
2474      */
2475     @SuppressWarnings("unchecked")
getAnnotation(Class<A> annotationClass)2476     public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
2477         Objects.requireNonNull(annotationClass);
2478 
2479         A annotation = getDeclaredAnnotation(annotationClass);
2480         if (annotation != null) {
2481             return annotation;
2482         }
2483 
2484         if (annotationClass.isDeclaredAnnotationPresent(Inherited.class)) {
2485             for (Class<?> sup = getSuperclass(); sup != null; sup = sup.getSuperclass()) {
2486                 annotation = sup.getDeclaredAnnotation(annotationClass);
2487                 if (annotation != null) {
2488                     return annotation;
2489                 }
2490             }
2491         }
2492 
2493         return null;
2494     }
2495 
2496     /**
2497      * {@inheritDoc}
2498      * @throws NullPointerException {@inheritDoc}
2499      * @since 1.5
2500      */
2501     @Override
isAnnotationPresent(Class<? extends Annotation> annotationClass)2502     public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
2503         if (annotationClass == null) {
2504             throw new NullPointerException("annotationClass == null");
2505         }
2506 
2507         if (isDeclaredAnnotationPresent(annotationClass)) {
2508             return true;
2509         }
2510 
2511         if (annotationClass.isDeclaredAnnotationPresent(Inherited.class)) {
2512             for (Class<?> sup = getSuperclass(); sup != null; sup = sup.getSuperclass()) {
2513                 if (sup.isDeclaredAnnotationPresent(annotationClass)) {
2514                     return true;
2515                 }
2516             }
2517         }
2518 
2519         return false;
2520     }
2521 
2522     /**
2523      * @throws NullPointerException {@inheritDoc}
2524      * @since 1.8
2525      */
2526     @Override
getAnnotationsByType(Class<A> annotationClass)2527     public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {
2528       // Find any associated annotations [directly or repeatably (indirectly) present on this].
2529       A[] annotations = GenericDeclaration.super.getAnnotationsByType(annotationClass);
2530 
2531       if (annotations.length != 0) {
2532         return annotations;
2533       }
2534 
2535       // Nothing was found, attempt looking for associated annotations recursively up to the root
2536       // class if and only if:
2537       // * The annotation class was marked with @Inherited.
2538       //
2539       // Inherited annotations are not coalesced into a single set: the first declaration found is
2540       // returned.
2541 
2542       if (annotationClass.isDeclaredAnnotationPresent(Inherited.class)) {
2543         Class<?> superClass = getSuperclass();  // Returns null if klass's base is Object.
2544 
2545         if (superClass != null) {
2546           return superClass.getAnnotationsByType(annotationClass);
2547         }
2548       }
2549 
2550       // Annotated was not marked with @Inherited, or no superclass.
2551       return (A[]) Array.newInstance(annotationClass, 0);  // Safe by construction.
2552     }
2553 
2554     /**
2555      * @since 1.5
2556      */
2557     @Override
getAnnotations()2558     public Annotation[] getAnnotations() {
2559         /*
2560          * We need to get the annotations declared on this class, plus the
2561          * annotations from superclasses that have the "@Inherited" annotation
2562          * set.  We create a temporary map to use while we accumulate the
2563          * annotations and convert it to an array at the end.
2564          *
2565          * It's possible to have duplicates when annotations are inherited.
2566          * We use a Map to filter those out.
2567          *
2568          * HashMap might be overkill here.
2569          */
2570         HashMap<Class<?>, Annotation> map = new HashMap<Class<?>, Annotation>();
2571         for (Annotation declaredAnnotation : getDeclaredAnnotations()) {
2572             map.put(declaredAnnotation.annotationType(), declaredAnnotation);
2573         }
2574         for (Class<?> sup = getSuperclass(); sup != null; sup = sup.getSuperclass()) {
2575             for (Annotation declaredAnnotation : sup.getDeclaredAnnotations()) {
2576                 Class<? extends Annotation> clazz = declaredAnnotation.annotationType();
2577                 if (!map.containsKey(clazz) && clazz.isDeclaredAnnotationPresent(Inherited.class)) {
2578                     map.put(clazz, declaredAnnotation);
2579                 }
2580             }
2581         }
2582 
2583         /* Convert annotation values from HashMap to array. */
2584         Collection<Annotation> coll = map.values();
2585         return coll.toArray(new Annotation[coll.size()]);
2586     }
2587 
2588     /**
2589      * @throws NullPointerException {@inheritDoc}
2590      * @since 1.8
2591      */
2592     @Override
2593     @FastNative
getDeclaredAnnotation(Class<A> annotationClass)2594     public native <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass);
2595 
2596     /**
2597      * @since 1.5
2598      */
2599     @Override
2600     @FastNative
getDeclaredAnnotations()2601     public native Annotation[] getDeclaredAnnotations();
2602 
2603     /**
2604      * Returns true if the annotation exists.
2605      */
2606     @FastNative
isDeclaredAnnotationPresent(Class<? extends Annotation> annotationClass)2607     private native boolean isDeclaredAnnotationPresent(Class<? extends Annotation> annotationClass);
2608 
getSignatureAttribute()2609     private String getSignatureAttribute() {
2610         String[] annotation = getSignatureAnnotation();
2611         if (annotation == null) {
2612             return null;
2613         }
2614         StringBuilder result = new StringBuilder();
2615         for (String s : annotation) {
2616             result.append(s);
2617         }
2618         return result.toString();
2619     }
2620 
2621     @FastNative
getSignatureAnnotation()2622     private native String[] getSignatureAnnotation();
2623 
2624     /**
2625      * Is this a runtime created proxy class?
2626      *
2627      * @hide
2628      */
isProxy()2629     public boolean isProxy() {
2630         return (accessFlags & 0x00040000) != 0;
2631     }
2632 
2633     /**
2634      * @hide
2635      */
getAccessFlags()2636     public int getAccessFlags() {
2637         return accessFlags;
2638     }
2639 
2640 
2641     /**
2642      * Returns the method if it is defined by this class; {@code null} otherwise. This may return a
2643      * non-public member.
2644      *
2645      * @param name the method name
2646      * @param args the method's parameter types
2647      */
2648     @FastNative
getDeclaredMethodInternal(String name, Class<?>[] args)2649     private native Method getDeclaredMethodInternal(String name, Class<?>[] args);
2650 
2651     private static class Caches {
2652         /**
2653          * Cache to avoid frequent recalculation of generic interfaces, which is generally uncommon.
2654          * Sized sufficient to allow ConcurrentHashMapTest to run without recalculating its generic
2655          * interfaces (required to avoid time outs). Validated by running reflection heavy code
2656          * such as applications using Guice-like frameworks.
2657          */
2658         private static final BasicLruCache<Class, Type[]> genericInterfaces
2659             = new BasicLruCache<Class, Type[]>(8);
2660     }
2661 }
2662