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