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