1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17/*
18 * Copyright (C) 2006-2007 The Android Open Source Project
19 *
20 * Licensed under the Apache License, Version 2.0 (the "License");
21 * you may not use this file except in compliance with the License.
22 * You may obtain a copy of the License at
23 *
24 *      http://www.apache.org/licenses/LICENSE-2.0
25 *
26 * Unless required by applicable law or agreed to in writing, software
27 * distributed under the License is distributed on an "AS IS" BASIS,
28 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29 * See the License for the specific language governing permissions and
30 * limitations under the License.
31 */
32
33package java.lang;
34
35import com.android.dex.Dex;
36import dalvik.system.VMStack;
37import java.io.InputStream;
38import java.io.Serializable;
39import java.lang.annotation.Annotation;
40import java.lang.reflect.AbstractMethod;
41import java.lang.reflect.AccessibleObject;
42import java.lang.reflect.AnnotatedElement;
43import java.lang.reflect.ArtField;
44import java.lang.reflect.ArtMethod;
45import java.lang.reflect.Constructor;
46import java.lang.reflect.Field;
47import java.lang.reflect.GenericDeclaration;
48import java.lang.reflect.InvocationTargetException;
49import java.lang.reflect.Member;
50import java.lang.reflect.Method;
51import java.lang.reflect.Modifier;
52import java.lang.reflect.Type;
53import java.lang.reflect.TypeVariable;
54import java.net.URL;
55import java.security.ProtectionDomain;
56import java.util.ArrayList;
57import java.util.Arrays;
58import java.util.List;
59import libcore.reflect.AnnotationAccess;
60import libcore.reflect.GenericSignatureParser;
61import libcore.reflect.InternalNames;
62import libcore.reflect.Types;
63import libcore.util.BasicLruCache;
64import libcore.util.CollectionUtils;
65import libcore.util.EmptyArray;
66
67/**
68 * The in-memory representation of a Java class. This representation serves as
69 * the starting point for querying class-related information, a process usually
70 * called "reflection". There are basically three types of {@code Class}
71 * instances: those representing real classes and interfaces, those representing
72 * primitive types, and those representing array classes.
73 *
74 * <h4>Class instances representing object types (classes or interfaces)</h4>
75 * <p>
76 * These represent an ordinary class or interface as found in the class
77 * hierarchy. The name associated with these {@code Class} instances is simply
78 * the fully qualified class name of the class or interface that it represents.
79 * In addition to this human-readable name, each class is also associated by a
80 * so-called <em>descriptor</em>, which is the letter "L", followed by the
81 * class name and a semicolon (";"). The descriptor is what the runtime system
82 * uses internally for identifying the class (for example in a DEX file).
83 * </p>
84 * <h4>Classes representing primitive types</h4>
85 * <p>
86 * These represent the standard Java primitive types and hence share their
87 * names (for example "int" for the {@code int} primitive type). Although it is
88 * not possible to create new instances based on these {@code Class} instances,
89 * they are still useful for providing reflection information, and as the
90 * component type of array classes. There is one {@code Class} instance for each
91 * primitive type, and their descriptors are:
92 * </p>
93 * <ul>
94 * <li>{@code B} representing the {@code byte} primitive type</li>
95 * <li>{@code S} representing the {@code short} primitive type</li>
96 * <li>{@code I} representing the {@code int} primitive type</li>
97 * <li>{@code J} representing the {@code long} primitive type</li>
98 * <li>{@code F} representing the {@code float} primitive type</li>
99 * <li>{@code D} representing the {@code double} primitive type</li>
100 * <li>{@code C} representing the {@code char} primitive type</li>
101 * <li>{@code Z} representing the {@code boolean} primitive type</li>
102 * <li>{@code V} representing void function return values</li>
103 * </ul>
104 * <p>
105 * <h4>Classes representing array classes</h4>
106 * <p>
107 * These represent the classes of Java arrays. There is one such {@code Class}
108 * instance per combination of array leaf component type and arity (number of
109 * dimensions). In this case, the name associated with the {@code Class}
110 * consists of one or more left square brackets (one per dimension in the array)
111 * followed by the descriptor of the class representing the leaf component type,
112 * which can be either an object type or a primitive type. The descriptor of a
113 * {@code Class} representing an array type is the same as its name. Examples
114 * of array class descriptors are:
115 * </p>
116 * <ul>
117 * <li>{@code [I} representing the {@code int[]} type</li>
118 * <li>{@code [Ljava/lang/String;} representing the {@code String[]} type</li>
119 * <li>{@code [[[C} representing the {@code char[][][]} type (three dimensions!)</li>
120 * </ul>
121 */
122public final class Class<T> implements Serializable, AnnotatedElement, GenericDeclaration, Type {
123
124    private static final long serialVersionUID = 3206093459760846163L;
125
126    /** defining class loader, or NULL for the "bootstrap" system loader. */
127    private transient ClassLoader classLoader;
128
129    /**
130     * For array classes, the component class object for instanceof/checkcast (for String[][][],
131     * this will be String[][]). NULL for non-array classes.
132     */
133    private transient Class<?> componentType;
134    /**
135     * DexCache of resolved constant pool entries. Will be null for certain VM-generated classes
136     * e.g. arrays and primitive classes.
137     */
138    private transient DexCache dexCache;
139
140    /** static, private, and &lt;init&gt; methods. */
141    private transient ArtMethod[] directMethods;
142
143    /**
144     * Instance fields. These describe the layout of the contents of an Object. Note that only the
145     * fields directly declared by this class are listed in iFields; fields declared by a
146     * superclass are listed in the superclass's Class.iFields.
147     *
148     * All instance fields that refer to objects are guaranteed to be at the beginning of the field
149     * list.  {@link Class#numReferenceInstanceFields} specifies the number of reference fields.
150     */
151    private transient ArtField[] iFields;
152
153    /**
154     * The interface table (iftable_) contains pairs of a interface class and an array of the
155     * interface methods. There is one pair per interface supported by this class.  That
156     * means one pair for each interface we support directly, indirectly via superclass, or
157     * indirectly via a superinterface.  This will be null if neither we nor our superclass
158     * implement any interfaces.
159     *
160     * Why we need this: given "class Foo implements Face", declare "Face faceObj = new Foo()".
161     * Invoke faceObj.blah(), where "blah" is part of the Face interface.  We can't easily use a
162     * single vtable.
163     *
164     * For every interface a concrete class implements, we create an array of the concrete vtable_
165     * methods for the methods in the interface.
166     */
167    private transient Object[] ifTable;
168
169    /** Lazily computed name of this class; always prefer calling getName(). */
170    private transient String name;
171
172    /** Static fields */
173    private transient ArtField[] sFields;
174
175    /** The superclass, or NULL if this is java.lang.Object, an interface or primitive type. */
176    private transient Class<? super T> superClass;
177
178    /** If class verify fails, we must return same error on subsequent tries. */
179    private transient Class<?> verifyErrorClass;
180
181    /** Virtual methods defined in this class; invoked through vtable. */
182    private transient ArtMethod[] virtualMethods;
183
184    /**
185     * Virtual method table (vtable), for use by "invoke-virtual". The vtable from the superclass
186     * is copied in, and virtual methods from our class either replace those from the super or are
187     * appended. For abstract classes, methods may be created in the vtable that aren't in
188     * virtual_ methods_ for miranda methods.
189     */
190    private transient ArtMethod[] vtable;
191
192    /** access flags; low 16 bits are defined by VM spec */
193    private transient int accessFlags;
194
195    /**
196     * Total size of the Class instance; used when allocating storage on GC heap.
197     * See also {@link Class#objectSize}.
198     */
199    private transient int classSize;
200
201    /**
202     * tid used to check for recursive static initializer invocation.
203     */
204    private transient int clinitThreadId;
205
206    /**
207     * Class def index from dex file. An index of 65535 indicates that there is no class definition,
208     * for example for an array type.
209     * TODO: really 16bits as type indices are 16bit.
210     */
211    private transient int dexClassDefIndex;
212
213    /**
214     * Class type index from dex file, lazily computed. An index of 65535 indicates that the type
215     * index isn't known. Volatile to avoid double-checked locking bugs.
216     * TODO: really 16bits as type indices are 16bit.
217     */
218    private transient volatile int dexTypeIndex;
219
220    /** Number of instance fields that are object references. */
221    private transient int numReferenceInstanceFields;
222
223    /** Number of static fields that are object references. */
224    private transient int numReferenceStaticFields;
225
226    /**
227     * Total object size; used when allocating storage on GC heap. For interfaces and abstract
228     * classes this will be zero. See also {@link Class#classSize}.
229     */
230    private transient int objectSize;
231
232    /** Primitive type value, or 0 if not a primitive type; set for generated primitive classes. */
233    private transient int primitiveType;
234
235    /** Bitmap of offsets of iFields. */
236    private transient int referenceInstanceOffsets;
237
238    /** Bitmap of offsets of sFields. */
239    private transient int referenceStaticOffsets;
240
241    /** State of class initialization */
242    private transient int status;
243
244    private Class() {
245        // Prevent this class to be instantiated, instance should be created by JVM only
246    }
247
248    /**
249     * Returns a {@code Class} object which represents the class with
250     * the given name. The name should be the name of a non-primitive
251     * class, as described in the {@link Class class definition}.
252     * Primitive types can not be found using this method; use {@code
253     * int.class} or {@code Integer.TYPE} instead.
254     *
255     * <p>If the class has not yet been loaded, it is loaded and initialized
256     * first. This is done through either the class loader of the calling class
257     * or one of its parent class loaders. It is possible that a static initializer is run as
258     * a result of this call.
259     *
260     * @throws ClassNotFoundException
261     *             if the requested class cannot be found.
262     * @throws LinkageError
263     *             if an error occurs during linkage
264     * @throws ExceptionInInitializerError
265     *             if an exception occurs during static initialization of a
266     *             class.
267     */
268    public static Class<?> forName(String className) throws ClassNotFoundException {
269        return forName(className, true, VMStack.getCallingClassLoader());
270    }
271
272    /**
273     * Returns a {@code Class} object which represents the class with
274     * the given name. The name should be the name of a non-primitive
275     * class, as described in the {@link Class class definition}.
276     * Primitive types can not be found using this method; use {@code
277     * int.class} or {@code Integer.TYPE} instead.
278     *
279     * <p>If the class has not yet been loaded, it is loaded first, using the given class loader.
280     * If the class has not yet been initialized and {@code shouldInitialize} is true,
281     * the class will be initialized.
282     *
283     * @throws ClassNotFoundException
284     *             if the requested class cannot be found.
285     * @throws LinkageError
286     *             if an error occurs during linkage
287     * @throws ExceptionInInitializerError
288     *             if an exception occurs during static initialization of a
289     *             class.
290     */
291    public static Class<?> forName(String className, boolean shouldInitialize,
292            ClassLoader classLoader) throws ClassNotFoundException {
293
294        if (classLoader == null) {
295            classLoader = ClassLoader.getSystemClassLoader();
296        }
297        // Catch an Exception thrown by the underlying native code. It wraps
298        // up everything inside a ClassNotFoundException, even if e.g. an
299        // Error occurred during initialization. This as a workaround for
300        // an ExceptionInInitializerError that's also wrapped. It is actually
301        // expected to be thrown. Maybe the same goes for other errors.
302        // Not wrapping up all the errors will break android though.
303        Class<?> result;
304        try {
305            result = classForName(className, shouldInitialize, classLoader);
306        } catch (ClassNotFoundException e) {
307            Throwable cause = e.getCause();
308            if (cause instanceof LinkageError) {
309                throw (LinkageError) cause;
310            }
311            throw e;
312        }
313        return result;
314    }
315
316    static native Class<?> classForName(String className, boolean shouldInitialize,
317            ClassLoader classLoader) throws ClassNotFoundException;
318
319    /**
320     * Returns an array containing {@code Class} objects for all
321     * public classes, interfaces, enums and annotations that are
322     * members of this class and its superclasses. This does not
323     * include classes of implemented interfaces.  If there are no
324     * such class members or if this object represents a primitive
325     * type then an array of length 0 is returned.
326     */
327    public Class<?>[] getClasses() {
328        List<Class<?>> result = new ArrayList<Class<?>>();
329        for (Class<?> c = this; c != null; c = c.superClass) {
330            for (Class<?> member : c.getDeclaredClasses()) {
331                if (Modifier.isPublic(member.getModifiers())) {
332                    result.add(member);
333                }
334            }
335        }
336        return result.toArray(new Class[result.size()]);
337    }
338
339    @Override public <A extends Annotation> A getAnnotation(Class<A> annotationType) {
340        return AnnotationAccess.getAnnotation(this, annotationType);
341    }
342
343    /**
344     * Returns an array containing all the annotations of this class. If there are no annotations
345     * then an empty array is returned.
346     *
347     * @see #getDeclaredAnnotations()
348     */
349    @Override public Annotation[] getAnnotations() {
350        return AnnotationAccess.getAnnotations(this);
351    }
352
353    /**
354     * Returns the canonical name of this class. If this class does not have a
355     * canonical name as defined in the Java Language Specification, then the
356     * method returns {@code null}.
357     */
358    public String getCanonicalName() {
359        if (isLocalClass() || isAnonymousClass())
360            return null;
361
362        if (isArray()) {
363            /*
364             * The canonical name of an array type depends on the (existence of)
365             * the component type's canonical name.
366             */
367            String name = getComponentType().getCanonicalName();
368            if (name != null) {
369                return name + "[]";
370            }
371        } else if (isMemberClass()) {
372            /*
373             * The canonical name of an inner class depends on the (existence
374             * of) the declaring class' canonical name.
375             */
376            String name = getDeclaringClass().getCanonicalName();
377            if (name != null) {
378                return name + "." + getSimpleName();
379            }
380        } else {
381            /*
382             * The canonical name of a top-level class or primitive type is
383             * equal to the fully qualified name.
384             */
385            return getName();
386        }
387
388        /*
389         * Other classes don't have a canonical name.
390         */
391        return null;
392    }
393
394    /**
395     * Returns the class loader which was used to load the class represented by
396     * this {@code Class}. Implementations are free to return {@code null} for
397     * classes that were loaded by the bootstrap class loader. The Android
398     * reference implementation, though, always returns a reference to an actual
399     * class loader.
400     */
401    public ClassLoader getClassLoader() {
402        if (this.isPrimitive()) {
403            return null;
404        }
405
406        ClassLoader loader = getClassLoaderImpl();
407        if (loader == null) {
408            loader = BootClassLoader.getInstance();
409        }
410        return loader;
411    }
412
413    /**
414     * This must be provided by the VM vendor, as it is used by other provided
415     * class implementations in this package. Outside of this class, it is used
416     * by SecurityManager.classLoaderDepth(),
417     * currentClassLoader() and currentLoadedClass(). Return the ClassLoader for
418     * this Class without doing any security checks. The bootstrap ClassLoader
419     * is returned, unlike getClassLoader() which returns null in place of the
420     * bootstrap ClassLoader.
421     */
422    ClassLoader getClassLoaderImpl() {
423        ClassLoader loader = classLoader;
424        return loader == null ? BootClassLoader.getInstance() : loader;
425    }
426
427    /**
428     * Returns a {@code Class} object which represents the component type if
429     * this class represents an array type. Returns {@code null} if this class
430     * does not represent an array type. The component type of an array type is
431     * the type of the elements of the array.
432     */
433    public Class<?> getComponentType() {
434      return componentType;
435    }
436
437    /**
438     * Returns the dex file from which this class was loaded.
439     *
440     * @hide
441     */
442    public Dex getDex() {
443        if (dexCache == null) {
444            return null;
445        }
446        return dexCache.getDex();
447    }
448
449    /**
450     * Returns a string from the dex cache, computing the string from the dex file if necessary.
451     *
452     * @hide
453     */
454    public String getDexCacheString(Dex dex, int dexStringIndex) {
455        String[] dexCacheStrings = dexCache.strings;
456        String s = dexCacheStrings[dexStringIndex];
457        if (s == null) {
458            s = dex.strings().get(dexStringIndex).intern();
459            dexCacheStrings[dexStringIndex] = s;
460        }
461        return s;
462    }
463
464    /**
465     * Returns a resolved type from the dex cache, computing the type from the dex file if
466     * necessary.
467     *
468     * @hide
469     */
470    public Class<?> getDexCacheType(Dex dex, int dexTypeIndex) {
471        Class<?>[] dexCacheResolvedTypes = dexCache.resolvedTypes;
472        Class<?> resolvedType = dexCacheResolvedTypes[dexTypeIndex];
473        if (resolvedType == null) {
474            int descriptorIndex = dex.typeIds().get(dexTypeIndex);
475            String descriptor = getDexCacheString(dex, descriptorIndex);
476            resolvedType = InternalNames.getClass(getClassLoader(), descriptor);
477            dexCacheResolvedTypes[dexTypeIndex] = resolvedType;
478        }
479        return resolvedType;
480    }
481
482    /**
483     * Returns a {@code Constructor} object which represents the public
484     * constructor matching the given parameter types.
485     * {@code (Class[]) null} is equivalent to the empty array.
486     *
487     * @throws NoSuchMethodException
488     *             if the constructor cannot be found.
489     * @see #getDeclaredConstructor(Class[])
490     */
491    public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException {
492        return getConstructor(parameterTypes, true);
493    }
494
495    /**
496     * Returns a {@code Constructor} object which represents the constructor
497     * matching the specified parameter types that is declared by the class
498     * represented by this {@code Class}.
499     * {@code (Class[]) null} is equivalent to the empty array.
500     *
501     * @throws NoSuchMethodException
502     *             if the requested constructor cannot be found.
503     * @see #getConstructor(Class[])
504     */
505    public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
506            throws NoSuchMethodException {
507        return getConstructor(parameterTypes, false);
508    }
509
510    /**
511     * Returns a constructor with the given parameters.
512     *
513     * @param publicOnly true to only return public constructores.
514     * @param parameterTypes argument types to match the constructor's.
515     */
516    private Constructor<T> getConstructor(Class<?>[] parameterTypes, boolean publicOnly)
517            throws NoSuchMethodException {
518        if (parameterTypes == null) {
519            parameterTypes = EmptyArray.CLASS;
520        }
521        for (Class<?> c : parameterTypes) {
522            if (c == null) {
523                throw new NoSuchMethodException("parameter type is null");
524            }
525        }
526        Constructor<T> result = getDeclaredConstructorInternal(parameterTypes);
527        if (result == null || publicOnly && !Modifier.isPublic(result.getAccessFlags())) {
528            throw new NoSuchMethodException("<init> " + Arrays.toString(parameterTypes));
529        }
530        return result;
531    }
532
533    /**
534     * Returns the constructor with the given parameters if it is defined by this class; null
535     * otherwise. This may return a non-public member.
536     *
537     * @param args the types of the parameters to the constructor.
538     */
539    private Constructor<T> getDeclaredConstructorInternal(Class<?>[] args) {
540        if (directMethods != null) {
541            for (ArtMethod m : directMethods) {
542                int modifiers = m.getAccessFlags();
543                if (Modifier.isStatic(modifiers)) {
544                    // skip <clinit> which is a static constructor
545                    continue;
546                }
547                if (!Modifier.isConstructor(modifiers)) {
548                    continue;
549                }
550                if (!ArtMethod.equalConstructorParameters(m, args)) {
551                    continue;
552                }
553                return new Constructor<T>(m);
554            }
555        }
556        return null;
557    }
558
559    /**
560     * Returns an array containing {@code Constructor} objects for all public
561     * constructors for this {@code Class}. If there
562     * are no public constructors or if this {@code Class} represents an array
563     * class, a primitive type or void then an empty array is returned.
564     *
565     * @see #getDeclaredConstructors()
566     */
567    public Constructor<?>[] getConstructors() {
568        ArrayList<Constructor<T>> constructors = new ArrayList();
569        getDeclaredConstructors(true, constructors);
570        return constructors.toArray(new Constructor[constructors.size()]);
571    }
572
573    /**
574     * Returns an array containing {@code Constructor} objects for all
575     * constructors declared in the class represented by this {@code Class}. If
576     * there are no constructors or if this {@code Class} represents an array
577     * class, a primitive type or void then an empty array is returned.
578     *
579     * @see #getConstructors()
580     */
581    public Constructor<?>[] getDeclaredConstructors() {
582        ArrayList<Constructor<T>> constructors = new ArrayList();
583        getDeclaredConstructors(false, constructors);
584        return constructors.toArray(new Constructor[constructors.size()]);
585    }
586
587    private void getDeclaredConstructors(boolean publicOnly, List<Constructor<T>> constructors) {
588        if (directMethods != null) {
589            for (ArtMethod m : directMethods) {
590                int modifiers = m.getAccessFlags();
591                if (!publicOnly || Modifier.isPublic(modifiers)) {
592                    if (Modifier.isStatic(modifiers)) {
593                        // skip <clinit> which is a static constructor
594                        continue;
595                    }
596                    if (Modifier.isConstructor(modifiers)) {
597                        constructors.add(new Constructor<T>(m));
598                    }
599                }
600            }
601        }
602    }
603
604    /**
605     * Returns a {@code Method} object which represents the method matching the
606     * specified name and parameter types that is declared by the class
607     * represented by this {@code Class}.
608     *
609     * @param name
610     *            the requested method's name.
611     * @param parameterTypes
612     *            the parameter types of the requested method.
613     *            {@code (Class[]) null} is equivalent to the empty array.
614     * @return the method described by {@code name} and {@code parameterTypes}.
615     * @throws NoSuchMethodException
616     *             if the requested constructor cannot be found.
617     * @throws NullPointerException
618     *             if {@code name} is {@code null}.
619     * @see #getMethod(String, Class[])
620     */
621    public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
622            throws NoSuchMethodException {
623        return getMethod(name, parameterTypes, false);
624    }
625
626    /**
627     * Returns a {@code Method} object which represents the public method with
628     * the specified name and parameter types.
629     * {@code (Class[]) null} is equivalent to the empty array.
630     * This method first searches the
631     * class C represented by this {@code Class}, then the superclasses of C and
632     * finally the interfaces implemented by C and finally the superclasses of C
633     * for a method with matching name.
634     *
635     * @throws NoSuchMethodException
636     *             if the method cannot be found.
637     * @see #getDeclaredMethod(String, Class[])
638     */
639    public Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException {
640        return getMethod(name, parameterTypes, true);
641    }
642
643    private Method getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods)
644            throws NoSuchMethodException {
645        if (name == null) {
646            throw new NullPointerException("name == null");
647        }
648        if (parameterTypes == null) {
649            parameterTypes = EmptyArray.CLASS;
650        }
651        for (Class<?> c : parameterTypes) {
652            if (c == null) {
653                throw new NoSuchMethodException("parameter type is null");
654            }
655        }
656        Method result = recursivePublicMethods ? getPublicMethodRecursive(name, parameterTypes)
657                                               : getDeclaredMethodInternal(name, parameterTypes);
658        // Fail if we didn't find the method or it was expected to be public.
659        if (result == null ||
660            (recursivePublicMethods && !Modifier.isPublic(result.getAccessFlags()))) {
661            throw new NoSuchMethodException(name + " " + Arrays.toString(parameterTypes));
662        }
663        return result;
664    }
665
666    private Method getPublicMethodRecursive(String name, Class<?>[] parameterTypes) {
667        // search superclasses
668        for (Class<?> c = this; c != null; c = c.getSuperclass()) {
669            Method result = c.getDeclaredMethodInternal(name, parameterTypes);
670            if (result != null && Modifier.isPublic(result.getAccessFlags())) {
671                return result;
672            }
673        }
674        // search iftable which has a flattened and uniqued list of interfaces
675        Object[] iftable = ifTable;
676        if (iftable != null) {
677            for (int i = 0; i < iftable.length; i += 2) {
678                Class<?> ifc = (Class<?>) iftable[i];
679                Method result = ifc.getPublicMethodRecursive(name, parameterTypes);
680                if (result != null && Modifier.isPublic(result.getAccessFlags())) {
681                    return result;
682                }
683            }
684        }
685        return null;
686    }
687
688    /**
689     * Returns the method if it is defined by this class; null otherwise. This may return a
690     * non-public member.
691     *
692     * @param name the method name
693     * @param args the method's parameter types
694     */
695    private Method getDeclaredMethodInternal(String name, Class<?>[] args) {
696        // Covariant return types permit the class to define multiple
697        // methods with the same name and parameter types. Prefer to
698        // return a non-synthetic method in such situations. We may
699        // still return a synthetic method to handle situations like
700        // escalated visibility. We never return miranda methods that
701        // were synthesized by the VM.
702        int skipModifiers = Modifier.MIRANDA | Modifier.SYNTHETIC;
703        ArtMethod artMethodResult = null;
704        if (virtualMethods != null) {
705            for (ArtMethod m : virtualMethods) {
706                String methodName = ArtMethod.getMethodName(m);
707                if (!name.equals(methodName)) {
708                    continue;
709                }
710                if (!ArtMethod.equalMethodParameters(m, args)) {
711                    continue;
712                }
713                int modifiers = m.getAccessFlags();
714                if ((modifiers & skipModifiers) == 0) {
715                    return new Method(m);
716                }
717                if ((modifiers & Modifier.MIRANDA) == 0) {
718                    // Remember as potential result if it's not a miranda method.
719                    artMethodResult = m;
720                }
721            }
722        }
723        if (artMethodResult == null) {
724            if (directMethods != null) {
725                for (ArtMethod m : directMethods) {
726                    int modifiers = m.getAccessFlags();
727                    if (Modifier.isConstructor(modifiers)) {
728                        continue;
729                    }
730                    String methodName = ArtMethod.getMethodName(m);
731                    if (!name.equals(methodName)) {
732                        continue;
733                    }
734                    if (!ArtMethod.equalMethodParameters(m, args)) {
735                        continue;
736                    }
737                    if ((modifiers & skipModifiers) == 0) {
738                        return new Method(m);
739                    }
740                    // Direct methods cannot be miranda methods,
741                    // so this potential result must be synthetic.
742                    artMethodResult = m;
743                }
744            }
745        }
746        if (artMethodResult == null) {
747            return null;
748        }
749        return new Method(artMethodResult);
750    }
751
752    /**
753     * Returns an array containing {@code Method} objects for all methods
754     * declared in the class represented by this {@code Class}. If there are no
755     * methods or if this {@code Class} represents an array class, a primitive
756     * type or void then an empty array is returned.
757     *
758     * @see #getMethods()
759     */
760    public Method[] getDeclaredMethods() {
761        int initial_size = virtualMethods == null ? 0 : virtualMethods.length;
762        initial_size += directMethods == null ? 0 : directMethods.length;
763        ArrayList<Method> methods = new ArrayList<Method>(initial_size);
764        getDeclaredMethods(false, methods);
765        Method[] result = methods.toArray(new Method[methods.size()]);
766        for (Method m : result) {
767            // Throw NoClassDefFoundError if types cannot be resolved.
768            m.getReturnType();
769            m.getParameterTypes();
770        }
771        return result;
772
773    }
774
775    /**
776     * Returns the list of methods without performing any security checks
777     * first. If no methods exist, an empty array is returned.
778     */
779    private void getDeclaredMethods(boolean publicOnly, List<Method> methods) {
780        if (virtualMethods != null) {
781            for (ArtMethod m : virtualMethods) {
782                int modifiers = m.getAccessFlags();
783                if (!publicOnly || Modifier.isPublic(modifiers)) {
784                    // Add non-miranda virtual methods.
785                    if ((modifiers & Modifier.MIRANDA) == 0) {
786                        methods.add(new Method(m));
787                    }
788                }
789            }
790        }
791        if (directMethods != null) {
792            for (ArtMethod m : directMethods) {
793                int modifiers = m.getAccessFlags();
794                if (!publicOnly || Modifier.isPublic(modifiers)) {
795                    // Add non-constructor direct/static methods.
796                    if (!Modifier.isConstructor(modifiers)) {
797                        methods.add(new Method(m));
798                    }
799                }
800            }
801        }
802    }
803
804    /**
805     * Returns an array containing {@code Method} objects for all public methods
806     * for the class C represented by this {@code Class}. Methods may be
807     * declared in C, the interfaces it implements or in the superclasses of C.
808     * The elements in the returned array are in no particular order.
809     *
810     * <p>If there are no public methods or if this {@code Class} represents a
811     * primitive type or {@code void} then an empty array is returned.
812     *
813     * @see #getDeclaredMethods()
814     */
815    public Method[] getMethods() {
816        List<Method> methods = new ArrayList<Method>();
817        getPublicMethodsInternal(methods);
818        /*
819         * Remove duplicate methods defined by superclasses and
820         * interfaces, preferring to keep methods declared by derived
821         * types.
822         */
823        CollectionUtils.removeDuplicates(methods, Method.ORDER_BY_SIGNATURE);
824        return methods.toArray(new Method[methods.size()]);
825    }
826
827    /**
828     * Populates {@code result} with public methods defined by this class, its
829     * superclasses, and all implemented interfaces, including overridden methods.
830     */
831    private void getPublicMethodsInternal(List<Method> result) {
832        getDeclaredMethods(true, result);
833        if (!isInterface()) {
834            // Search superclasses, for interfaces don't search java.lang.Object.
835            for (Class<?> c = superClass; c != null; c = c.superClass) {
836                c.getDeclaredMethods(true, result);
837            }
838        }
839        // Search iftable which has a flattened and uniqued list of interfaces.
840        Object[] iftable = ifTable;
841        if (iftable != null) {
842            for (int i = 0; i < iftable.length; i += 2) {
843                Class<?> ifc = (Class<?>) iftable[i];
844                ifc.getDeclaredMethods(true, result);
845            }
846        }
847    }
848
849    /**
850     * Returns the annotations that are directly defined on the class
851     * represented by this {@code Class}. Annotations that are inherited are not
852     * included in the result. If there are no annotations at all, an empty
853     * array is returned.
854     *
855     * @see #getAnnotations()
856     */
857    @Override public Annotation[] getDeclaredAnnotations() {
858        List<Annotation> result = AnnotationAccess.getDeclaredAnnotations(this);
859        return result.toArray(new Annotation[result.size()]);
860    }
861
862    /**
863     * Returns an array containing {@code Class} objects for all classes,
864     * interfaces, enums and annotations that are members of this class.
865     */
866    public Class<?>[] getDeclaredClasses() {
867        return AnnotationAccess.getMemberClasses(this);
868    }
869
870    /**
871     * Returns a {@code Field} object for the field with the given name
872     * which is declared in the class represented by this {@code Class}.
873     *
874     * @throws NoSuchFieldException if the requested field can not be found.
875     * @see #getField(String)
876     */
877    public Field getDeclaredField(String name) throws NoSuchFieldException {
878        if (name == null) {
879            throw new NullPointerException("name == null");
880        }
881        Field result = getDeclaredFieldInternal(name);
882        if (result == null) {
883            throw new NoSuchFieldException(name);
884        } else {
885            result.getType();  // Throw NoClassDefFoundError if type cannot be resolved.
886        }
887        return result;
888    }
889
890    /**
891     * Returns an array containing {@code Field} objects for all fields declared
892     * in the class represented by this {@code Class}. If there are no fields or
893     * if this {@code Class} represents an array class, a primitive type or void
894     * then an empty array is returned.
895     *
896     * @see #getFields()
897     */
898    public Field[] getDeclaredFields() {
899        int initial_size = sFields == null ? 0 : sFields.length;
900        initial_size += iFields == null ? 0 : iFields.length;
901        ArrayList<Field> fields = new ArrayList(initial_size);
902        getDeclaredFields(false, fields);
903        Field[] result = fields.toArray(new Field[fields.size()]);
904        for (Field f : result) {
905            f.getType();  // Throw NoClassDefFoundError if type cannot be resolved.
906        }
907        return result;
908    }
909
910    private void getDeclaredFields(boolean publicOnly, List<Field> fields) {
911        if (iFields != null) {
912            for (ArtField f : iFields) {
913                if (!publicOnly || Modifier.isPublic(f.getAccessFlags())) {
914                    fields.add(new Field(f));
915                }
916            }
917        }
918        if (sFields != null) {
919            for (ArtField f : sFields) {
920                if (!publicOnly || Modifier.isPublic(f.getAccessFlags())) {
921                    fields.add(new Field(f));
922                }
923            }
924        }
925    }
926
927    /**
928     * Returns the field if it is defined by this class; null otherwise. This
929     * may return a non-public member.
930     */
931    private Field getDeclaredFieldInternal(String name) {
932        if (iFields != null) {
933            for (ArtField f : iFields) {
934                if (f.getName().equals(name)) {
935                    return new Field(f);
936                }
937            }
938        }
939        if (sFields != null) {
940            for (ArtField f : sFields) {
941                if (f.getName().equals(name)) {
942                    return new Field(f);
943                }
944            }
945        }
946        return null;
947    }
948
949    /**
950     * Returns the class that this class is a member of, or {@code null} if this
951     * class is a top-level class, a primitive, an array, or defined within a
952     * method or constructor.
953     */
954    public Class<?> getDeclaringClass() {
955        return AnnotationAccess.getDeclaringClass(this);
956    }
957
958    /**
959     * Returns the class enclosing this class. For most classes this is the same
960     * as the {@link #getDeclaringClass() declaring class}. For classes defined
961     * within a method or constructor (typically anonymous inner classes), this
962     * is the declaring class of that member.
963     */
964    public Class<?> getEnclosingClass() {
965        Class<?> declaringClass = getDeclaringClass();
966        if (declaringClass != null) {
967            return declaringClass;
968        }
969        AccessibleObject member = AnnotationAccess.getEnclosingMethodOrConstructor(this);
970        return member != null
971                ? ((Member) member).getDeclaringClass()
972                : null;
973    }
974
975    /**
976     * Returns the enclosing {@code Constructor} of this {@code Class}, if it is an
977     * anonymous or local/automatic class; otherwise {@code null}.
978     */
979    public Constructor<?> getEnclosingConstructor() {
980        if (classNameImpliesTopLevel()) {
981            return null;
982        }
983        AccessibleObject result = AnnotationAccess.getEnclosingMethodOrConstructor(this);
984        return result instanceof Constructor ? (Constructor<?>) result : null;
985    }
986
987    /**
988     * Returns the enclosing {@code Method} of this {@code Class}, if it is an
989     * anonymous or local/automatic class; otherwise {@code null}.
990     */
991    public Method getEnclosingMethod() {
992        if (classNameImpliesTopLevel()) {
993            return null;
994        }
995        AccessibleObject result = AnnotationAccess.getEnclosingMethodOrConstructor(this);
996        return result instanceof Method ? (Method) result : null;
997    }
998
999    /**
1000     * Returns true if this class is definitely a top level class, or false if
1001     * a more expensive check like {@link #getEnclosingClass()} is necessary.
1002     *
1003     * <p>This is a hack that exploits an implementation detail of all Java
1004     * language compilers: generated names always contain "$". As it is possible
1005     * for a top level class to be named with a "$", a false result <strong>does
1006     * not</strong> indicate that this isn't a top-level class.
1007     */
1008    private boolean classNameImpliesTopLevel() {
1009        return !getName().contains("$");
1010    }
1011
1012    /**
1013     * Returns the {@code enum} constants associated with this {@code Class}.
1014     * Returns {@code null} if this {@code Class} does not represent an {@code
1015     * enum} type.
1016     */
1017    @SuppressWarnings("unchecked") // we only cast after confirming that this class is an enum
1018    public T[] getEnumConstants() {
1019        if (!isEnum()) {
1020            return null;
1021        }
1022        return (T[]) Enum.getSharedConstants((Class) this).clone();
1023    }
1024
1025    /**
1026     * Returns a {@code Field} object which represents the public field with the
1027     * given name. This method first searches the class C represented by
1028     * this {@code Class}, then the interfaces implemented by C and finally the
1029     * superclasses of C.
1030     *
1031     * @throws NoSuchFieldException
1032     *             if the field cannot be found.
1033     * @see #getDeclaredField(String)
1034     */
1035    public Field getField(String name) throws NoSuchFieldException {
1036        if (name == null) {
1037            throw new NullPointerException("name == null");
1038        }
1039        Field result = getPublicFieldRecursive(name);
1040        if (result == null) {
1041            throw new NoSuchFieldException(name);
1042        } else {
1043            result.getType();  // Throw NoClassDefFoundError if type cannot be resolved.
1044        }
1045        return result;
1046    }
1047
1048    private Field getPublicFieldRecursive(String name) {
1049        // search superclasses
1050        for (Class<?> c = this; c != null; c = c.superClass) {
1051            Field result = c.getDeclaredFieldInternal(name);
1052            if (result != null && (result.getModifiers() & Modifier.PUBLIC) != 0) {
1053                return result;
1054            }
1055        }
1056
1057        // search iftable which has a flattened and uniqued list of interfaces
1058        if (ifTable != null) {
1059            for (int i = 0; i < ifTable.length; i += 2) {
1060                Class<?> ifc = (Class<?>) ifTable[i];
1061                Field result = ifc.getPublicFieldRecursive(name);
1062                if (result != null && (result.getModifiers() & Modifier.PUBLIC) != 0) {
1063                    return result;
1064                }
1065            }
1066        }
1067
1068        return null;
1069    }
1070
1071    /**
1072     * Returns an array containing {@code Field} objects for all public fields
1073     * for the class C represented by this {@code Class}. Fields may be declared
1074     * in C, the interfaces it implements or in the superclasses of C. The
1075     * elements in the returned array are in no particular order.
1076     *
1077     * <p>If there are no public fields or if this class represents an array class,
1078     * a primitive type or {@code void} then an empty array is returned.
1079     *
1080     * @see #getDeclaredFields()
1081     */
1082    public Field[] getFields() {
1083        List<Field> fields = new ArrayList<Field>();
1084        getPublicFieldsRecursive(fields);
1085        Field[] result = fields.toArray(new Field[fields.size()]);
1086        for (Field f : result) {
1087            f.getType();  // Throw NoClassDefFoundError if type cannot be resolved.
1088        }
1089        return result;
1090    }
1091
1092    /**
1093     * Populates {@code result} with public fields defined by this class, its
1094     * superclasses, and all implemented interfaces.
1095     */
1096    private void getPublicFieldsRecursive(List<Field> result) {
1097        // search superclasses
1098        for (Class<?> c = this; c != null; c = c.superClass) {
1099            c.getDeclaredFields(true, result);
1100        }
1101
1102        // search iftable which has a flattened and uniqued list of interfaces
1103        Object[] iftable = ifTable;
1104        if (iftable != null) {
1105            for (int i = 0; i < iftable.length; i += 2) {
1106                Class<?> ifc = (Class<?>) iftable[i];
1107                ifc.getDeclaredFields(true, result);
1108            }
1109        }
1110    }
1111
1112    /**
1113     * Returns the {@link Type}s of the interfaces that this {@code Class} directly
1114     * implements. If the {@code Class} represents a primitive type or {@code
1115     * void} then an empty array is returned.
1116     */
1117    public Type[] getGenericInterfaces() {
1118        Type[] result;
1119        synchronized (Caches.genericInterfaces) {
1120            result = Caches.genericInterfaces.get(this);
1121            if (result == null) {
1122                String annotationSignature = AnnotationAccess.getSignature(this);
1123                if (annotationSignature == null) {
1124                    result = getInterfaces();
1125                } else {
1126                    GenericSignatureParser parser = new GenericSignatureParser(getClassLoader());
1127                    parser.parseForClass(this, annotationSignature);
1128                    result = Types.getTypeArray(parser.interfaceTypes, false);
1129                }
1130                Caches.genericInterfaces.put(this, result);
1131            }
1132        }
1133        return (result.length == 0) ? result : result.clone();
1134    }
1135
1136    /**
1137     * Returns the {@code Type} that represents the superclass of this {@code
1138     * class}.
1139     */
1140    public Type getGenericSuperclass() {
1141        Type genericSuperclass = getSuperclass();
1142        String annotationSignature = AnnotationAccess.getSignature(this);
1143        if (annotationSignature != null) {
1144            GenericSignatureParser parser = new GenericSignatureParser(getClassLoader());
1145            parser.parseForClass(this, annotationSignature);
1146            genericSuperclass = parser.superclassType;
1147        }
1148        return Types.getType(genericSuperclass);
1149    }
1150
1151    /**
1152     * Returns an array of {@code Class} objects that match the interfaces
1153     * in the {@code implements} declaration of the class represented
1154     * by this {@code Class}. The order of the elements in the array is
1155     * identical to the order in the original class declaration. If the class
1156     * does not implement any interfaces, an empty array is returned.
1157     *
1158     * <p>This method only returns directly-implemented interfaces, and does not
1159     * include interfaces implemented by superclasses or superinterfaces of any
1160     * implemented interfaces.
1161     */
1162    public Class<?>[] getInterfaces() {
1163        if (isArray()) {
1164            return new Class<?>[] { Cloneable.class, Serializable.class };
1165        } else if (isProxy()) {
1166            return getProxyInterfaces();
1167        }
1168        Dex dex = getDex();
1169        if (dex == null) {
1170            return EmptyArray.CLASS;
1171        }
1172        short[] interfaces = dex.interfaceTypeIndicesFromClassDefIndex(dexClassDefIndex);
1173        Class<?>[] result = new Class<?>[interfaces.length];
1174        for (int i = 0; i < interfaces.length; i++) {
1175            result[i] = getDexCacheType(dex, interfaces[i]);
1176        }
1177        return result;
1178    }
1179
1180    // Returns the interfaces that this proxy class directly implements.
1181    private native Class<?>[] getProxyInterfaces();
1182
1183    /**
1184     * Returns an integer that represents the modifiers of the class represented
1185     * by this {@code Class}. The returned value is a combination of bits
1186     * defined by constants in the {@link Modifier} class.
1187     */
1188    public int getModifiers() {
1189        // Array classes inherit modifiers from their component types, but in the case of arrays
1190        // of an inner class, the class file may contain "fake" access flags because it's not valid
1191        // for a top-level class to private, say. The real access flags are stored in the InnerClass
1192        // attribute, so we need to make sure we drill down to the inner class: the accessFlags
1193        // field is not the value we want to return, and the synthesized array class does not itself
1194        // have an InnerClass attribute. https://code.google.com/p/android/issues/detail?id=56267
1195        if (isArray()) {
1196            int componentModifiers = getComponentType().getModifiers();
1197            if ((componentModifiers & Modifier.INTERFACE) != 0) {
1198                componentModifiers &= ~(Modifier.INTERFACE | Modifier.STATIC);
1199            }
1200            return Modifier.ABSTRACT | Modifier.FINAL | componentModifiers;
1201        }
1202        int JAVA_FLAGS_MASK = 0xffff;
1203        int modifiers = AnnotationAccess.getInnerClassFlags(this, accessFlags & JAVA_FLAGS_MASK);
1204        return modifiers & JAVA_FLAGS_MASK;
1205    }
1206
1207    /**
1208     * Returns the name of the class represented by this {@code Class}. For a
1209     * description of the format which is used, see the class definition of
1210     * {@link Class}.
1211     */
1212    public String getName() {
1213        String result = name;
1214        return (result == null) ? (name = getNameNative()) : result;
1215    }
1216
1217    private native String getNameNative();
1218
1219    /**
1220     * Returns the simple name of the class represented by this {@code Class} as
1221     * defined in the source code. If there is no name (that is, the class is
1222     * anonymous) then an empty string is returned. If the receiver is an array
1223     * then the name of the underlying type with square braces appended (for
1224     * example {@code "Integer[]"}) is returned.
1225     *
1226     * @return the simple name of the class represented by this {@code Class}.
1227     */
1228    public String getSimpleName() {
1229        if (isArray()) {
1230            return getComponentType().getSimpleName() + "[]";
1231        }
1232
1233        if (isAnonymousClass()) {
1234            return "";
1235        }
1236
1237        if (isMemberClass() || isLocalClass()) {
1238            return getInnerClassName();
1239        }
1240
1241        String name = getName();
1242        int dot = name.lastIndexOf('.');
1243        if (dot != -1) {
1244            return name.substring(dot + 1);
1245        }
1246
1247        return name;
1248    }
1249
1250    /**
1251     * Returns the simple name of a member or local class, or null otherwise.
1252     */
1253    private String getInnerClassName() {
1254        return AnnotationAccess.getInnerClassName(this);
1255    }
1256
1257    /**
1258     * Returns null.
1259     */
1260    public ProtectionDomain getProtectionDomain() {
1261        return null;
1262    }
1263
1264    /**
1265     * Returns the URL of the given resource, or null if the resource is not found.
1266     * The mapping between the resource name and the URL is managed by the class' class loader.
1267     *
1268     * @see ClassLoader
1269     */
1270    public URL getResource(String resourceName) {
1271        // Get absolute resource name, but without the leading slash
1272        if (resourceName.startsWith("/")) {
1273            resourceName = resourceName.substring(1);
1274        } else {
1275            String pkg = getName();
1276            int dot = pkg.lastIndexOf('.');
1277            if (dot != -1) {
1278                pkg = pkg.substring(0, dot).replace('.', '/');
1279            } else {
1280                pkg = "";
1281            }
1282
1283            resourceName = pkg + "/" + resourceName;
1284        }
1285
1286        // Delegate to proper class loader
1287        ClassLoader loader = getClassLoader();
1288        if (loader != null) {
1289            return loader.getResource(resourceName);
1290        } else {
1291            return ClassLoader.getSystemResource(resourceName);
1292        }
1293    }
1294
1295    /**
1296     * Returns a read-only stream for the contents of the given resource, or null if the resource
1297     * is not found.
1298     * The mapping between the resource name and the stream is managed by the class' class loader.
1299     *
1300     * @see ClassLoader
1301     */
1302    public InputStream getResourceAsStream(String resourceName) {
1303        // Get absolute resource name, but without the leading slash
1304        if (resourceName.startsWith("/")) {
1305            resourceName = resourceName.substring(1);
1306        } else {
1307            String pkg = getName();
1308            int dot = pkg.lastIndexOf('.');
1309            if (dot != -1) {
1310                pkg = pkg.substring(0, dot).replace('.', '/');
1311            } else {
1312                pkg = "";
1313            }
1314
1315            resourceName = pkg + "/" + resourceName;
1316        }
1317
1318        // Delegate to proper class loader
1319        ClassLoader loader = getClassLoader();
1320        if (loader != null) {
1321            return loader.getResourceAsStream(resourceName);
1322        } else {
1323            return ClassLoader.getSystemResourceAsStream(resourceName);
1324        }
1325    }
1326
1327    /**
1328     * Returns null. (On Android, a {@code ClassLoader} can load classes from multiple dex files.
1329     * All classes from any given dex file will have the same signers, but different dex
1330     * files may have different signers. This does not fit well with the original
1331     * {@code ClassLoader}-based model of {@code getSigners}.)
1332     */
1333    public Object[] getSigners() {
1334        // See http://code.google.com/p/android/issues/detail?id=1766.
1335        return null;
1336    }
1337
1338    /**
1339     * Returns the {@code Class} object which represents the superclass of the
1340     * class represented by this {@code Class}. If this {@code Class} represents
1341     * the {@code Object} class, a primitive type, an interface or void then the
1342     * method returns {@code null}. If this {@code Class} represents an array
1343     * class then the {@code Object} class is returned.
1344     */
1345    public Class<? super T> getSuperclass() {
1346      // For interfaces superClass is Object (which agrees with the JNI spec)
1347      // but not with the expected behavior here.
1348      if (isInterface()) {
1349        return null;
1350      } else {
1351        return superClass;
1352      }
1353    }
1354
1355    /**
1356     * Returns an array containing {@code TypeVariable} objects for type
1357     * variables declared by the generic class represented by this {@code
1358     * Class}. Returns an empty array if the class is not generic.
1359     */
1360    @SuppressWarnings("unchecked")
1361    @Override public synchronized TypeVariable<Class<T>>[] getTypeParameters() {
1362        String annotationSignature = AnnotationAccess.getSignature(this);
1363        if (annotationSignature == null) {
1364            return EmptyArray.TYPE_VARIABLE;
1365        }
1366        GenericSignatureParser parser = new GenericSignatureParser(getClassLoader());
1367        parser.parseForClass(this, annotationSignature);
1368        return parser.formalTypeParameters;
1369    }
1370
1371    /**
1372     * Tests whether this {@code Class} represents an annotation class.
1373     */
1374    public boolean isAnnotation() {
1375        final int ACC_ANNOTATION = 0x2000;  // not public in reflect.Modifier
1376        return (accessFlags & ACC_ANNOTATION) != 0;
1377    }
1378
1379    @Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {
1380        return AnnotationAccess.isAnnotationPresent(this, annotationType);
1381    }
1382
1383    /**
1384     * Tests whether the class represented by this {@code Class} is
1385     * anonymous.
1386     */
1387    public boolean isAnonymousClass() {
1388        return AnnotationAccess.isAnonymousClass(this);
1389    }
1390
1391    /**
1392     * Tests whether the class represented by this {@code Class} is an array class.
1393     */
1394    public boolean isArray() {
1395        return getComponentType() != null;
1396    }
1397
1398    /**
1399     * Is this a runtime created proxy class?
1400     *
1401     * @hide
1402     */
1403    public boolean isProxy() {
1404        return (accessFlags & 0x00040000) != 0;
1405    }
1406
1407    /**
1408     * Can {@code c}  be assigned to this class? For example, String can be assigned to Object
1409     * (by an upcast), however, an Object cannot be assigned to a String as a potentially exception
1410     * throwing downcast would be necessary. Similarly for interfaces, a class that implements (or
1411     * an interface that extends) another can be assigned to its parent, but not vice-versa. All
1412     * Classes may assign to themselves. Classes for primitive types may not assign to each other.
1413     *
1414     * @param c the class to check.
1415     * @return {@code true} if {@code c} can be assigned to the class
1416     *         represented by this {@code Class}; {@code false} otherwise.
1417     * @throws NullPointerException if {@code c} is {@code null}.
1418     */
1419    public boolean isAssignableFrom(Class<?> c) {
1420        if (this == c) {
1421            return true;  // Can always assign to things of the same type.
1422        } else if (this == Object.class) {
1423            return !c.isPrimitive();  // Can assign any reference to java.lang.Object.
1424        } else if (isArray()) {
1425            return c.isArray() && componentType.isAssignableFrom(c.componentType);
1426        } else if (isInterface()) {
1427            // Search iftable which has a flattened and uniqued list of interfaces.
1428            Object[] iftable = c.ifTable;
1429            if (iftable != null) {
1430                for (int i = 0; i < iftable.length; i += 2) {
1431                    Class<?> ifc = (Class<?>) iftable[i];
1432                    if (ifc == this) {
1433                        return true;
1434                    }
1435                }
1436            }
1437            return false;
1438        } else {
1439            if (!c.isInterface()) {
1440                for (c = c.superClass; c != null; c = c.superClass) {
1441                    if (c == this) {
1442                        return true;
1443                    }
1444                }
1445            }
1446            return false;
1447        }
1448    }
1449
1450    /**
1451     * Tests whether the class represented by this {@code Class} is an
1452     * {@code enum}.
1453     */
1454    public boolean isEnum() {
1455        return (getSuperclass() == Enum.class) && ((accessFlags & 0x4000) != 0);
1456    }
1457
1458    /**
1459     * Tests whether the given object can be cast to the class
1460     * represented by this {@code Class}. This is the runtime version of the
1461     * {@code instanceof} operator.
1462     *
1463     * @return {@code true} if {@code object} can be cast to the type
1464     *         represented by this {@code Class}; {@code false} if {@code
1465     *         object} is {@code null} or cannot be cast.
1466     */
1467    public boolean isInstance(Object object) {
1468        if (object == null) {
1469            return false;
1470        }
1471        return isAssignableFrom(object.getClass());
1472    }
1473
1474    /**
1475     * Tests whether this {@code Class} represents an interface.
1476     */
1477    public boolean isInterface() {
1478      return (accessFlags & Modifier.INTERFACE) != 0;
1479    }
1480
1481    /**
1482     * Tests whether the class represented by this {@code Class} is defined
1483     * locally.
1484     */
1485    public boolean isLocalClass() {
1486        return !classNameImpliesTopLevel()
1487                && AnnotationAccess.getEnclosingMethodOrConstructor(this) != null
1488                && !isAnonymousClass();
1489    }
1490
1491    /**
1492     * Tests whether the class represented by this {@code Class} is a member
1493     * class.
1494     */
1495    public boolean isMemberClass() {
1496        return getDeclaringClass() != null;
1497    }
1498
1499    /**
1500     * Tests whether this {@code Class} represents a primitive type.
1501     */
1502    public boolean isPrimitive() {
1503      return primitiveType != 0;
1504    }
1505
1506    /**
1507     * Tests whether this {@code Class} represents a synthetic type.
1508     */
1509    public boolean isSynthetic() {
1510        final int ACC_SYNTHETIC = 0x1000;   // not public in reflect.Modifier
1511        return (accessFlags & ACC_SYNTHETIC) != 0;
1512    }
1513
1514    /**
1515     * Indicates whether this {@code Class} or its parents override finalize.
1516     *
1517     * @hide
1518     */
1519    public boolean isFinalizable() {
1520      final int ACC_CLASS_IS_FINALIZABLE = 0x80000000;  // not public in reflect.Modifier
1521      return (accessFlags & ACC_CLASS_IS_FINALIZABLE) != 0;
1522    }
1523
1524    /**
1525     * Returns a new instance of the class represented by this {@code Class},
1526     * created by invoking the default (that is, zero-argument) constructor. If
1527     * there is no such constructor, or if the creation fails (either because of
1528     * a lack of available memory or because an exception is thrown by the
1529     * constructor), an {@code InstantiationException} is thrown. If the default
1530     * constructor exists but is not accessible from the context where this
1531     * method is invoked, an {@code IllegalAccessException} is thrown.
1532     *
1533     * @throws IllegalAccessException
1534     *             if the default constructor is not visible.
1535     * @throws InstantiationException
1536     *             if the instance cannot be created.
1537     */
1538    public T newInstance() throws InstantiationException, IllegalAccessException {
1539        if (isPrimitive() || isInterface() || isArray() || Modifier.isAbstract(accessFlags)) {
1540            throw new InstantiationException(this + " cannot be instantiated");
1541        }
1542        Class<?> caller = VMStack.getStackClass1();
1543        if (!caller.canAccess(this)) {
1544            throw new IllegalAccessException(this + " is not accessible from " + caller);
1545        }
1546        Constructor<T> init;
1547        try {
1548            init = getDeclaredConstructor();
1549        } catch (NoSuchMethodException e) {
1550            InstantiationException t =
1551                new InstantiationException(this + " has no zero argument constructor");
1552            t.initCause(e);
1553            throw t;
1554        }
1555        if (!caller.canAccessMember(this, init.getAccessFlags())) {
1556            throw new IllegalAccessException(init + " is not accessible from " + caller);
1557        }
1558        try {
1559            return init.newInstance();
1560        } catch (InvocationTargetException e) {
1561            InstantiationException t = new InstantiationException(this);
1562            t.initCause(e);
1563            throw t;
1564        }
1565    }
1566
1567    private boolean canAccess(Class<?> c) {
1568        if(Modifier.isPublic(c.accessFlags)) {
1569            return true;
1570        }
1571        return inSamePackage(c);
1572    }
1573
1574    private boolean canAccessMember(Class<?> memberClass, int memberModifiers) {
1575        if (memberClass == this || Modifier.isPublic(memberModifiers)) {
1576            return true;
1577        }
1578        if (Modifier.isPrivate(memberModifiers)) {
1579            return false;
1580        }
1581        if (Modifier.isProtected(memberModifiers)) {
1582            for (Class<?> parent = this.superClass; parent != null; parent = parent.superClass) {
1583                if (parent == memberClass) {
1584                    return true;
1585                }
1586            }
1587        }
1588        return inSamePackage(memberClass);
1589    }
1590
1591    private boolean inSamePackage(Class<?> c) {
1592        if (classLoader != c.classLoader) {
1593            return false;
1594        }
1595        String packageName1 = getPackageName$();
1596        String packageName2 = c.getPackageName$();
1597        if (packageName1 == null) {
1598            return packageName2 == null;
1599        } else if (packageName2 == null) {
1600            return false;
1601        } else {
1602            return packageName1.equals(packageName2);
1603        }
1604    }
1605
1606    @Override
1607    public String toString() {
1608        if (isPrimitive()) {
1609            return getSimpleName();
1610        } else {
1611            return (isInterface() ? "interface " : "class ") + getName();
1612        }
1613    }
1614
1615    /**
1616     * Returns the {@code Package} of which the class represented by this
1617     * {@code Class} is a member. Returns {@code null} if no {@code Package}
1618     * object was created by the class loader of the class.
1619     */
1620    public Package getPackage() {
1621        // TODO This might be a hack, but the VM doesn't have the necessary info.
1622        ClassLoader loader = getClassLoader();
1623        if (loader != null) {
1624            String packageName = getPackageName$();
1625            return packageName != null ? loader.getPackage(packageName) : null;
1626        }
1627        return null;
1628    }
1629
1630    /**
1631     * Returns the package name of this class. This returns null for classes in
1632     * the default package.
1633     *
1634     * @hide
1635     */
1636    public String getPackageName$() {
1637        String name = getName();
1638        int last = name.lastIndexOf('.');
1639        return last == -1 ? null : name.substring(0, last);
1640    }
1641
1642    /**
1643     * Returns the assertion status for the class represented by this {@code
1644     * Class}. Assertion is enabled / disabled based on the class loader,
1645     * package or class default at runtime.
1646     */
1647    public boolean desiredAssertionStatus() {
1648      return false;
1649    }
1650
1651    /**
1652     * Casts this {@code Class} to represent a subclass of the given class.
1653     * If successful, this {@code Class} is returned; otherwise a {@code
1654     * ClassCastException} is thrown.
1655     *
1656     * @throws ClassCastException
1657     *             if this {@code Class} cannot be cast to the given type.
1658     */
1659    @SuppressWarnings("unchecked")
1660    public <U> Class<? extends U> asSubclass(Class<U> c) {
1661        if (c.isAssignableFrom(this)) {
1662            return (Class<? extends U>)this;
1663        }
1664        String actualClassName = this.getName();
1665        String desiredClassName = c.getName();
1666        throw new ClassCastException(actualClassName + " cannot be cast to " + desiredClassName);
1667    }
1668
1669    /**
1670     * Casts the given object to the type represented by this {@code Class}.
1671     * If the object is {@code null} then the result is also {@code null}.
1672     *
1673     * @throws ClassCastException
1674     *             if the object cannot be cast to the given type.
1675     */
1676    @SuppressWarnings("unchecked")
1677    public T cast(Object obj) {
1678        if (obj == null) {
1679            return null;
1680        } else if (this.isInstance(obj)) {
1681            return (T)obj;
1682        }
1683        String actualClassName = obj.getClass().getName();
1684        String desiredClassName = this.getName();
1685        throw new ClassCastException(actualClassName + " cannot be cast to " + desiredClassName);
1686    }
1687
1688    /**
1689     * The class def of this class in its own Dex, or -1 if there is no class def.
1690     *
1691     * @hide
1692     */
1693    public int getDexClassDefIndex() {
1694        return (dexClassDefIndex == 65535) ? -1 : dexClassDefIndex;
1695    }
1696
1697    /**
1698     * The type index of this class in its own Dex, or -1 if it is unknown. If a class is referenced
1699     * by multiple Dex files, it will have a different type index in each. Dex files support 65534
1700     * type indices, with 65535 representing no index.
1701     *
1702     * @hide
1703     */
1704    public int getDexTypeIndex() {
1705        int typeIndex = dexTypeIndex;
1706        if (typeIndex != 65535) {
1707            return typeIndex;
1708        }
1709        synchronized (this) {
1710            typeIndex = dexTypeIndex;
1711            if (typeIndex == 65535) {
1712                if (dexClassDefIndex >= 0) {
1713                    typeIndex = getDex().typeIndexFromClassDefIndex(dexClassDefIndex);
1714                } else {
1715                    typeIndex = getDex().findTypeIndex(InternalNames.getInternalName(this));
1716                    if (typeIndex < 0) {
1717                        typeIndex = -1;
1718                    }
1719                }
1720                dexTypeIndex = typeIndex;
1721            }
1722        }
1723        return typeIndex;
1724    }
1725
1726    /**
1727     * The annotation directory offset of this class in its own Dex, or 0 if it
1728     * is unknown.
1729     *
1730     * TODO: 0 is a sentinel that means 'no annotations directory'; this should be -1 if unknown
1731     *
1732     * @hide
1733     */
1734    public int getDexAnnotationDirectoryOffset() {
1735        Dex dex = getDex();
1736        if (dex == null) {
1737            return 0;
1738        }
1739        int classDefIndex = getDexClassDefIndex();
1740        if (classDefIndex < 0) {
1741            return 0;
1742        }
1743        return dex.annotationDirectoryOffsetFromClassDefIndex(classDefIndex);
1744    }
1745
1746    private static class Caches {
1747        /**
1748         * Cache to avoid frequent recalculation of generic interfaces, which is generally uncommon.
1749         * Sized sufficient to allow ConcurrentHashMapTest to run without recalculating its generic
1750         * interfaces (required to avoid time outs). Validated by running reflection heavy code
1751         * such as applications using Guice-like frameworks.
1752         */
1753        private static final BasicLruCache<Class, Type[]> genericInterfaces
1754            = new BasicLruCache<Class, Type[]>(8);
1755    }
1756}
1757