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