1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1994, 2021, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package java.lang;
28 
29 import dalvik.annotation.compat.VersionCodes;
30 import dalvik.annotation.optimization.FastNative;
31 import dalvik.system.ClassExt;
32 import dalvik.system.VMRuntime;
33 
34 import java.io.Serializable;
35 import java.lang.annotation.Annotation;
36 import java.lang.annotation.Inherited;
37 import java.lang.constant.ClassDesc;
38 import java.lang.constant.ClassDesc;
39 import java.lang.constant.Constable;
40 import java.lang.invoke.TypeDescriptor;
41 import java.lang.invoke.MethodHandles;
42 import java.lang.ref.SoftReference;
43 import java.io.IOException;
44 import java.io.InputStream;
45 import java.io.ObjectStreamField;
46 import java.lang.invoke.TypeDescriptor;
47 import java.lang.invoke.MethodHandles;
48 import java.lang.reflect.AnnotatedElement;
49 import java.lang.reflect.Array;
50 import java.lang.reflect.Constructor;
51 import java.lang.reflect.Executable;
52 import java.lang.reflect.Field;
53 import java.lang.reflect.GenericArrayType;
54 import java.lang.reflect.GenericDeclaration;
55 import java.lang.reflect.InvocationTargetException;
56 import java.lang.reflect.Member;
57 import java.lang.reflect.Method;
58 import java.lang.reflect.Modifier;
59 import java.lang.reflect.Parameter;
60 import java.lang.reflect.Proxy;
61 import java.lang.reflect.RecordComponent;
62 import java.lang.reflect.Type;
63 import java.lang.reflect.TypeVariable;
64 import java.lang.constant.Constable;
65 import java.net.URL;
66 import java.security.AccessController;
67 import java.security.PrivilegedAction;
68 import java.util.ArrayList;
69 import java.util.Arrays;
70 import java.util.Collection;
71 import java.util.Collections;
72 import java.util.HashMap;
73 import java.util.HashSet;
74 import java.util.LinkedHashMap;
75 import java.util.LinkedHashSet;
76 import java.util.List;
77 import java.util.Map;
78 import java.util.Objects;
79 import java.util.Optional;
80 import java.util.Set;
81 import java.util.StringJoiner;
82 import java.util.stream.Collectors;
83 import jdk.internal.HotSpotIntrinsicCandidate;
84 import jdk.internal.vm.annotation.IntrinsicCandidate;
85 import jdk.internal.misc.Unsafe;
86 import jdk.internal.misc.VM;
87 import libcore.reflect.GenericSignatureParser;
88 import libcore.reflect.InternalNames;
89 import libcore.reflect.RecordComponents;
90 import libcore.reflect.Types;
91 import libcore.util.BasicLruCache;
92 import libcore.util.CollectionUtils;
93 import libcore.util.EmptyArray;
94 
95 import jdk.internal.misc.Unsafe;
96 import jdk.internal.reflect.CallerSensitive;
97 import jdk.internal.reflect.Reflection;
98 import jdk.internal.vm.annotation.IntrinsicCandidate;
99 import sun.invoke.util.Wrapper;
100 import sun.security.util.SecurityConstants;
101 import sun.reflect.misc.ReflectUtil;
102 
103 
104 // Android-changed: Removed javadoc related to hidden classes.
105 // Android-changed: Removed javadoc related to loading from class file.
106 /**
107  * Instances of the class {@code Class} represent classes and
108  * interfaces in a running Java application. An enum class and a record
109  * class are kinds of class; an annotation interface is a kind of
110  * interface. Every array also belongs to a class that is reflected as
111  * a {@code Class} object that is shared by all arrays with the same
112  * element type and number of dimensions.  The primitive Java types
113  * ({@code boolean}, {@code byte}, {@code char}, {@code short}, {@code
114  * int}, {@code long}, {@code float}, and {@code double}), and the
115  * keyword {@code void} are also represented as {@code Class} objects.
116  *
117  * <p> {@code Class} has no public constructor. Instead a {@code Class}
118  * object is constructed automatically by the Java Virtual Machine when
119  * a class is derived from the bytes of a {@code class} file through
120  * the invocation of one of the following methods:
121  * <ul>
122  * <li> {@link ClassLoader#defineClass(String, byte[], int, int) ClassLoader::defineClass}
123  * </ul>
124  *
125  * <p> The methods of class {@code Class} expose many characteristics of a
126  * class or interface. Most characteristics are derived from the {@code class}
127  * file that the class loader passed to the Java Virtual Machine. A few
128  * characteristics are determined by the class loading environment at run time.
129  *
130  * <p> The following example uses a {@code Class} object to print the
131  * class name of an object:
132  *
133  * <blockquote><pre>
134  *     void printClassName(Object obj) {
135  *         System.out.println("The class of " + obj +
136  *                            " is " + obj.getClass().getName());
137  *     }
138  * </pre></blockquote>
139  *
140  * It is also possible to get the {@code Class} object for a named
141  * class or interface (or for {@code void}) using a <i>class literal</i>.
142  * For example:
143  *
144  * <blockquote>
145  *     {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
146  * </blockquote>
147  *
148  * <p> Some methods of class {@code Class} expose whether the declaration of
149  * a class or interface in Java source code was <em>enclosed</em> within
150  * another declaration. Other methods describe how a class or interface
151  * is situated in a <em>nest</em>. A <a id="nest">nest</a> is a set of
152  * classes and interfaces, in the same run-time package, that
153  * allow mutual access to their {@code private} members.
154  * The classes and interfaces are known as <em>nestmates</em>.
155  * One nestmate acts as the
156  * <em>nest host</em>, and enumerates the other nestmates which
157  * belong to the nest; each of them in turn records it as the nest host.
158  * The classes and interfaces which belong to a nest, including its host, are
159  * determined when
160  * {@code class} files are generated, for example, a Java compiler
161  * will typically record a top-level class as the host of a nest where the
162  * other members are the classes and interfaces whose declarations are
163  * enclosed within the top-level class declaration.
164  *
165  * <p> Some methods of class {@code Class} expose whether the declaration of
166  * a class or interface in Java source code was <em>enclosed</em> within
167  * another declaration. Other methods describe how a class or interface
168  * is situated in a <em>nest</em>. A <a id="nest">nest</a> is a set of
169  * classes and interfaces, in the same run-time package, that
170  * allow mutual access to their {@code private} members.
171  * The classes and interfaces are known as <em>nestmates</em>.
172  * One nestmate acts as the
173  * <em>nest host</em>, and enumerates the other nestmates which
174  * belong to the nest; each of them in turn records it as the nest host.
175  * The classes and interfaces which belong to a nest, including its host, are
176  * determined when
177  * {@code class} files are generated, for example, a Java compiler
178  * will typically record a top-level class as the host of a nest where the
179  * other members are the classes and interfaces whose declarations are
180  * enclosed within the top-level class declaration.
181  *
182  * @param <T> the type of the class modeled by this {@code Class}
183  * object.  For example, the type of {@code String.class} is {@code
184  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
185  * unknown.
186  *
187  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
188  * @since   1.0
189  * @jls 15.8.2 Class Literals
190  */
191 public final class Class<T> implements java.io.Serializable,
192                               GenericDeclaration,
193                               Type,
194                               AnnotatedElement,
195                               TypeDescriptor.OfField<Class<?>>,
196                               Constable {
197     private static final int ANNOTATION= 0x00002000;
198     private static final int ENUM      = 0x00004000;
199     private static final int SYNTHETIC = 0x00001000;
200     private static final int FINALIZABLE = 0x80000000;
201 
202     /** defining class loader, or null for the "bootstrap" system loader. */
203     private transient ClassLoader classLoader;
204 
205     /**
206      * For array classes, the component class object for instanceof/checkcast (for String[][][],
207      * this will be String[][]). null for non-array classes.
208      */
209     private transient Class<?> componentType;
210 
211     /**
212      * DexCache of resolved constant pool entries. Will be null for certain runtime-generated classes
213      * e.g. arrays and primitive classes.
214      */
215     private transient Object dexCache;
216 
217     /**
218      * Extra data that only some classes possess. This is allocated lazily as needed.
219      */
220     private transient ClassExt extData;
221 
222     /**
223      * The interface table (iftable_) contains pairs of a interface class and an array of the
224      * interface methods. There is one pair per interface supported by this class.  That
225      * means one pair for each interface we support directly, indirectly via superclass, or
226      * indirectly via a superinterface.  This will be null if neither we nor our superclass
227      * implement any interfaces.
228      *
229      * Why we need this: given "class Foo implements Face", declare "Face faceObj = new Foo()".
230      * Invoke faceObj.blah(), where "blah" is part of the Face interface.  We can't easily use a
231      * single vtable.
232      *
233      * For every interface a concrete class implements, we create an array of the concrete vtable_
234      * methods for the methods in the interface.
235      */
236     private transient Object[] ifTable;
237 
238     /** Lazily computed name of this class; always prefer calling getName(). */
239     private transient String name;
240 
241     /** The superclass, or null if this is java.lang.Object, an interface or primitive type. */
242     private transient Class<? super T> superClass;
243 
244     /**
245      * Virtual method table (vtable), for use by "invoke-virtual". The vtable from the superclass
246      * is copied in, and virtual methods from our class either replace those from the super or are
247      * appended. For abstract classes, methods may be created in the vtable that aren't in
248      * virtual_ methods_ for miranda methods.
249      */
250     private transient Object vtable;
251 
252     /**
253      * Instance fields. These describe the layout of the contents of an Object. Note that only the
254      * fields directly declared by this class are listed in iFields; fields declared by a
255      * superclass are listed in the superclass's Class.iFields.
256      *
257      * All instance fields that refer to objects are guaranteed to be at the beginning of the field
258      * list.  {@link Class#numReferenceInstanceFields} specifies the number of reference fields.
259      */
260     private transient long iFields;
261 
262     /** All methods with this class as the base for virtual dispatch. */
263     private transient long methods;
264 
265     /** Static fields */
266     private transient long sFields;
267 
268     /** access flags; low 16 bits are defined by VM spec */
269     private transient int accessFlags;
270 
271     /** Class flags to help the GC with object scanning. */
272     private transient int classFlags;
273 
274     /**
275      * Total size of the Class instance; used when allocating storage on GC heap.
276      * See also {@link Class#objectSize}.
277      */
278     private transient int classSize;
279 
280     /**
281      * tid used to check for recursive static initializer invocation.
282      */
283     private transient int clinitThreadId;
284 
285     /**
286      * Class def index from dex file. An index of 65535 indicates that there is no class definition,
287      * for example for an array type.
288      * TODO: really 16bits as type indices are 16bit.
289      */
290     private transient int dexClassDefIndex;
291 
292     /**
293      * Class type index from dex file, lazily computed. An index of 65535 indicates that the type
294      * index isn't known. Volatile to avoid double-checked locking bugs.
295      * TODO: really 16bits as type indices are 16bit.
296      */
297     private transient volatile int dexTypeIndex;
298 
299     /** Number of instance fields that are object references. */
300     private transient int numReferenceInstanceFields;
301 
302     /** Number of static fields that are object references. */
303     private transient int numReferenceStaticFields;
304 
305     /**
306      * Total object size; used when allocating storage on GC heap. For interfaces and abstract
307      * classes this will be zero. See also {@link Class#classSize}.
308      */
309     private transient int objectSize;
310 
311     /**
312      * Aligned object size for allocation fast path. The value is max int if the object is
313      * uninitialized or finalizable, otherwise the aligned object size.
314      */
315     private transient int objectSizeAllocFastPath;
316 
317     /**
318      * The lower 16 bits is the primitive type value, or 0 if not a primitive type; set for
319      * generated primitive classes.
320      */
321     private transient int primitiveType;
322 
323     /** Bitmap of offsets of iFields. */
324     private transient int referenceInstanceOffsets;
325 
326     /** State of class initialization */
327     private transient int status;
328 
329     /** Offset of the first virtual method copied from an interface in the methods array. */
330     private transient short copiedMethodsOffset;
331 
332     /** Offset of the first virtual method defined in this class in the methods array. */
333     private transient short virtualMethodsOffset;
334 
335     /*
336      * Private constructor. Only the Java Virtual Machine creates Class objects.
337      * This constructor is not used and prevents the default constructor being
338      * generated.
339      */
Class()340     private Class() {}
341 
Class(ClassLoader loader, Class<?> arrayComponentType)342     private Class(ClassLoader loader, Class<?> arrayComponentType) {
343         // Initialize final field for classLoader.  The initialization value of non-null
344         // prevents future JIT optimizations from assuming this final field is null.
345         classLoader = loader;
346         componentType = arrayComponentType;
347     }
348 
349     /**
350      * Converts the object to a string. The string representation is the
351      * string "class" or "interface", followed by a space, and then by the
352      * name of the class in the format returned by {@code getName}.
353      * If this {@code Class} object represents a primitive type,
354      * this method returns the name of the primitive type.  If
355      * this {@code Class} object represents void this method returns
356      * "void". If this {@code Class} object represents an array type,
357      * this method returns "class " followed by {@code getName}.
358      *
359      * @return a string representation of this {@code Class} object.
360      */
toString()361     public String toString() {
362         return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
363             + getName();
364     }
365 
366     /**
367      * Returns a string describing this {@code Class}, including
368      * information about modifiers and type parameters.
369      *
370      * The string is formatted as a list of type modifiers, if any,
371      * followed by the kind of type (empty string for primitive types
372      * and {@code class}, {@code enum}, {@code interface},
373      * {@code @interface}, or {@code record} as appropriate), followed
374      * by the type's name, followed by an angle-bracketed
375      * comma-separated list of the type's type parameters, if any,
376      * including informative bounds on the type parameters, if any.
377      *
378      * A space is used to separate modifiers from one another and to
379      * separate any modifiers from the kind of type. The modifiers
380      * occur in canonical order. If there are no type parameters, the
381      * type parameter list is elided.
382      *
383      * For an array type, the string starts with the type name,
384      * followed by an angle-bracketed comma-separated list of the
385      * type's type parameters, if any, followed by a sequence of
386      * {@code []} characters, one set of brackets per dimension of
387      * the array.
388      *
389      * <p>Note that since information about the runtime representation
390      * of a type is being generated, modifiers not present on the
391      * originating source code or illegal on the originating source
392      * code may be present.
393      *
394      * @return a string describing this {@code Class}, including
395      * information about modifiers and type parameters
396      *
397      * @since 1.8
398      */
toGenericString()399     public String toGenericString() {
400         if (isPrimitive()) {
401             return toString();
402         } else {
403             StringBuilder sb = new StringBuilder();
404             Class<?> component = this;
405             int arrayDepth = 0;
406 
407             if (isArray()) {
408                 do {
409                     arrayDepth++;
410                     component = component.getComponentType();
411                 } while (component.isArray());
412                 sb.append(component.getName());
413             } else {
414                 // Class modifiers are a superset of interface modifiers
415                 int modifiers = getModifiers() & Modifier.classModifiers();
416                 if (modifiers != 0) {
417                     sb.append(Modifier.toString(modifiers));
418                     sb.append(' ');
419                 }
420 
421                 if (isAnnotation()) {
422                     sb.append('@');
423                 }
424                 if (isInterface()) { // Note: all annotation interfaces are interfaces
425                     sb.append("interface");
426                 } else {
427                     if (isEnum())
428                         sb.append("enum");
429                     else if (isRecord())
430                         sb.append("record");
431                     else
432                         sb.append("class");
433                 }
434                 sb.append(' ');
435                 sb.append(getName());
436             }
437 
438             TypeVariable<?>[] typeparms = component.getTypeParameters();
439             if (typeparms.length > 0) {
440                 // Android-changed: Don't print the generic string of inner types on Android 14 or
441                 // lower due to app compatibility.
442                 if (VMRuntime.getSdkVersion() >= VersionCodes.VANILLA_ICE_CREAM) {
443                     sb.append(Arrays.stream(typeparms)
444                             .map(Class::typeVarBounds)
445                             .collect(Collectors.joining(",", "<", ">")));
446                 } else {
447                     StringJoiner sj = new StringJoiner(",", "<", ">");
448                     for(TypeVariable<?> typeparm: typeparms) {
449                         sj.add(typeparm.getTypeName());
450                     }
451                     sb.append(sj.toString());
452                 }
453             }
454 
455             if (arrayDepth > 0) sb.append("[]".repeat(arrayDepth));
456 
457             return sb.toString();
458         }
459     }
460 
typeVarBounds(TypeVariable<?> typeVar)461     static String typeVarBounds(TypeVariable<?> typeVar) {
462         Type[] bounds = typeVar.getBounds();
463         if (bounds.length == 1 && bounds[0].equals(Object.class)) {
464             return typeVar.getName();
465         } else {
466             return typeVar.getName() + " extends " +
467                 Arrays.stream(bounds)
468                 .map(Type::getTypeName)
469                 .collect(Collectors.joining(" & "));
470         }
471     }
472 
473     /**
474      * Returns the {@code Class} object associated with the class or
475      * interface with the given string name.  Invoking this method is
476      * equivalent to:
477      *
478      * <blockquote>
479      *  {@code Class.forName(className, true, currentLoader)}
480      * </blockquote>
481      *
482      * where {@code currentLoader} denotes the defining class loader of
483      * the current class.
484      *
485      * <p> For example, the following code fragment returns the
486      * runtime {@code Class} descriptor for the class named
487      * {@code java.lang.Thread}:
488      *
489      * <blockquote>
490      *   {@code Class t = Class.forName("java.lang.Thread")}
491      * </blockquote>
492      * <p>
493      * A call to {@code forName("X")} causes the class named
494      * {@code X} to be initialized.
495      *
496      * @param      className   the fully qualified name of the desired class.
497      * @return     the {@code Class} object for the class with the
498      *             specified name.
499      * @throws    LinkageError if the linkage fails
500      * @throws    ExceptionInInitializerError if the initialization provoked
501      *            by this method fails
502      * @throws    ClassNotFoundException if the class cannot be located
503      *
504      * @jls 12.2 Loading of Classes and Interfaces
505      * @jls 12.3 Linking of Classes and Interfaces
506      * @jls 12.4 Initialization of Classes and Interfaces
507      */
508     @CallerSensitive
forName(String className)509     public static Class<?> forName(String className)
510                 throws ClassNotFoundException {
511         Class<?> caller = Reflection.getCallerClass();
512         return forName(className, true, ClassLoader.getClassLoader(caller));
513     }
514 
515     // Android-changed: Remove SecurityException javadoc.
516     /**
517      * Returns the {@code Class} object associated with the class or
518      * interface with the given string name, using the given class loader.
519      * Given the fully qualified name for a class or interface (in the same
520      * format returned by {@code getName}) this method attempts to
521      * locate and load the class or interface.  The specified class
522      * loader is used to load the class or interface.  If the parameter
523      * {@code loader} is null, the class is loaded through the bootstrap
524      * class loader.  The class is initialized only if the
525      * {@code initialize} parameter is {@code true} and if it has
526      * not been initialized earlier.
527      *
528      * <p> If {@code name} denotes a primitive type or void, an attempt
529      * will be made to locate a user-defined class in the unnamed package whose
530      * name is {@code name}. Therefore, this method cannot be used to
531      * obtain any of the {@code Class} objects representing primitive
532      * types or void.
533      *
534      * <p> If {@code name} denotes an array class, the component type of
535      * the array class is loaded but not initialized.
536      *
537      * <p> For example, in an instance method the expression:
538      *
539      * <blockquote>
540      *  {@code Class.forName("Foo")}
541      * </blockquote>
542      *
543      * is equivalent to:
544      *
545      * <blockquote>
546      *  {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
547      * </blockquote>
548      *
549      * Note that this method throws errors related to loading, linking
550      * or initializing as specified in Sections {@jls 12.2}, {@jls
551      * 12.3}, and {@jls 12.4} of <cite>The Java Language
552      * Specification</cite>.
553      * Note that this method does not check whether the requested class
554      * is accessible to its caller.
555      *
556      * @param name       fully qualified name of the desired class
557 
558      * @param initialize if {@code true} the class will be initialized
559      *                   (which implies linking). See Section {@jls
560      *                   12.4} of <cite>The Java Language
561      *                   Specification</cite>.
562      * @param loader     class loader from which the class must be loaded
563      * @return           class object representing the desired class
564      *
565      * @throws    LinkageError if the linkage fails
566      * @throws    ExceptionInInitializerError if the initialization provoked
567      *            by this method fails
568      * @throws    ClassNotFoundException if the class cannot be located by
569      *            the specified class loader
570      *
571      * @see       java.lang.Class#forName(String)
572      * @see       java.lang.ClassLoader
573      *
574      * @jls 12.2 Loading of Classes and Interfaces
575      * @jls 12.3 Linking of Classes and Interfaces
576      * @jls 12.4 Initialization of Classes and Interfaces
577      * @since     1.2
578      */
579     @CallerSensitive
forName(String name, boolean initialize, ClassLoader loader)580     public static Class<?> forName(String name, boolean initialize,
581                                    ClassLoader loader)
582         throws ClassNotFoundException
583     {
584         // Android-changed: Android has no SecurityManager.
585         /*
586         Class<?> caller = null;
587         @SuppressWarnings("removal")
588         SecurityManager sm = System.getSecurityManager();
589         if (sm != null) {
590             // Reflective call to get caller class is only needed if a security manager
591             // is present.  Avoid the overhead of making this call otherwise.
592             caller = Reflection.getCallerClass();
593             if (loader == null) {
594                 ClassLoader ccl = ClassLoader.getClassLoader(caller);
595                 if (ccl != null) {
596                     sm.checkPermission(
597                         SecurityConstants.GET_CLASSLOADER_PERMISSION);
598                 }
599             }
600         }
601         */
602         if (loader == null) {
603             loader = BootClassLoader.getInstance();
604         }
605         Class<?> result;
606         try {
607             result = classForName(name, initialize, loader);
608         } catch (ClassNotFoundException e) {
609             Throwable cause = e.getCause();
610             if (cause instanceof LinkageError) {
611                 throw (LinkageError) cause;
612             }
613             throw e;
614         }
615         return result;
616     }
617 
618     /** Called after security checks have been made. */
619     @FastNative
classForName(String className, boolean shouldInitialize, ClassLoader classLoader)620     static native Class<?> classForName(String className, boolean shouldInitialize,
621             ClassLoader classLoader) throws ClassNotFoundException;
622 
623     // Android-removed: Remove unsupported forName(Module, String) method.
624     /*
625      * Returns the {@code Class} with the given <a href="ClassLoader.html#name">
626      * binary name</a> in the given module.
627      *
628      * <p> This method attempts to locate and load the class or interface.
629      * It does not link the class, and does not run the class initializer.
630      * If the class is not found, this method returns {@code null}. </p>
631      *
632      * <p> If the class loader of the given module defines other modules and
633      * the given name is a class defined in a different module, this method
634      * returns {@code null} after the class is loaded. </p>
635      *
636      * <p> This method does not check whether the requested class is
637      * accessible to its caller. </p>
638      *
639      * @apiNote
640      * This method returns {@code null} on failure rather than
641      * throwing a {@link ClassNotFoundException}, as is done by
642      * the {@link #forName(String, boolean, ClassLoader)} method.
643      * The security check is a stack-based permission check if the caller
644      * loads a class in another module.
645      *
646      * @param  module   A module
647      * @param  name     The <a href="ClassLoader.html#binary-name">binary name</a>
648      *                  of the class
649      * @return {@code Class} object of the given name defined in the given module;
650      *         {@code null} if not found.
651      *
652      * @throws NullPointerException if the given module or name is {@code null}
653      *
654      * @throws LinkageError if the linkage fails
655      *
656      * @throws SecurityException
657      *         <ul>
658      *         <li> if the caller is not the specified module and
659      *         {@code RuntimePermission("getClassLoader")} permission is denied; or</li>
660      *         <li> access to the module content is denied. For example,
661      *         permission check will be performed when a class loader calls
662      *         {@link ModuleReader#open(String)} to read the bytes of a class file
663      *         in a module.</li>
664      *         </ul>
665      *
666      * @jls 12.2 Loading of Classes and Interfaces
667      * @jls 12.3 Linking of Classes and Interfaces
668      * @since 9
669      * @spec JPMS
670      *
671     @CallerSensitive
672     public static Class<?> forName(Module module, String name) {
673         Objects.requireNonNull(module);
674         Objects.requireNonNull(name);
675 
676         ClassLoader cl;
677         SecurityManager sm = System.getSecurityManager();
678         if (sm != null) {
679             Class<?> caller = Reflection.getCallerClass();
680             if (caller != null && caller.getModule() != module) {
681                 // if caller is null, Class.forName is the last java frame on the stack.
682                 // java.base has all permissions
683                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
684             }
685             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
686             cl = AccessController.doPrivileged(pa);
687         } else {
688             cl = module.getClassLoader();
689         }
690 
691         if (cl != null) {
692             return cl.loadClass(module, name);
693         } else {
694             return BootLoader.loadClass(module, name);
695         }
696     }
697     */
698 
699     // Android-changed: Remove SecurityException javadoc.
700     /**
701      * Creates a new instance of the class represented by this {@code Class}
702      * object.  The class is instantiated as if by a {@code new}
703      * expression with an empty argument list.  The class is initialized if it
704      * has not already been initialized.
705      *
706      * @deprecated This method propagates any exception thrown by the
707      * nullary constructor, including a checked exception.  Use of
708      * this method effectively bypasses the compile-time exception
709      * checking that would otherwise be performed by the compiler.
710      * The {@link
711      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
712      * Constructor.newInstance} method avoids this problem by wrapping
713      * any exception thrown by the constructor in a (checked) {@link
714      * java.lang.reflect.InvocationTargetException}.
715      *
716      * <p>The call
717      *
718      * <pre>{@code
719      * clazz.newInstance()
720      * }</pre>
721      *
722      * can be replaced by
723      *
724      * <pre>{@code
725      * clazz.getDeclaredConstructor().newInstance()
726      * }</pre>
727      *
728      * The latter sequence of calls is inferred to be able to throw
729      * the additional exception types {@link
730      * InvocationTargetException} and {@link
731      * NoSuchMethodException}. Both of these exception types are
732      * subclasses of {@link ReflectiveOperationException}.
733      *
734      * @return  a newly allocated instance of the class represented by this
735      *          object.
736      * @throws  IllegalAccessException  if the class or its nullary
737      *          constructor is not accessible.
738      * @throws  InstantiationException
739      *          if this {@code Class} represents an abstract class,
740      *          an interface, an array class, a primitive type, or void;
741      *          or if the class has no nullary constructor;
742      *          or if the instantiation fails for some other reason.
743      * @throws  ExceptionInInitializerError if the initialization
744      *          provoked by this method fails.
745      */
746     // Android-changed: Implement newInstance() by native code.
747     /*
748     @SuppressWarnings("removal")
749     @CallerSensitive
750     public T newInstance()
751         throws InstantiationException, IllegalAccessException
752     {
753         SecurityManager sm = System.getSecurityManager();
754         if (sm != null) {
755             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false);
756         }
757 
758         // Constructor lookup
759         Constructor<T> tmpConstructor = cachedConstructor;
760         if (tmpConstructor == null) {
761             if (this == Class.class) {
762                 throw new IllegalAccessException(
763                     "Can not call newInstance() on the Class for java.lang.Class"
764                 );
765             }
766             try {
767                 Class<?>[] empty = {};
768                 final Constructor<T> c = getReflectionFactory().copyConstructor(
769                     getConstructor0(empty, Member.DECLARED));
770                 // Disable accessibility checks on the constructor
771                 // access check is done with the true caller
772                 java.security.AccessController.doPrivileged(
773                     new java.security.PrivilegedAction<>() {
774                         public Void run() {
775                                 c.setAccessible(true);
776                                 return null;
777                             }
778                         });
779                 cachedConstructor = tmpConstructor = c;
780             } catch (NoSuchMethodException e) {
781                 throw (InstantiationException)
782                     new InstantiationException(getName()).initCause(e);
783             }
784         }
785 
786         try {
787             Class<?> caller = Reflection.getCallerClass();
788             return getReflectionFactory().newInstance(tmpConstructor, null, caller);
789         } catch (InvocationTargetException e) {
790             Unsafe.getUnsafe().throwException(e.getTargetException());
791             // Not reached
792             return null;
793         }
794     }
795 
796     private transient volatile Constructor<T> cachedConstructor;
797     */
798     @FastNative
799     @Deprecated(since="9")
newInstance()800     public native T newInstance() throws InstantiationException, IllegalAccessException;
801 
802     /**
803      * Determines if the specified {@code Object} is assignment-compatible
804      * with the object represented by this {@code Class}.  This method is
805      * the dynamic equivalent of the Java language {@code instanceof}
806      * operator. The method returns {@code true} if the specified
807      * {@code Object} argument is non-null and can be cast to the
808      * reference type represented by this {@code Class} object without
809      * raising a {@code ClassCastException.} It returns {@code false}
810      * otherwise.
811      *
812      * <p> Specifically, if this {@code Class} object represents a
813      * declared class, this method returns {@code true} if the specified
814      * {@code Object} argument is an instance of the represented class (or
815      * of any of its subclasses); it returns {@code false} otherwise. If
816      * this {@code Class} object represents an array class, this method
817      * returns {@code true} if the specified {@code Object} argument
818      * can be converted to an object of the array class by an identity
819      * conversion or by a widening reference conversion; it returns
820      * {@code false} otherwise. If this {@code Class} object
821      * represents an interface, this method returns {@code true} if the
822      * class or any superclass of the specified {@code Object} argument
823      * implements this interface; it returns {@code false} otherwise. If
824      * this {@code Class} object represents a primitive type, this method
825      * returns {@code false}.
826      *
827      * @param   obj the object to check
828      * @return  true if {@code obj} is an instance of this class
829      *
830      * @since 1.1
831      */
832     @IntrinsicCandidate
833     // Android-changed: JNI code can be replaced by simple java code.
834     // public native boolean isInstance(Object obj);
isInstance(Object obj)835     public boolean isInstance(Object obj) {
836         if (obj == null) {
837             return false;
838         }
839         return isAssignableFrom(obj.getClass());
840     }
841 
842 
843     /**
844      * Determines if the class or interface represented by this
845      * {@code Class} object is either the same as, or is a superclass or
846      * superinterface of, the class or interface represented by the specified
847      * {@code Class} parameter. It returns {@code true} if so;
848      * otherwise it returns {@code false}. If this {@code Class}
849      * object represents a primitive type, this method returns
850      * {@code true} if the specified {@code Class} parameter is
851      * exactly this {@code Class} object; otherwise it returns
852      * {@code false}.
853      *
854      * <p> Specifically, this method tests whether the type represented by the
855      * specified {@code Class} parameter can be converted to the type
856      * represented by this {@code Class} object via an identity conversion
857      * or via a widening reference conversion. See <cite>The Java Language
858      * Specification</cite>, sections {@jls 5.1.1} and {@jls 5.1.4},
859      * for details.
860      *
861      * @param     cls the {@code Class} object to be checked
862      * @return    the {@code boolean} value indicating whether objects of the
863      *            type {@code cls} can be assigned to objects of this class
864      * @throws    NullPointerException if the specified Class parameter is
865      *            null.
866      * @since     1.1
867      */
868     @IntrinsicCandidate
869     // Android-changed: JNI code can be replaced by simple java code.
870     // public native boolean isAssignableFrom(Class<?> cls);
isAssignableFrom(Class<?> cls)871     public boolean isAssignableFrom(Class<?> cls) {
872         if (this == cls) {
873             return true;  // Can always assign to things of the same type.
874         } else if (this == Object.class) {
875             return !cls.isPrimitive();  // Can assign any reference to java.lang.Object.
876         } else if (isArray()) {
877             return cls.isArray() && componentType.isAssignableFrom(cls.componentType);
878         } else if (isInterface()) {
879             // Search iftable which has a flattened and uniqued list of interfaces.
880             Object[] iftable = cls.ifTable;
881             if (iftable != null) {
882                 for (int i = 0; i < iftable.length; i += 2) {
883                     if (iftable[i] == this) {
884                         return true;
885                     }
886                 }
887             }
888             return false;
889         } else {
890             if (!cls.isInterface()) {
891                 for (cls = cls.superClass; cls != null; cls = cls.superClass) {
892                     if (cls == this) {
893                         return true;
894                     }
895                 }
896             }
897             return false;
898         }
899     }
900 
901     /**
902      * Determines if this {@code Class} object represents an
903      * interface type.
904      *
905      * @return  {@code true} if this {@code Class} object represents an interface;
906      *          {@code false} otherwise.
907      */
908     @IntrinsicCandidate
909     // Android-changed: JNI code can be replaced by simple java code.
910     // public native boolean isInterface();
isInterface()911     public boolean isInterface() {
912         return (accessFlags & Modifier.INTERFACE) != 0;
913     }
914 
915     /**
916      * Determines if this {@code Class} object represents an array class.
917      *
918      * @return  {@code true} if this {@code Class} object represents an array class;
919      *          {@code false} otherwise.
920      * @since   1.1
921      */
922     @IntrinsicCandidate
923     // Android-changed: JNI code can be replaced by simple java code.
924     // public native boolean isArray();
isArray()925     public boolean isArray() {
926         return getComponentType() != null;
927     }
928 
929     /**
930      * Determines if the specified {@code Class} object represents a
931      * primitive type.
932      *
933      * <p> There are nine predefined {@code Class} objects to represent
934      * the eight primitive types and void.  These are created by the Java
935      * Virtual Machine, and have the same names as the primitive types that
936      * they represent, namely {@code boolean}, {@code byte},
937      * {@code char}, {@code short}, {@code int},
938      * {@code long}, {@code float}, and {@code double}.
939      *
940      * <p> These objects may only be accessed via the following public static
941      * final variables, and are the only {@code Class} objects for which
942      * this method returns {@code true}.
943      *
944      * @return true if and only if this class represents a primitive type
945      *
946      * @see     java.lang.Boolean#TYPE
947      * @see     java.lang.Character#TYPE
948      * @see     java.lang.Byte#TYPE
949      * @see     java.lang.Short#TYPE
950      * @see     java.lang.Integer#TYPE
951      * @see     java.lang.Long#TYPE
952      * @see     java.lang.Float#TYPE
953      * @see     java.lang.Double#TYPE
954      * @see     java.lang.Void#TYPE
955      * @since 1.1
956      */
957     @IntrinsicCandidate
958     // Android-changed: JNI code can be replaced by simple java code.
959     // public native boolean isPrimitive();
isPrimitive()960     public boolean isPrimitive() {
961       return (primitiveType & 0xFFFF) != 0;
962     }
963 
964     /**
965      * Indicates whether this {@code Class} or its parents override finalize.
966      *
967      * @return {@code true} if and if this class or its parents override
968      *         finalize;
969      *
970      * @hide
971      */
isFinalizable()972     public boolean isFinalizable() {
973         return (getModifiers() & FINALIZABLE) != 0;
974     }
975 
976     /**
977      * Returns true if this {@code Class} object represents an annotation
978      * interface.  Note that if this method returns true, {@link #isInterface()}
979      * would also return true, as all annotation interfaces are also interfaces.
980      *
981      * @return {@code true} if this {@code Class} object represents an annotation
982      *      interface; {@code false} otherwise
983      * @since 1.5
984      */
isAnnotation()985     public boolean isAnnotation() {
986         return (getModifiers() & ANNOTATION) != 0;
987     }
988 
989     /**
990      *{@return {@code true} if and only if this class has the synthetic modifier
991      * bit set}
992      *
993      * @jls 13.1 The Form of a Binary
994      * @jvms 4.1 The {@code ClassFile} Structure
995      * @see <a
996      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
997      * programming language and JVM modeling in core reflection</a>
998      * @since 1.5
999      */
isSynthetic()1000     public boolean isSynthetic() {
1001         return (getModifiers() & SYNTHETIC) != 0;
1002     }
1003 
1004     // Android-changed: Removed javadoc related to hidden classes.
1005     /**
1006      * Returns the  name of the entity (class, interface, array class,
1007      * primitive type, or void) represented by this {@code Class} object.
1008      *
1009      * <p> If this {@code Class} object represents a class or interface,
1010      * not an array class, then:
1011      *
1012      * <p> If this {@code Class} object represents an array class, then
1013      * the result is a string consisting of one or more '{@code [}' characters
1014      * representing the depth of the array nesting, followed by the element
1015      * type as encoded using the following table:
1016      *
1017      * <blockquote><table class="striped">
1018      * <caption style="display:none">Element types and encodings</caption>
1019      * <thead>
1020      * <tr><th scope="col"> Element Type <th scope="col"> Encoding
1021      * </thead>
1022      * <tbody style="text-align:left">
1023      * <tr><th scope="row"> {@code boolean} <td style="text-align:center"> {@code Z}
1024      * <tr><th scope="row"> {@code byte}    <td style="text-align:center"> {@code B}
1025      * <tr><th scope="row"> {@code char}    <td style="text-align:center"> {@code C}
1026      * <tr><th scope="row"> class or interface with <a href="ClassLoader.html#binary-name">binary name</a> <i>N</i>
1027      *                                      <td style="text-align:center"> {@code L}<em>N</em>{@code ;}
1028      * <tr><th scope="row"> {@code double}  <td style="text-align:center"> {@code D}
1029      * <tr><th scope="row"> {@code float}   <td style="text-align:center"> {@code F}
1030      * <tr><th scope="row"> {@code int}     <td style="text-align:center"> {@code I}
1031      * <tr><th scope="row"> {@code long}    <td style="text-align:center"> {@code J}
1032      * <tr><th scope="row"> {@code short}   <td style="text-align:center"> {@code S}
1033      * </tbody>
1034      * </table></blockquote>
1035      *
1036      * <p> If this {@code Class} object represents a primitive type or {@code void},
1037      * then the result is a string with the same spelling as the Java language
1038      * keyword which corresponds to the primitive type or {@code void}.
1039      *
1040      * <p> Examples:
1041      * <blockquote><pre>
1042      * String.class.getName()
1043      *     returns "java.lang.String"
1044      * byte.class.getName()
1045      *     returns "byte"
1046      * (new Object[3]).getClass().getName()
1047      *     returns "[Ljava.lang.Object;"
1048      * (new int[3][4][5][6][7][8][9]).getClass().getName()
1049      *     returns "[[[[[[[I"
1050      * </pre></blockquote>
1051      *
1052      * @return  the name of the class, interface, or other entity
1053      *          represented by this {@code Class} object.
1054      * @jls 13.1 The Form of a Binary
1055      */
getName()1056     public String getName() {
1057         String name = this.name;
1058         // Android-changed: ART has a different JNI layer.
1059         // return name != null ? name : initClassName();
1060         if (name == null)
1061             this.name = name = getNameNative();
1062         return name;
1063 
1064     }
1065 
1066     // Android-changed: ART has a different JNI layer.
1067     // private native String initClassName();
1068     @FastNative
getNameNative()1069     private native String getNameNative();
1070 
1071     // Android-changed: Remove SecurityException javadoc.
1072     /**
1073      * Returns the class loader for the class.  Some implementations may use
1074      * null to represent the bootstrap class loader. This method will return
1075      * null in such implementations if this class was loaded by the bootstrap
1076      * class loader.
1077      *
1078      * <p>If this {@code Class} object
1079      * represents a primitive type or void, null is returned.
1080      *
1081      * @return  the class loader that loaded the class or interface
1082      *          represented by this {@code Class} object.
1083      * @see java.lang.ClassLoader
1084      * @see SecurityManager#checkPermission
1085      * @see java.lang.RuntimePermission
1086      */
1087     // Android-changed: Remove unused annotation.
1088     // @CallerSensitive
1089     // @ForceInline // to ensure Reflection.getCallerClass optimization
getClassLoader()1090     public ClassLoader getClassLoader() {
1091         if (isPrimitive()) {
1092             return null;
1093         }
1094         // Android-note: The RI returns null in the case where Android returns BootClassLoader.
1095         // Noted in http://b/111850480#comment3
1096         return (classLoader == null) ? BootClassLoader.getInstance() : classLoader;
1097     }
1098 
1099     // Android-removed: Remove unsupported getModule().
1100     /*
1101      * Returns the module that this class or interface is a member of.
1102      *
1103      * If this class represents an array type then this method returns the
1104      * {@code Module} for the element type. If this class represents a
1105      * primitive type or void, then the {@code Module} object for the
1106      * {@code java.base} module is returned.
1107      *
1108      * If this class is in an unnamed module then the {@linkplain
1109      * ClassLoader#getUnnamedModule() unnamed} {@code Module} of the class
1110      * loader for this class is returned.
1111      *
1112      * @return the module that this class or interface is a member of
1113      *
1114      * @since 9
1115      * @spec JPMS
1116      *
1117     public Module getModule() {
1118         return module;
1119     }
1120 
1121     // set by VM
1122     private transient Module module;
1123 
1124     // Set by VM
1125     private transient Object classData;
1126 
1127     // package-private
1128     Object getClassData() {
1129         return classData;
1130     }
1131     */
1132 
1133     /**
1134      * Returns an array of {@code TypeVariable} objects that represent the
1135      * type variables declared by the generic declaration represented by this
1136      * {@code GenericDeclaration} object, in declaration order.  Returns an
1137      * array of length 0 if the underlying generic declaration declares no type
1138      * variables.
1139      *
1140      * @return an array of {@code TypeVariable} objects that represent
1141      *     the type variables declared by this generic declaration
1142      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
1143      *     signature of this generic declaration does not conform to
1144      *     the format specified in section {@jvms 4.7.9} of
1145      *     <cite>The Java Virtual Machine Specification</cite>
1146      * @since 1.5
1147      */
1148     @Override
getTypeParameters()1149     public synchronized TypeVariable<Class<T>>[] getTypeParameters() {
1150         String annotationSignature = getSignatureAttribute();
1151         if (annotationSignature == null) {
1152             return EmptyArray.TYPE_VARIABLE;
1153         }
1154         GenericSignatureParser parser = new GenericSignatureParser(getClassLoader());
1155         parser.parseForClass(this, annotationSignature);
1156         return parser.formalTypeParameters;
1157     }
1158 
1159 
1160     /**
1161      * Returns the {@code Class} representing the direct superclass of the
1162      * entity (class, interface, primitive type or void) represented by
1163      * this {@code Class}.  If this {@code Class} represents either the
1164      * {@code Object} class, an interface, a primitive type, or void, then
1165      * null is returned.  If this {@code Class} object represents an array class
1166      * then the {@code Class} object representing the {@code Object} class is
1167      * returned.
1168      *
1169      * @return the direct superclass of the class represented by this {@code Class} object
1170      */
1171     @IntrinsicCandidate
1172     // Android-changed: ART has a different JNI layer.
1173     // public native Class<? super T> getSuperclass();
getSuperclass()1174     public Class<? super T> getSuperclass() {
1175         // For interfaces superClass is Object (which agrees with the JNI spec)
1176         // but not with the expected behavior here.
1177         if (isInterface()) {
1178             return null;
1179         } else {
1180             return superClass;
1181         }
1182     }
1183 
1184     /**
1185      * Returns the {@code Type} representing the direct superclass of
1186      * the entity (class, interface, primitive type or void) represented by
1187      * this {@code Class} object.
1188      *
1189      * <p>If the superclass is a parameterized type, the {@code Type}
1190      * object returned must accurately reflect the actual type
1191      * arguments used in the source code. The parameterized type
1192      * representing the superclass is created if it had not been
1193      * created before. See the declaration of {@link
1194      * java.lang.reflect.ParameterizedType ParameterizedType} for the
1195      * semantics of the creation process for parameterized types.  If
1196      * this {@code Class} object represents either the {@code Object}
1197      * class, an interface, a primitive type, or void, then null is
1198      * returned.  If this {@code Class} object represents an array class
1199      * then the {@code Class} object representing the {@code Object} class is
1200      * returned.
1201      *
1202      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
1203      *     class signature does not conform to the format specified in
1204      *     section {@jvms 4.7.9} of <cite>The Java Virtual
1205      *     Machine Specification</cite>
1206      * @throws TypeNotPresentException if the generic superclass
1207      *     refers to a non-existent type declaration
1208      * @throws java.lang.reflect.MalformedParameterizedTypeException if the
1209      *     generic superclass refers to a parameterized type that cannot be
1210      *     instantiated  for any reason
1211      * @return the direct superclass of the class represented by this {@code Class} object
1212      * @since 1.5
1213      */
getGenericSuperclass()1214     public Type getGenericSuperclass() {
1215         Type genericSuperclass = getSuperclass();
1216         // This method is specified to return null for all cases where getSuperclass
1217         // returns null, i.e, for primitives, interfaces, void and java.lang.Object.
1218         if (genericSuperclass == null) {
1219             return null;
1220         }
1221 
1222         String annotationSignature = getSignatureAttribute();
1223         if (annotationSignature != null) {
1224             GenericSignatureParser parser = new GenericSignatureParser(getClassLoader());
1225             parser.parseForClass(this, annotationSignature);
1226             genericSuperclass = parser.superclassType;
1227         }
1228         return Types.getType(genericSuperclass);
1229     }
1230 
1231     /**
1232      * Gets the package of this class.
1233      *
1234      * <p>If this class represents an array type, a primitive type or void,
1235      * this method returns {@code null}.
1236      *
1237      * @return the package of this class.
1238      * @revised 9
1239      */
getPackage()1240     public Package getPackage() {
1241         // Android-changed: ART has a different JNI layer.
1242         /*
1243         if (isPrimitive() || isArray()) {
1244             return null;
1245         }
1246         ClassLoader cl = getClassLoader0();
1247         return cl != null ? cl.definePackage(this)
1248             : BootLoader.definePackage(this);
1249         */
1250         ClassLoader loader = getClassLoader();
1251         if (loader != null) {
1252             String packageName = getPackageName();
1253             return packageName != null ? loader.getPackage(packageName) : null;
1254         }
1255         return null;
1256     }
1257 
1258     /**
1259      * Returns the fully qualified package name.
1260      *
1261      * <p> If this class is a top level class, then this method returns the fully
1262      * qualified name of the package that the class is a member of, or the
1263      * empty string if the class is in an unnamed package.
1264      *
1265      * <p> If this class is a member class, then this method is equivalent to
1266      * invoking {@code getPackageName()} on the {@linkplain #getEnclosingClass
1267      * enclosing class}.
1268      *
1269      * <p> If this class is a {@linkplain #isLocalClass local class} or an {@linkplain
1270      * #isAnonymousClass() anonymous class}, then this method is equivalent to
1271      * invoking {@code getPackageName()} on the {@linkplain #getDeclaringClass
1272      * declaring class} of the {@linkplain #getEnclosingMethod enclosing method} or
1273      * {@linkplain #getEnclosingConstructor enclosing constructor}.
1274      *
1275      * <p> If this class represents an array type then this method returns the
1276      * package name of the element type. If this class represents a primitive
1277      * type or void then the package name "{@code java.lang}" is returned.
1278      *
1279      * @return the fully qualified package name
1280      *
1281      * @since 9
1282      * @jls 6.7 Fully Qualified Names
1283      */
getPackageName()1284     public String getPackageName() {
1285         // BEGIN Android-changed: Don't use a private field as a cache.
1286         /*
1287         String pn = this.packageName;
1288         if (pn == null) {
1289             Class<?> c = isArray() ? elementType() : this;
1290             if (c.isPrimitive()) {
1291                 pn = "java.lang";
1292             } else {
1293                 String cn = c.getName();
1294                 int dot = cn.lastIndexOf('.');
1295                 pn = (dot != -1) ? cn.substring(0, dot).intern() : "";
1296             }
1297             this.packageName = pn;
1298         }
1299         return pn;
1300         */
1301             Class<?> c = this;
1302             while (c.isArray()) {
1303                 c = c.getComponentType();
1304             }
1305             if (c.isPrimitive()) {
1306                 return "java.lang";
1307             } else {
1308                 String cn = c.getName();
1309                 int dot = cn.lastIndexOf('.');
1310                 return (dot != -1) ? cn.substring(0, dot).intern() : "";
1311             }
1312         // END Android-changed: Don't use a private field as a cache.
1313     }
1314 
1315     // cached package name
1316     // Android-removed: Don't use a private field as a cache.
1317     // private transient String packageName;
1318 
1319     /**
1320      * Returns the interfaces directly implemented by the class or interface
1321      * represented by this {@code Class} object.
1322      *
1323      * <p>If this {@code Class} object represents a class, the return value is an array
1324      * containing objects representing all interfaces directly implemented by
1325      * the class.  The order of the interface objects in the array corresponds
1326      * to the order of the interface names in the {@code implements} clause of
1327      * the declaration of the class represented by this {@code Class} object.  For example,
1328      * given the declaration:
1329      * <blockquote>
1330      * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
1331      * </blockquote>
1332      * suppose the value of {@code s} is an instance of
1333      * {@code Shimmer}; the value of the expression:
1334      * <blockquote>
1335      * {@code s.getClass().getInterfaces()[0]}
1336      * </blockquote>
1337      * is the {@code Class} object that represents interface
1338      * {@code FloorWax}; and the value of:
1339      * <blockquote>
1340      * {@code s.getClass().getInterfaces()[1]}
1341      * </blockquote>
1342      * is the {@code Class} object that represents interface
1343      * {@code DessertTopping}.
1344      *
1345      * <p>If this {@code Class} object represents an interface, the array contains objects
1346      * representing all interfaces directly extended by the interface.  The
1347      * order of the interface objects in the array corresponds to the order of
1348      * the interface names in the {@code extends} clause of the declaration of
1349      * the interface represented by this {@code Class} object.
1350      *
1351      * <p>If this {@code Class} object represents a class or interface that implements no
1352      * interfaces, the method returns an array of length 0.
1353      *
1354      * <p>If this {@code Class} object represents a primitive type or void, the method
1355      * returns an array of length 0.
1356      *
1357      * <p>If this {@code Class} object represents an array type, the
1358      * interfaces {@code Cloneable} and {@code java.io.Serializable} are
1359      * returned in that order.
1360      *
1361      * @return an array of interfaces directly implemented by this class
1362      */
getInterfaces()1363     public Class<?>[] getInterfaces() {
1364         // Android-changed: ART has a different implenmentation.
1365         // return getInterfaces(true);
1366         if (isArray()) {
1367             return new Class<?>[] { Cloneable.class, Serializable.class };
1368         }
1369 
1370         final Class<?>[] ifaces = getInterfacesInternal();
1371         if (ifaces == null) {
1372             return EmptyArray.CLASS;
1373         }
1374 
1375         return ifaces;
1376     }
1377 
1378     // Android-revmoed: Remove unused getInterfaces(boolean) method.
1379     /*
1380     private Class<?>[] getInterfaces(boolean cloneArray) {
1381         ReflectionData<T> rd = reflectionData();
1382         if (rd == null) {
1383             // no cloning required
1384             return getInterfaces0();
1385         } else {
1386             Class<?>[] interfaces = rd.interfaces;
1387             if (interfaces == null) {
1388                 interfaces = getInterfaces0();
1389                 rd.interfaces = interfaces;
1390             }
1391             // defensively copy if requested
1392             return cloneArray ? interfaces.clone() : interfaces;
1393         }
1394     }
1395     */
1396 
1397     @FastNative
getInterfacesInternal()1398     private native Class<?>[] getInterfacesInternal();
1399 
1400 
1401     /**
1402      * Returns the {@code Type}s representing the interfaces
1403      * directly implemented by the class or interface represented by
1404      * this {@code Class} object.
1405      *
1406      * <p>If a superinterface is a parameterized type, the
1407      * {@code Type} object returned for it must accurately reflect
1408      * the actual type arguments used in the source code. The
1409      * parameterized type representing each superinterface is created
1410      * if it had not been created before. See the declaration of
1411      * {@link java.lang.reflect.ParameterizedType ParameterizedType}
1412      * for the semantics of the creation process for parameterized
1413      * types.
1414      *
1415      * <p>If this {@code Class} object represents a class, the return value is an array
1416      * containing objects representing all interfaces directly implemented by
1417      * the class.  The order of the interface objects in the array corresponds
1418      * to the order of the interface names in the {@code implements} clause of
1419      * the declaration of the class represented by this {@code Class} object.
1420      *
1421      * <p>If this {@code Class} object represents an interface, the array contains objects
1422      * representing all interfaces directly extended by the interface.  The
1423      * order of the interface objects in the array corresponds to the order of
1424      * the interface names in the {@code extends} clause of the declaration of
1425      * the interface represented by this {@code Class} object.
1426      *
1427      * <p>If this {@code Class} object represents a class or interface that implements no
1428      * interfaces, the method returns an array of length 0.
1429      *
1430      * <p>If this {@code Class} object represents a primitive type or void, the method
1431      * returns an array of length 0.
1432      *
1433      * <p>If this {@code Class} object represents an array type, the
1434      * interfaces {@code Cloneable} and {@code java.io.Serializable} are
1435      * returned in that order.
1436      *
1437      * @throws java.lang.reflect.GenericSignatureFormatError
1438      *     if the generic class signature does not conform to the
1439      *     format specified in section {@jvms 4.7.9} of <cite>The
1440      *     Java Virtual Machine Specification</cite>
1441      * @throws TypeNotPresentException if any of the generic
1442      *     superinterfaces refers to a non-existent type declaration
1443      * @throws java.lang.reflect.MalformedParameterizedTypeException
1444      *     if any of the generic superinterfaces refer to a parameterized
1445      *     type that cannot be instantiated for any reason
1446      * @return an array of interfaces directly implemented by this class
1447      * @since 1.5
1448      */
getGenericInterfaces()1449     public Type[] getGenericInterfaces() {
1450         Type[] result;
1451         synchronized (Caches.genericInterfaces) {
1452             result = Caches.genericInterfaces.get(this);
1453             if (result == null) {
1454                 String annotationSignature = getSignatureAttribute();
1455                 if (annotationSignature == null) {
1456                     result = getInterfaces();
1457                 } else {
1458                     GenericSignatureParser parser = new GenericSignatureParser(getClassLoader());
1459                     parser.parseForClass(this, annotationSignature);
1460                     result = Types.getTypeArray(parser.interfaceTypes, false);
1461                 }
1462                 Caches.genericInterfaces.put(this, result);
1463             }
1464         }
1465         return (result.length == 0) ? result : result.clone();
1466     }
1467 
1468 
1469     /**
1470      * Returns the {@code Class} representing the component type of an
1471      * array.  If this class does not represent an array class this method
1472      * returns null.
1473      *
1474      * @return the {@code Class} representing the component type of this
1475      * class if this class is an array
1476      * @see     java.lang.reflect.Array
1477      * @since 1.1
1478      */
getComponentType()1479     public Class<?> getComponentType() {
1480         // Android-changed: Android can return componentType field directly.
1481         /*
1482         if (isArray()) {
1483             return componentType;
1484         } else {
1485             return null;
1486         }
1487         */
1488       return componentType;
1489     }
1490 
1491     /*
1492      * Returns the {@code Class} representing the element type of an array class.
1493      * If this class does not represent an array class, then this method returns
1494      * {@code null}.
1495      */
elementType()1496     private Class<?> elementType() {
1497         if (!isArray()) return null;
1498 
1499         Class<?> c = this;
1500         while (c.isArray()) {
1501             c = c.getComponentType();
1502         }
1503         return c;
1504     }
1505 
1506     /**
1507      * Returns the Java language modifiers for this class or interface, encoded
1508      * in an integer. The modifiers consist of the Java Virtual Machine's
1509      * constants for {@code public}, {@code protected},
1510      * {@code private}, {@code final}, {@code static},
1511      * {@code abstract} and {@code interface}; they should be decoded
1512      * using the methods of class {@code Modifier}.
1513      *
1514      * <p> If the underlying class is an array class, then its
1515      * {@code public}, {@code private} and {@code protected}
1516      * modifiers are the same as those of its component type.  If this
1517      * {@code Class} object represents a primitive type or void, its
1518      * {@code public} modifier is always {@code true}, and its
1519      * {@code protected} and {@code private} modifiers are always
1520      * {@code false}. If this {@code Class} object represents an array class, a
1521      * primitive type or void, then its {@code final} modifier is always
1522      * {@code true} and its interface modifier is always
1523      * {@code false}. The values of its other modifiers are not determined
1524      * by this specification.
1525      *
1526      * <p> The modifier encodings are defined in section {@jvms 4.1}
1527      * of <cite>The Java Virtual Machine Specification</cite>.
1528      *
1529      * @return the {@code int} representing the modifiers for this class
1530      * @see     java.lang.reflect.Modifier
1531      * @see <a
1532      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1533      * programming language and JVM modeling in core reflection</a>
1534      * @since 1.1
1535      * @jls 8.1.1 Class Modifiers
1536      * @jls 9.1.1. Interface Modifiers
1537      */
1538     @IntrinsicCandidate
1539     // Android-changed: Android can use a simple java implementation.
1540     // public native int getModifiers();
getModifiers()1541     public int getModifiers() {
1542         // Array classes inherit modifiers from their component types, but in the case of arrays
1543         // of an inner class, the class file may contain "fake" access flags because it's not valid
1544         // for a top-level class to private, say. The real access flags are stored in the InnerClass
1545         // attribute, so we need to make sure we drill down to the inner class: the accessFlags
1546         // field is not the value we want to return, and the synthesized array class does not itself
1547         // have an InnerClass attribute. https://code.google.com/p/android/issues/detail?id=56267
1548         if (isArray()) {
1549             int componentModifiers = getComponentType().getModifiers();
1550             if ((componentModifiers & Modifier.INTERFACE) != 0) {
1551                 componentModifiers &= ~(Modifier.INTERFACE | Modifier.STATIC);
1552             }
1553             return Modifier.ABSTRACT | Modifier.FINAL | componentModifiers;
1554         }
1555         int JAVA_FLAGS_MASK = 0xffff;
1556         int modifiers = this.getInnerClassFlags(accessFlags & JAVA_FLAGS_MASK);
1557         return modifiers & JAVA_FLAGS_MASK;
1558     }
1559 
1560     /**
1561      * Gets the signers of this class.
1562      *
1563      * @return  the signers of this class, or null if there are no signers.  In
1564      *          particular, this method returns null if this {@code Class} object represents
1565      *          a primitive type or void.
1566      * @since   1.1
1567      */
getSigners()1568     public Object[] getSigners() {
1569         return null;
1570     }
1571 
1572     @FastNative
getEnclosingMethodNative()1573     private native Method getEnclosingMethodNative();
1574 
1575     /**
1576      * If this {@code Class} object represents a local or anonymous
1577      * class within a method, returns a {@link
1578      * java.lang.reflect.Method Method} object representing the
1579      * immediately enclosing method of the underlying class. Returns
1580      * {@code null} otherwise.
1581      *
1582      * In particular, this method returns {@code null} if the underlying
1583      * class is a local or anonymous class immediately enclosed by a class or
1584      * interface declaration, instance initializer or static initializer.
1585      *
1586      * @return the immediately enclosing method of the underlying class, if
1587      *     that class is a local or anonymous class; otherwise {@code null}.
1588      * @since 1.5
1589      */
1590     // Android-changed: Removed SecurityException.
getEnclosingMethod()1591     public Method getEnclosingMethod() {
1592         if (classNameImpliesTopLevel()) {
1593             return null;
1594         }
1595         /*
1596         else {
1597             if (!enclosingInfo.isMethod())
1598                 return null;
1599 
1600             MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
1601                                                               getFactory());
1602             Class<?>   returnType       = toClass(typeInfo.getReturnType());
1603             Type []    parameterTypes   = typeInfo.getParameterTypes();
1604             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1605 
1606             // Convert Types to Classes; returned types *should*
1607             // be class objects since the methodDescriptor's used
1608             // don't have generics information
1609             for(int i = 0; i < parameterClasses.length; i++)
1610                 parameterClasses[i] = toClass(parameterTypes[i]);
1611 
1612             // Perform access check
1613             final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1614             @SuppressWarnings("removal")
1615             SecurityManager sm = System.getSecurityManager();
1616             if (sm != null) {
1617                 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED,
1618                                                      Reflection.getCallerClass(), true);
1619             }
1620             Method[] candidates = enclosingCandidate.privateGetDeclaredMethods(false);
1621 
1622             /*
1623              * Loop over all declared methods; match method name,
1624              * number of and type of parameters, *and* return
1625              * type.  Matching return type is also necessary
1626              * because of covariant returns, etc.
1627              *
1628             ReflectionFactory fact = getReflectionFactory();
1629             for (Method m : candidates) {
1630                 if (m.getName().equals(enclosingInfo.getName()) &&
1631                     arrayContentsEq(parameterClasses,
1632                                     fact.getExecutableSharedParameterTypes(m))) {
1633                     // finally, check return type
1634                     if (m.getReturnType().equals(returnType)) {
1635                         return fact.copyMethod(m);
1636                     }
1637                 }
1638             }
1639 
1640             throw new InternalError("Enclosing method not found");
1641         }
1642         */
1643         return getEnclosingMethodNative();
1644     }
1645 
1646     // Android-removed: Remove unused getEnclosingMethodInfo().
1647     /*
1648     private native Object[] getEnclosingMethod0();
1649 
1650     private EnclosingMethodInfo getEnclosingMethodInfo() {
1651         Object[] enclosingInfo = getEnclosingMethod0();
1652         if (enclosingInfo == null)
1653             return null;
1654         else {
1655             return new EnclosingMethodInfo(enclosingInfo);
1656         }
1657     }
1658 
1659     private static final class EnclosingMethodInfo {
1660         private final Class<?> enclosingClass;
1661         private final String name;
1662         private final String descriptor;
1663 
1664         static void validate(Object[] enclosingInfo) {
1665             if (enclosingInfo.length != 3)
1666                 throw new InternalError("Malformed enclosing method information");
1667             try {
1668                 // The array is expected to have three elements:
1669 
1670                 // the immediately enclosing class
1671                 Class<?> enclosingClass = (Class<?>)enclosingInfo[0];
1672                 assert(enclosingClass != null);
1673 
1674                 // the immediately enclosing method or constructor's
1675                 // name (can be null).
1676                 String name = (String)enclosingInfo[1];
1677 
1678                 // the immediately enclosing method or constructor's
1679                 // descriptor (null iff name is).
1680                 String descriptor = (String)enclosingInfo[2];
1681                 assert((name != null && descriptor != null) || name == descriptor);
1682             } catch (ClassCastException cce) {
1683                 throw new InternalError("Invalid type in enclosing method information", cce);
1684             }
1685         }
1686 
1687         EnclosingMethodInfo(Object[] enclosingInfo) {
1688             validate(enclosingInfo);
1689             this.enclosingClass = (Class<?>)enclosingInfo[0];
1690             this.name = (String)enclosingInfo[1];
1691             this.descriptor = (String)enclosingInfo[2];
1692         }
1693 
1694         boolean isPartial() {
1695             return enclosingClass == null || name == null || descriptor == null;
1696         }
1697 
1698         boolean isConstructor() { return !isPartial() && "<init>".equals(name); }
1699 
1700         boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }
1701 
1702         Class<?> getEnclosingClass() { return enclosingClass; }
1703 
1704         String getName() { return name; }
1705 
1706         String getDescriptor() { return descriptor; }
1707 
1708     }
1709 
1710     private static Class<?> toClass(Type o) {
1711         if (o instanceof GenericArrayType)
1712             return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
1713                                      0)
1714                 .getClass();
1715         return (Class<?>)o;
1716      }
1717     */
1718 
1719     /**
1720      * If this {@code Class} object represents a local or anonymous
1721      * class within a constructor, returns a {@link
1722      * java.lang.reflect.Constructor Constructor} object representing
1723      * the immediately enclosing constructor of the underlying
1724      * class. Returns {@code null} otherwise.  In particular, this
1725      * method returns {@code null} if the underlying class is a local
1726      * or anonymous class immediately enclosed by a class or
1727      * interface declaration, instance initializer or static initializer.
1728      *
1729      * @return the immediately enclosing constructor of the underlying class, if
1730      *     that class is a local or anonymous class; otherwise {@code null}.
1731      * @since 1.5
1732      */
1733     // Android-changed: Removed SecurityException.
getEnclosingConstructor()1734     public Constructor<?> getEnclosingConstructor() {
1735         if (classNameImpliesTopLevel()) {
1736             return null;
1737         }
1738         /*
1739         else {
1740             if (!enclosingInfo.isConstructor())
1741                 return null;
1742 
1743             ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
1744                                                                         getFactory());
1745             Type []    parameterTypes   = typeInfo.getParameterTypes();
1746             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1747 
1748             // Convert Types to Classes; returned types *should*
1749             // be class objects since the methodDescriptor's used
1750             // don't have generics information
1751             for(int i = 0; i < parameterClasses.length; i++)
1752                 parameterClasses[i] = toClass(parameterTypes[i]);
1753 
1754             // Perform access check
1755             final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1756             @SuppressWarnings("removal")
1757             SecurityManager sm = System.getSecurityManager();
1758             if (sm != null) {
1759                 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED,
1760                                                      Reflection.getCallerClass(), true);
1761             }
1762 
1763             Constructor<?>[] candidates = enclosingCandidate
1764                     .privateGetDeclaredConstructors(false);
1765             /*
1766              * Loop over all declared constructors; match number
1767              * of and type of parameters.
1768              *
1769             ReflectionFactory fact = getReflectionFactory();
1770             for (Constructor<?> c : candidates) {
1771                 if (arrayContentsEq(parameterClasses,
1772                                     fact.getExecutableSharedParameterTypes(c))) {
1773                     return fact.copyConstructor(c);
1774                 }
1775             }
1776 
1777             throw new InternalError("Enclosing constructor not found");
1778 
1779         }
1780         */
1781         return getEnclosingConstructorNative();
1782     }
1783 
1784     @FastNative
getEnclosingConstructorNative()1785     private native Constructor<?> getEnclosingConstructorNative();
1786 
classNameImpliesTopLevel()1787     private boolean classNameImpliesTopLevel() {
1788         return !getName().contains("$");
1789     }
1790 
1791 
1792     /**
1793      * If the class or interface represented by this {@code Class} object
1794      * is a member of another class, returns the {@code Class} object
1795      * representing the class in which it was declared.  This method returns
1796      * null if this class or interface is not a member of any other class.  If
1797      * this {@code Class} object represents an array class, a primitive
1798      * type, or void,then this method returns null.
1799      *
1800      * @return the declaring class for this class
1801      * @since 1.1
1802      */
1803     // Android-changed: Removed SecurityException.
1804     /*
1805     @CallerSensitive
1806     public Class<?> getDeclaringClass() throws SecurityException {
1807         final Class<?> candidate = getDeclaringClass0();
1808 
1809         if (candidate != null) {
1810             @SuppressWarnings("removal")
1811             SecurityManager sm = System.getSecurityManager();
1812             if (sm != null) {
1813                 candidate.checkPackageAccess(sm,
1814                     ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
1815             }
1816         }
1817         return candidate;
1818     }
1819 
1820     private native Class<?> getDeclaringClass0();
1821     */
1822     @FastNative
getDeclaringClass()1823     public native Class<?> getDeclaringClass();
1824 
1825     /**
1826      * Returns the immediately enclosing class of the underlying
1827      * class.  If the underlying class is a top level class this
1828      * method returns {@code null}.
1829      * @return the immediately enclosing class of the underlying class
1830      * @since 1.5
1831      */
1832     // Android-changed: Removed SecurityException.
1833     /*
1834     @CallerSensitive
1835     public Class<?> getEnclosingClass() throws SecurityException {
1836         // There are five kinds of classes (or interfaces):
1837         // a) Top level classes
1838         // b) Nested classes (static member classes)
1839         // c) Inner classes (non-static member classes)
1840         // d) Local classes (named classes declared within a method)
1841         // e) Anonymous classes
1842 
1843 
1844         // JVM Spec 4.7.7: A class must have an EnclosingMethod
1845         // attribute if and only if it is a local class or an
1846         // anonymous class.
1847         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1848         Class<?> enclosingCandidate;
1849 
1850         if (enclosingInfo == null) {
1851             // This is a top level or a nested class or an inner class (a, b, or c)
1852             enclosingCandidate = getDeclaringClass0();
1853         } else {
1854             Class<?> enclosingClass = enclosingInfo.getEnclosingClass();
1855             // This is a local class or an anonymous class (d or e)
1856             if (enclosingClass == this || enclosingClass == null)
1857                 throw new InternalError("Malformed enclosing method information");
1858             else
1859                 enclosingCandidate = enclosingClass;
1860         }
1861 
1862         if (enclosingCandidate != null) {
1863             @SuppressWarnings("removal")
1864             SecurityManager sm = System.getSecurityManager();
1865             if (sm != null) {
1866                 enclosingCandidate.checkPackageAccess(sm,
1867                     ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
1868             }
1869         }
1870         return enclosingCandidate;
1871     }
1872     */
1873     @FastNative
getEnclosingClass()1874     public native Class<?> getEnclosingClass();
1875 
1876     /**
1877      * Returns the simple name of the underlying class as given in the
1878      * source code. An empty string is returned if the underlying class is
1879      * {@linkplain #isAnonymousClass() anonymous}.
1880      * A {@linkplain #isSynthetic() synthetic class}, one not present
1881      * in source code, can have a non-empty name including special
1882      * characters, such as "{@code $}".
1883      *
1884      * <p>The simple name of an {@linkplain #isArray() array class} is the simple name of the
1885      * component type with "[]" appended.  In particular the simple
1886      * name of an array class whose component type is anonymous is "[]".
1887      *
1888      * @return the simple name of the underlying class
1889      * @since 1.5
1890      */
getSimpleName()1891     public String getSimpleName() {
1892         // Android-changed: ART has a different JNI layer.
1893         if (isArray())
1894             return getComponentType().getSimpleName()+"[]";
1895 
1896         return getSimpleNameNative();
1897     }
1898 
1899     /**
1900      * Return an informative string for the name of this class or interface.
1901      *
1902      * @return an informative string for the name of this class or interface
1903      * @since 1.8
1904      */
getTypeName()1905     public String getTypeName() {
1906         if (isArray()) {
1907             try {
1908                 Class<?> cl = this;
1909                 int dimensions = 0;
1910                 do {
1911                     dimensions++;
1912                     cl = cl.getComponentType();
1913                 } while (cl.isArray());
1914                 return cl.getName() + "[]".repeat(dimensions);
1915             } catch (Throwable e) { /*FALLTHRU*/ }
1916         }
1917         return getName();
1918     }
1919 
1920     // Android-changed: Removed javadoc related to hidden classes.
1921     /**
1922      * Returns the canonical name of the underlying class as
1923      * defined by <cite>The Java Language Specification</cite>.
1924      * Returns {@code null} if the underlying class does not have a canonical
1925      * name. Classes without canonical names include:
1926      * <ul>
1927      * <li>a {@linkplain #isLocalClass() local class}
1928      * <li>a {@linkplain #isAnonymousClass() anonymous class}
1929      * <li>an array whose component type does not have a canonical name</li>
1930      * </ul>
1931      *
1932      * @return the canonical name of the underlying class if it exists, and
1933      * {@code null} otherwise.
1934      * @since 1.5
1935      */
getCanonicalName()1936     public String getCanonicalName() {
1937         // Android-changed: Android has no ReflectionData class.
1938         if (isArray()) {
1939             String canonicalName = getComponentType().getCanonicalName();
1940             if (canonicalName != null)
1941                 return canonicalName + "[]";
1942             else
1943                 return null;
1944         }
1945         if (isHidden() || isLocalOrAnonymousClass())
1946             // Android-changed: Android has no ReflectionData class. Returns null directly.
1947             // return ReflectionData.NULL_SENTINEL;
1948             return null;
1949         Class<?> enclosingClass = getEnclosingClass();
1950         if (enclosingClass == null) { // top level class
1951             return getName();
1952         } else {
1953             String enclosingName = enclosingClass.getCanonicalName();
1954             if (enclosingName == null)
1955                 // Android-changed: Android has no ReflectionData class. Returns null directly.
1956                 // return ReflectionData.NULL_SENTINEL;
1957                 return null;
1958             String simpleName = getSimpleName();
1959             return new StringBuilder(enclosingName.length() + simpleName.length() + 1)
1960                     .append(enclosingName)
1961                     .append('.')
1962                     .append(simpleName)
1963                     .toString();
1964         }
1965     }
1966 
1967     /**
1968      * Returns {@code true} if and only if the underlying class
1969      * is an anonymous class.
1970      *
1971      * @return {@code true} if and only if this class is an anonymous class.
1972      * @since 1.5
1973      * @jls 15.9.5 Anonymous Class Declarations
1974      */
1975     // Android-changed: ART has a different JNI layer.
1976     /*
1977     public boolean isAnonymousClass() {
1978         return !isArray() && isLocalOrAnonymousClass() &&
1979                 getSimpleBinaryName0() == null;
1980     }
1981     */
1982     @FastNative
isAnonymousClass()1983     public native boolean isAnonymousClass();
1984 
1985     /**
1986      * Returns {@code true} if and only if the underlying class
1987      * is a local class.
1988      *
1989      * @return {@code true} if and only if this class is a local class.
1990      * @since 1.5
1991      * @jls 14.3 Local Class Declarations
1992      */
isLocalClass()1993     public boolean isLocalClass() {
1994         // Android-changed: ART has a different JNI layer.
1995         // return isLocalOrAnonymousClass() &&
1996         //     (isArray() || getSimpleBinaryName0() != null);
1997         return (getEnclosingMethod() != null || getEnclosingConstructor() != null)
1998                 && !isAnonymousClass();
1999     }
2000 
2001     /**
2002      * Returns {@code true} if and only if the underlying class
2003      * is a member class.
2004      *
2005      * @return {@code true} if and only if this class is a member class.
2006      * @since 1.5
2007      * @jls 8.5 Member Type Declarations
2008      */
isMemberClass()2009     public boolean isMemberClass() {
2010         // Android-changed: ART has a different JNI layer.
2011         // return !isLocalOrAnonymousClass() && getDeclaringClass0() != null;
2012         return !isLocalOrAnonymousClass() && getDeclaringClass() != null;
2013     }
2014 
2015     /**
2016      * Returns {@code true} if this is a top level class.  Returns {@code false}
2017      * otherwise.
2018      */
isTopLevelClass()2019     private boolean isTopLevelClass() {
2020         // Android-changed: ART has a different JNI layer.
2021         // return !isLocalOrAnonymousClass() && getDeclaringClass0() == null;
2022         return !isLocalOrAnonymousClass() && getDeclaringClass() == null;
2023     }
2024 
2025     /**
2026      * Returns {@code true} if this is a local class or an anonymous
2027      * class.  Returns {@code false} otherwise.
2028      */
isLocalOrAnonymousClass()2029     private boolean isLocalOrAnonymousClass() {
2030         // Android-changed: ART has a different JNI layer.
2031         /*
2032         // JVM Spec 4.7.7: A class must have an EnclosingMethod
2033         // attribute if and only if it is a local class or an
2034         // anonymous class.
2035         return hasEnclosingMethodInfo();
2036         */
2037         return isLocalClass() || isAnonymousClass();
2038     }
2039 
2040     /**
2041      * Returns an array containing {@code Class} objects representing all
2042      * the public classes and interfaces that are members of the class
2043      * represented by this {@code Class} object.  This includes public
2044      * class and interface members inherited from superclasses and public class
2045      * and interface members declared by the class.  This method returns an
2046      * array of length 0 if this {@code Class} object has no public member
2047      * classes or interfaces.  This method also returns an array of length 0 if
2048      * this {@code Class} object represents a primitive type, an array
2049      * class, or void.
2050      *
2051      * @return the array of {@code Class} objects representing the public
2052      *         members of this class
2053      *
2054      * @since 1.1
2055      */
2056     @SuppressWarnings("removal")
2057     @CallerSensitive
getClasses()2058     public Class<?>[] getClasses() {
2059         // Android-changed: Removed SecurityManager check.
2060         List<Class<?>> result = new ArrayList<Class<?>>();
2061         for (Class<?> c = this; c != null; c = c.superClass) {
2062             for (Class<?> member : c.getDeclaredClasses()) {
2063                 if (Modifier.isPublic(member.getModifiers())) {
2064                     result.add(member);
2065                 }
2066             }
2067         }
2068         return result.toArray(new Class[result.size()]);
2069     }
2070 
2071 
2072     /**
2073      * Returns an array containing {@code Field} objects reflecting all
2074      * the accessible public fields of the class or interface represented by
2075      * this {@code Class} object.
2076      *
2077      * <p> If this {@code Class} object represents a class or interface with
2078      * no accessible public fields, then this method returns an array of length
2079      * 0.
2080      *
2081      * <p> If this {@code Class} object represents a class, then this method
2082      * returns the public fields of the class and of all its superclasses and
2083      * superinterfaces.
2084      *
2085      * <p> If this {@code Class} object represents an interface, then this
2086      * method returns the fields of the interface and of all its
2087      * superinterfaces.
2088      *
2089      * <p> If this {@code Class} object represents an array type, a primitive
2090      * type, or void, then this method returns an array of length 0.
2091      *
2092      * <p> The elements in the returned array are not sorted and are not in any
2093      * particular order.
2094      *
2095      * @return the array of {@code Field} objects representing the
2096      *         public fields
2097      * @throws SecurityException
2098      *         If a security manager, <i>s</i>, is present and
2099      *         the caller's class loader is not the same as or an
2100      *         ancestor of the class loader for the current class and
2101      *         invocation of {@link SecurityManager#checkPackageAccess
2102      *         s.checkPackageAccess()} denies access to the package
2103      *         of this class.
2104      *
2105      * @since 1.1
2106      * @jls 8.2 Class Members
2107      * @jls 8.3 Field Declarations
2108      */
2109     @CallerSensitive
getFields()2110     public Field[] getFields() throws SecurityException {
2111         // Android-changed: Removed SecurityManager check.
2112         List<Field> fields = new ArrayList<Field>();
2113         getPublicFieldsRecursive(fields);
2114         return fields.toArray(new Field[fields.size()]);
2115     }
2116 
2117     /**
2118      * Populates {@code result} with public fields defined by this class, its
2119      * superclasses, and all implemented interfaces.
2120      */
getPublicFieldsRecursive(List<Field> result)2121     private void getPublicFieldsRecursive(List<Field> result) {
2122         // search superclasses
2123         for (Class<?> c = this; c != null; c = c.superClass) {
2124             Collections.addAll(result, c.getPublicDeclaredFields());
2125         }
2126 
2127         // search iftable which has a flattened and uniqued list of interfaces
2128         Object[] iftable = ifTable;
2129         if (iftable != null) {
2130             for (int i = 0; i < iftable.length; i += 2) {
2131                 Collections.addAll(result, ((Class<?>) iftable[i]).getPublicDeclaredFields());
2132             }
2133         }
2134     }
2135 
2136     /**
2137      * Returns an array containing {@code Method} objects reflecting all the
2138      * public methods of the class or interface represented by this {@code
2139      * Class} object, including those declared by the class or interface and
2140      * those inherited from superclasses and superinterfaces.
2141      *
2142      * <p> If this {@code Class} object represents an array type, then the
2143      * returned array has a {@code Method} object for each of the public
2144      * methods inherited by the array type from {@code Object}. It does not
2145      * contain a {@code Method} object for {@code clone()}.
2146      *
2147      * <p> If this {@code Class} object represents an interface then the
2148      * returned array does not contain any implicitly declared methods from
2149      * {@code Object}. Therefore, if no methods are explicitly declared in
2150      * this interface or any of its superinterfaces then the returned array
2151      * has length 0. (Note that a {@code Class} object which represents a class
2152      * always has public methods, inherited from {@code Object}.)
2153      *
2154      * <p> The returned array never contains methods with names "{@code <init>}"
2155      * or "{@code <clinit>}".
2156      *
2157      * <p> The elements in the returned array are not sorted and are not in any
2158      * particular order.
2159      *
2160      * <p> Generally, the result is computed as with the following 4 step algorithm.
2161      * Let C be the class or interface represented by this {@code Class} object:
2162      * <ol>
2163      * <li> A union of methods is composed of:
2164      *   <ol type="a">
2165      *   <li> C's declared public instance and static methods as returned by
2166      *        {@link #getDeclaredMethods()} and filtered to include only public
2167      *        methods.</li>
2168      *   <li> If C is a class other than {@code Object}, then include the result
2169      *        of invoking this algorithm recursively on the superclass of C.</li>
2170      *   <li> Include the results of invoking this algorithm recursively on all
2171      *        direct superinterfaces of C, but include only instance methods.</li>
2172      *   </ol></li>
2173      * <li> Union from step 1 is partitioned into subsets of methods with same
2174      *      signature (name, parameter types) and return type.</li>
2175      * <li> Within each such subset only the most specific methods are selected.
2176      *      Let method M be a method from a set of methods with same signature
2177      *      and return type. M is most specific if there is no such method
2178      *      N != M from the same set, such that N is more specific than M.
2179      *      N is more specific than M if:
2180      *   <ol type="a">
2181      *   <li> N is declared by a class and M is declared by an interface; or</li>
2182      *   <li> N and M are both declared by classes or both by interfaces and
2183      *        N's declaring type is the same as or a subtype of M's declaring type
2184      *        (clearly, if M's and N's declaring types are the same type, then
2185      *        M and N are the same method).</li>
2186      *   </ol></li>
2187      * <li> The result of this algorithm is the union of all selected methods from
2188      *      step 3.</li>
2189      * </ol>
2190      *
2191      * @apiNote There may be more than one method with a particular name
2192      * and parameter types in a class because while the Java language forbids a
2193      * class to declare multiple methods with the same signature but different
2194      * return types, the Java virtual machine does not.  This
2195      * increased flexibility in the virtual machine can be used to
2196      * implement various language features.  For example, covariant
2197      * returns can be implemented with {@linkplain
2198      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
2199      * method and the overriding method would have the same
2200      * signature but different return types.
2201      *
2202      * @return the array of {@code Method} objects representing the
2203      *         public methods of this class
2204      * @throws SecurityException
2205      *         If a security manager, <i>s</i>, is present and
2206      *         the caller's class loader is not the same as or an
2207      *         ancestor of the class loader for the current class and
2208      *         invocation of {@link SecurityManager#checkPackageAccess
2209      *         s.checkPackageAccess()} denies access to the package
2210      *         of this class.
2211      *
2212      * @jls 8.2 Class Members
2213      * @jls 8.4 Method Declarations
2214      * @since 1.1
2215      */
2216     @CallerSensitive
getMethods()2217     public Method[] getMethods() throws SecurityException {
2218         // Android-changed: Removed SecurityManager check.
2219         List<Method> methods = new ArrayList<Method>();
2220         getPublicMethodsInternal(methods);
2221         /*
2222          * Remove duplicate methods defined by superclasses and
2223          * interfaces, preferring to keep methods declared by derived
2224          * types.
2225          */
2226         CollectionUtils.removeDuplicates(methods, Method.ORDER_BY_SIGNATURE);
2227         return methods.toArray(new Method[methods.size()]);
2228     }
2229 
2230     /**
2231      * Populates {@code result} with public methods defined by this class, its
2232      * superclasses, and all implemented interfaces, including overridden methods.
2233      */
getPublicMethodsInternal(List<Method> result)2234     private void getPublicMethodsInternal(List<Method> result) {
2235         Collections.addAll(result, getDeclaredMethodsUnchecked(true));
2236         if (!isInterface()) {
2237             // Search superclasses, for interfaces don't search java.lang.Object.
2238             for (Class<?> c = superClass; c != null; c = c.superClass) {
2239                 Collections.addAll(result, c.getDeclaredMethodsUnchecked(true));
2240             }
2241         }
2242         // Search iftable which has a flattened and uniqued list of interfaces.
2243         Object[] iftable = ifTable;
2244         if (iftable != null) {
2245             for (int i = 0; i < iftable.length; i += 2) {
2246                 Class<?> ifc = (Class<?>) iftable[i];
2247                 Collections.addAll(result, ifc.getDeclaredMethodsUnchecked(true));
2248             }
2249         }
2250     }
2251 
2252     /**
2253      * Returns an array containing {@code Constructor} objects reflecting
2254      * all the public constructors of the class represented by this
2255      * {@code Class} object.  An array of length 0 is returned if the
2256      * class has no public constructors, or if the class is an array class, or
2257      * if the class reflects a primitive type or void.
2258      *
2259      * @apiNote
2260      * While this method returns an array of {@code
2261      * Constructor<T>} objects (that is an array of constructors from
2262      * this class), the return type of this method is {@code
2263      * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
2264      * might be expected.  This less informative return type is
2265      * necessary since after being returned from this method, the
2266      * array could be modified to hold {@code Constructor} objects for
2267      * different classes, which would violate the type guarantees of
2268      * {@code Constructor<T>[]}.
2269      *
2270      * @return the array of {@code Constructor} objects representing the
2271      *         public constructors of this class
2272      * @throws SecurityException
2273      *         If a security manager, <i>s</i>, is present and
2274      *         the caller's class loader is not the same as or an
2275      *         ancestor of the class loader for the current class and
2276      *         invocation of {@link SecurityManager#checkPackageAccess
2277      *         s.checkPackageAccess()} denies access to the package
2278      *         of this class.
2279      *
2280      * @since 1.1
2281      */
2282     @CallerSensitive
getConstructors()2283     public Constructor<?>[] getConstructors() throws SecurityException {
2284         // Android-changed: Removed SecurityManager check.
2285         return getDeclaredConstructorsInternal(true);
2286     }
2287 
2288 
2289     /**
2290      * Returns a {@code Field} object that reflects the specified public member
2291      * field of the class or interface represented by this {@code Class}
2292      * object. The {@code name} parameter is a {@code String} specifying the
2293      * simple name of the desired field.
2294      *
2295      * <p> The field to be reflected is determined by the algorithm that
2296      * follows.  Let C be the class or interface represented by this {@code Class} object:
2297      *
2298      * <OL>
2299      * <LI> If C declares a public field with the name specified, that is the
2300      *      field to be reflected.</LI>
2301      * <LI> If no field was found in step 1 above, this algorithm is applied
2302      *      recursively to each direct superinterface of C. The direct
2303      *      superinterfaces are searched in the order they were declared.</LI>
2304      * <LI> If no field was found in steps 1 and 2 above, and C has a
2305      *      superclass S, then this algorithm is invoked recursively upon S.
2306      *      If C has no superclass, then a {@code NoSuchFieldException}
2307      *      is thrown.</LI>
2308      * </OL>
2309      *
2310      * <p> If this {@code Class} object represents an array type, then this
2311      * method does not find the {@code length} field of the array type.
2312      *
2313      * @param name the field name
2314      * @return the {@code Field} object of this class specified by
2315      *         {@code name}
2316      * @throws NoSuchFieldException if a field with the specified name is
2317      *         not found.
2318      * @throws NullPointerException if {@code name} is {@code null}
2319      * @throws SecurityException
2320      *         If a security manager, <i>s</i>, is present and
2321      *         the caller's class loader is not the same as or an
2322      *         ancestor of the class loader for the current class and
2323      *         invocation of {@link SecurityManager#checkPackageAccess
2324      *         s.checkPackageAccess()} denies access to the package
2325      *         of this class.
2326      *
2327      * @since 1.1
2328      * @jls 8.2 Class Members
2329      * @jls 8.3 Field Declarations
2330      */
2331     // Android-changed: Removed SecurityException.
2332     @CallerSensitive
getField(String name)2333     public Field getField(String name) throws NoSuchFieldException {
2334         Objects.requireNonNull(name);
2335         Field result = getPublicFieldRecursive(name);
2336         if (result == null) {
2337             throw new NoSuchFieldException(name);
2338         }
2339         return result;
2340     }
2341 
2342     /**
2343      * The native implementation of the {@code getField} method.
2344      *
2345      * @throws NullPointerException
2346      *            if name is null.
2347      * @see #getField(String)
2348      */
2349     @FastNative
getPublicFieldRecursive(String name)2350     private native Field getPublicFieldRecursive(String name);
2351 
2352     /**
2353      * Returns a {@code Method} object that reflects the specified public
2354      * member method of the class or interface represented by this
2355      * {@code Class} object. The {@code name} parameter is a
2356      * {@code String} specifying the simple name of the desired method. The
2357      * {@code parameterTypes} parameter is an array of {@code Class}
2358      * objects that identify the method's formal parameter types, in declared
2359      * order. If {@code parameterTypes} is {@code null}, it is
2360      * treated as if it were an empty array.
2361      *
2362      * <p> If this {@code Class} object represents an array type, then this
2363      * method finds any public method inherited by the array type from
2364      * {@code Object} except method {@code clone()}.
2365      *
2366      * <p> If this {@code Class} object represents an interface then this
2367      * method does not find any implicitly declared method from
2368      * {@code Object}. Therefore, if no methods are explicitly declared in
2369      * this interface or any of its superinterfaces, then this method does not
2370      * find any method.
2371      *
2372      * <p> This method does not find any method with name "{@code <init>}" or
2373      * "{@code <clinit>}".
2374      *
2375      * <p> Generally, the method to be reflected is determined by the 4 step
2376      * algorithm that follows.
2377      * Let C be the class or interface represented by this {@code Class} object:
2378      * <ol>
2379      * <li> A union of methods is composed of:
2380      *   <ol type="a">
2381      *   <li> C's declared public instance and static methods as returned by
2382      *        {@link #getDeclaredMethods()} and filtered to include only public
2383      *        methods that match given {@code name} and {@code parameterTypes}</li>
2384      *   <li> If C is a class other than {@code Object}, then include the result
2385      *        of invoking this algorithm recursively on the superclass of C.</li>
2386      *   <li> Include the results of invoking this algorithm recursively on all
2387      *        direct superinterfaces of C, but include only instance methods.</li>
2388      *   </ol></li>
2389      * <li> This union is partitioned into subsets of methods with same
2390      *      return type (the selection of methods from step 1 also guarantees that
2391      *      they have the same method name and parameter types).</li>
2392      * <li> Within each such subset only the most specific methods are selected.
2393      *      Let method M be a method from a set of methods with same VM
2394      *      signature (return type, name, parameter types).
2395      *      M is most specific if there is no such method N != M from the same
2396      *      set, such that N is more specific than M. N is more specific than M
2397      *      if:
2398      *   <ol type="a">
2399      *   <li> N is declared by a class and M is declared by an interface; or</li>
2400      *   <li> N and M are both declared by classes or both by interfaces and
2401      *        N's declaring type is the same as or a subtype of M's declaring type
2402      *        (clearly, if M's and N's declaring types are the same type, then
2403      *        M and N are the same method).</li>
2404      *   </ol></li>
2405      * <li> The result of this algorithm is chosen arbitrarily from the methods
2406      *      with most specific return type among all selected methods from step 3.
2407      *      Let R be a return type of a method M from the set of all selected methods
2408      *      from step 3. M is a method with most specific return type if there is
2409      *      no such method N != M from the same set, having return type S != R,
2410      *      such that S is a subtype of R as determined by
2411      *      R.class.{@link #isAssignableFrom}(S.class).
2412      * </ol>
2413      *
2414      * @apiNote There may be more than one method with matching name and
2415      * parameter types in a class because while the Java language forbids a
2416      * class to declare multiple methods with the same signature but different
2417      * return types, the Java virtual machine does not.  This
2418      * increased flexibility in the virtual machine can be used to
2419      * implement various language features.  For example, covariant
2420      * returns can be implemented with {@linkplain
2421      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
2422      * method and the overriding method would have the same
2423      * signature but different return types. This method would return the
2424      * overriding method as it would have a more specific return type.
2425      *
2426      * @param name the name of the method
2427      * @param parameterTypes the list of parameters
2428      * @return the {@code Method} object that matches the specified
2429      *         {@code name} and {@code parameterTypes}
2430      * @throws NoSuchMethodException if a matching method is not found
2431      *         or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
2432      * @throws NullPointerException if {@code name} is {@code null}
2433      * @throws SecurityException
2434      *         If a security manager, <i>s</i>, is present and
2435      *         the caller's class loader is not the same as or an
2436      *         ancestor of the class loader for the current class and
2437      *         invocation of {@link SecurityManager#checkPackageAccess
2438      *         s.checkPackageAccess()} denies access to the package
2439      *         of this class.
2440      *
2441      * @jls 8.2 Class Members
2442      * @jls 8.4 Method Declarations
2443      * @since 1.1
2444      */
2445     @CallerSensitive
getMethod(String name, Class<?>... parameterTypes)2446     public Method getMethod(String name, Class<?>... parameterTypes)
2447         throws NoSuchMethodException, SecurityException {
2448         Objects.requireNonNull(name);
2449         // Android-changed: Removed SecurityManager check.
2450         return getMethod(name, parameterTypes, true);
2451     }
2452 
2453 
2454     /**
2455      * Returns a {@code Constructor} object that reflects the specified
2456      * public constructor of the class represented by this {@code Class}
2457      * object. The {@code parameterTypes} parameter is an array of
2458      * {@code Class} objects that identify the constructor's formal
2459      * parameter types, in declared order.
2460      *
2461      * If this {@code Class} object represents an inner class
2462      * declared in a non-static context, the formal parameter types
2463      * include the explicit enclosing instance as the first parameter.
2464      *
2465      * <p> The constructor to reflect is the public constructor of the class
2466      * represented by this {@code Class} object whose formal parameter
2467      * types match those specified by {@code parameterTypes}.
2468      *
2469      * @param parameterTypes the parameter array
2470      * @return the {@code Constructor} object of the public constructor that
2471      *         matches the specified {@code parameterTypes}
2472      * @throws NoSuchMethodException if a matching method is not found.
2473      * @throws SecurityException
2474      *         If a security manager, <i>s</i>, is present and
2475      *         the caller's class loader is not the same as or an
2476      *         ancestor of the class loader for the current class and
2477      *         invocation of {@link SecurityManager#checkPackageAccess
2478      *         s.checkPackageAccess()} denies access to the package
2479      *         of this class.
2480      *
2481      * @since 1.1
2482      */
getConstructor(Class<?>.... parameterTypes)2483     public Constructor<T> getConstructor(Class<?>... parameterTypes)
2484         throws NoSuchMethodException, SecurityException
2485     {
2486         // Android-changed: Removed SecurityManager check.
2487         return getConstructor0(parameterTypes, Member.PUBLIC);
2488     }
2489 
2490 
2491     /**
2492      * Returns an array of {@code Class} objects reflecting all the
2493      * classes and interfaces declared as members of the class represented by
2494      * this {@code Class} object. This includes public, protected, default
2495      * (package) access, and private classes and interfaces declared by the
2496      * class, but excludes inherited classes and interfaces.  This method
2497      * returns an array of length 0 if the class declares no classes or
2498      * interfaces as members, or if this {@code Class} object represents a
2499      * primitive type, an array class, or void.
2500      *
2501      * @return the array of {@code Class} objects representing all the
2502      *         declared members of this class
2503      * @throws SecurityException
2504      *         If a security manager, <i>s</i>, is present and any of the
2505      *         following conditions is met:
2506      *
2507      *         <ul>
2508      *
2509      *         <li> the caller's class loader is not the same as the
2510      *         class loader of this class and invocation of
2511      *         {@link SecurityManager#checkPermission
2512      *         s.checkPermission} method with
2513      *         {@code RuntimePermission("accessDeclaredMembers")}
2514      *         denies access to the declared classes within this class
2515      *
2516      *         <li> the caller's class loader is not the same as or an
2517      *         ancestor of the class loader for the current class and
2518      *         invocation of {@link SecurityManager#checkPackageAccess
2519      *         s.checkPackageAccess()} denies access to the package
2520      *         of this class
2521      *
2522      *         </ul>
2523      *
2524      * @since 1.1
2525      * @jls 8.5 Member Type Declarations
2526      */
2527     // Android-changed: Removed SecurityException.
2528     /*
2529     @CallerSensitive
2530     public Class<?>[] getDeclaredClasses() throws SecurityException {
2531         @SuppressWarnings("removal")
2532         SecurityManager sm = System.getSecurityManager();
2533         if (sm != null) {
2534             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), false);
2535         }
2536         return getDeclaredClasses0();
2537     }
2538     */
2539     @FastNative
getDeclaredClasses()2540     public native Class<?>[] getDeclaredClasses();
2541 
2542     /**
2543      * Returns an array of {@code Field} objects reflecting all the fields
2544      * declared by the class or interface represented by this
2545      * {@code Class} object. This includes public, protected, default
2546      * (package) access, and private fields, but excludes inherited fields.
2547      *
2548      * <p> If this {@code Class} object represents a class or interface with no
2549      * declared fields, then this method returns an array of length 0.
2550      *
2551      * <p> If this {@code Class} object represents an array type, a primitive
2552      * type, or void, then this method returns an array of length 0.
2553      *
2554      * <p> The elements in the returned array are not sorted and are not in any
2555      * particular order.
2556      *
2557      * @return  the array of {@code Field} objects representing all the
2558      *          declared fields of this class
2559      * @throws  SecurityException
2560      *          If a security manager, <i>s</i>, is present and any of the
2561      *          following conditions is met:
2562      *
2563      *          <ul>
2564      *
2565      *          <li> the caller's class loader is not the same as the
2566      *          class loader of this class and invocation of
2567      *          {@link SecurityManager#checkPermission
2568      *          s.checkPermission} method with
2569      *          {@code RuntimePermission("accessDeclaredMembers")}
2570      *          denies access to the declared fields within this class
2571      *
2572      *          <li> the caller's class loader is not the same as or an
2573      *          ancestor of the class loader for the current class and
2574      *          invocation of {@link SecurityManager#checkPackageAccess
2575      *          s.checkPackageAccess()} denies access to the package
2576      *          of this class
2577      *
2578      *          </ul>
2579      *
2580      * @since 1.1
2581      * @jls 8.2 Class Members
2582      * @jls 8.3 Field Declarations
2583      */
2584     // Android-changed: Removed SecurityException.
2585     /*
2586     @CallerSensitive
2587     public Field[] getDeclaredFields() throws SecurityException {
2588         @SuppressWarnings("removal")
2589         SecurityManager sm = System.getSecurityManager();
2590         if (sm != null) {
2591             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2592         }
2593         return copyFields(privateGetDeclaredFields(false));
2594     }
2595     */
2596     @FastNative
getDeclaredFields()2597     public native Field[] getDeclaredFields();
2598 
2599     /**
2600      * Returns an array of {@code RecordComponent} objects representing all the
2601      * record components of this record class, or {@code null} if this class is
2602      * not a record class.
2603      *
2604      * <p> The components are returned in the same order that they are declared
2605      * in the record header. The array is empty if this record class has no
2606      * components. If the class is not a record class, that is {@link
2607      * #isRecord()} returns {@code false}, then this method returns {@code null}.
2608      * Conversely, if {@link #isRecord()} returns {@code true}, then this method
2609      * returns a non-null value.
2610      *
2611      * @apiNote
2612      * <p> The following method can be used to find the record canonical constructor:
2613      *
2614      * <pre>{@code
2615      * static <T extends Record> Constructor<T> getCanonicalConstructor(Class<T> cls)
2616      *     throws NoSuchMethodException {
2617      *   Class<?>[] paramTypes =
2618      *     Arrays.stream(cls.getRecordComponents())
2619      *           .map(RecordComponent::getType)
2620      *           .toArray(Class<?>[]::new);
2621      *   return cls.getDeclaredConstructor(paramTypes);
2622      * }}</pre>
2623      *
2624      * @return  An array of {@code RecordComponent} objects representing all the
2625      *          record components of this record class, or {@code null} if this
2626      *          class is not a record class
2627      * @throws  SecurityException
2628      *          If a security manager, <i>s</i>, is present and any of the
2629      *          following conditions is met:
2630      *
2631      *          <ul>
2632      *
2633      *          <li> the caller's class loader is not the same as the
2634      *          class loader of this class and invocation of
2635      *          {@link SecurityManager#checkPermission
2636      *          s.checkPermission} method with
2637      *          {@code RuntimePermission("accessDeclaredMembers")}
2638      *          denies access to the declared methods within this class
2639      *
2640      *          <li> the caller's class loader is not the same as or an
2641      *          ancestor of the class loader for the current class and
2642      *          invocation of {@link SecurityManager#checkPackageAccess
2643      *          s.checkPackageAccess()} denies access to the package
2644      *          of this class
2645      *
2646      *          </ul>
2647      *
2648      * @jls 8.10 Record Classes
2649      * @since 16
2650      */
2651     @CallerSensitive
getRecordComponents()2652     public RecordComponent[] getRecordComponents() {
2653         // Android-removed: Android doesn't support SecurityManager.
2654         /*
2655         @SuppressWarnings("removal")
2656         SecurityManager sm = System.getSecurityManager();
2657         if (sm != null) {
2658             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2659         }
2660         */
2661         if (!isRecord()) {
2662             return null;
2663         }
2664         return getRecordComponents0();
2665     }
2666 
2667     /**
2668      * Populates a list of fields without performing any security or type
2669      * resolution checks first. If no fields exist, the list is not modified.
2670      *
2671      * @param publicOnly Whether to return only public fields.
2672      * @hide
2673      */
2674     @FastNative
getDeclaredFieldsUnchecked(boolean publicOnly)2675     public native Field[] getDeclaredFieldsUnchecked(boolean publicOnly);
2676 
2677     /**
2678      * Returns an array containing {@code Method} objects reflecting all the
2679      * declared methods of the class or interface represented by this {@code
2680      * Class} object, including public, protected, default (package)
2681      * access, and private methods, but excluding inherited methods.
2682      * The declared methods may include methods <em>not</em> in the
2683      * source of the class or interface, including {@linkplain
2684      * Method#isBridge bridge methods} and other {@linkplain
2685      * Executable#isSynthetic synthetic} methods added by compilers.
2686      *
2687      * <p> If this {@code Class} object represents a class or interface that
2688      * has multiple declared methods with the same name and parameter types,
2689      * but different return types, then the returned array has a {@code Method}
2690      * object for each such method.
2691      *
2692      * <p> If this {@code Class} object represents a class or interface that
2693      * has a class initialization method {@code <clinit>}, then the returned
2694      * array does <em>not</em> have a corresponding {@code Method} object.
2695      *
2696      * <p> If this {@code Class} object represents a class or interface with no
2697      * declared methods, then the returned array has length 0.
2698      *
2699      * <p> If this {@code Class} object represents an array type, a primitive
2700      * type, or void, then the returned array has length 0.
2701      *
2702      * <p> The elements in the returned array are not sorted and are not in any
2703      * particular order.
2704      *
2705      * @return  the array of {@code Method} objects representing all the
2706      *          declared methods of this class
2707      * @throws  SecurityException
2708      *          If a security manager, <i>s</i>, is present and any of the
2709      *          following conditions is met:
2710      *
2711      *          <ul>
2712      *
2713      *          <li> the caller's class loader is not the same as the
2714      *          class loader of this class and invocation of
2715      *          {@link SecurityManager#checkPermission
2716      *          s.checkPermission} method with
2717      *          {@code RuntimePermission("accessDeclaredMembers")}
2718      *          denies access to the declared methods within this class
2719      *
2720      *          <li> the caller's class loader is not the same as or an
2721      *          ancestor of the class loader for the current class and
2722      *          invocation of {@link SecurityManager#checkPackageAccess
2723      *          s.checkPackageAccess()} denies access to the package
2724      *          of this class
2725      *
2726      *          </ul>
2727      *
2728      * @jls 8.2 Class Members
2729      * @jls 8.4 Method Declarations
2730      * @see <a
2731      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
2732      * programming language and JVM modeling in core reflection</a>
2733      * @since 1.1
2734      */
getDeclaredMethods()2735     public Method[] getDeclaredMethods() throws SecurityException {
2736         // Android-changed: Removed SecurityManager check.
2737         Method[] result = getDeclaredMethodsUnchecked(false);
2738         for (Method m : result) {
2739             // Throw NoClassDefFoundError if types cannot be resolved.
2740             m.getReturnType();
2741             m.getParameterTypes();
2742         }
2743         return result;
2744     }
2745 
2746     /**
2747      * Populates a list of methods without performing any security or type
2748      * resolution checks first. If no methods exist, the list is not modified.
2749      *
2750      * @param publicOnly Whether to return only public methods.
2751      * @hide
2752      */
2753     @FastNative
getDeclaredMethodsUnchecked(boolean publicOnly)2754     public native Method[] getDeclaredMethodsUnchecked(boolean publicOnly);
2755 
2756     /**
2757      * Returns an array of {@code Constructor} objects reflecting all the
2758      * constructors declared by the class represented by this
2759      * {@code Class} object. These are public, protected, default
2760      * (package) access, and private constructors.  The elements in the array
2761      * returned are not sorted and are not in any particular order.  If the
2762      * class has a default constructor, it is included in the returned array.
2763      * This method returns an array of length 0 if this {@code Class}
2764      * object represents an interface, a primitive type, an array class, or
2765      * void.
2766      *
2767      * <p> See <cite>The Java Language Specification</cite>,
2768      * section {@jls 8.2}.
2769      *
2770      * @return  the array of {@code Constructor} objects representing all the
2771      *          declared constructors of this class
2772      * @throws  SecurityException
2773      *          If a security manager, <i>s</i>, is present and any of the
2774      *          following conditions is met:
2775      *
2776      *          <ul>
2777      *
2778      *          <li> the caller's class loader is not the same as the
2779      *          class loader of this class and invocation of
2780      *          {@link SecurityManager#checkPermission
2781      *          s.checkPermission} method with
2782      *          {@code RuntimePermission("accessDeclaredMembers")}
2783      *          denies access to the declared constructors within this class
2784      *
2785      *          <li> the caller's class loader is not the same as or an
2786      *          ancestor of the class loader for the current class and
2787      *          invocation of {@link SecurityManager#checkPackageAccess
2788      *          s.checkPackageAccess()} denies access to the package
2789      *          of this class
2790      *
2791      *          </ul>
2792      *
2793      * @since 1.1
2794      * @jls 8.8 Constructor Declarations
2795      */
getDeclaredConstructors()2796     public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
2797         // Android-changed: Removed SecurityManager check.
2798         return getDeclaredConstructorsInternal(false);
2799     }
2800 
2801 
2802     /**
2803      * Returns the constructor with the given parameters if it is defined by this class;
2804      * {@code null} otherwise. This may return a non-public member.
2805      */
2806     @FastNative
getDeclaredConstructorsInternal(boolean publicOnly)2807     private native Constructor<?>[] getDeclaredConstructorsInternal(boolean publicOnly);
2808 
2809     /**
2810      * Returns a {@code Field} object that reflects the specified declared
2811      * field of the class or interface represented by this {@code Class}
2812      * object. The {@code name} parameter is a {@code String} that specifies
2813      * the simple name of the desired field.
2814      *
2815      * <p> If this {@code Class} object represents an array type, then this
2816      * method does not find the {@code length} field of the array type.
2817      *
2818      * @param name the name of the field
2819      * @return  the {@code Field} object for the specified field in this
2820      *          class
2821      * @throws  NoSuchFieldException if a field with the specified name is
2822      *          not found.
2823      * @throws  NullPointerException if {@code name} is {@code null}
2824      * @throws  SecurityException
2825      *          If a security manager, <i>s</i>, is present and any of the
2826      *          following conditions is met:
2827      *
2828      *          <ul>
2829      *
2830      *          <li> the caller's class loader is not the same as the
2831      *          class loader of this class and invocation of
2832      *          {@link SecurityManager#checkPermission
2833      *          s.checkPermission} method with
2834      *          {@code RuntimePermission("accessDeclaredMembers")}
2835      *          denies access to the declared field
2836      *
2837      *          <li> the caller's class loader is not the same as or an
2838      *          ancestor of the class loader for the current class and
2839      *          invocation of {@link SecurityManager#checkPackageAccess
2840      *          s.checkPackageAccess()} denies access to the package
2841      *          of this class
2842      *
2843      *          </ul>
2844      *
2845      * @since 1.1
2846      * @jls 8.2 Class Members
2847      * @jls 8.3 Field Declarations
2848      */
2849     // Android-changed: ART has a different JNI layer.
2850     // Android-changed: Removed SecurityException.
2851     /*
2852     @CallerSensitive
2853     public Field getDeclaredField(String name)
2854         throws NoSuchFieldException, SecurityException {
2855         Objects.requireNonNull(name);
2856         @SuppressWarnings("removal")
2857         SecurityManager sm = System.getSecurityManager();
2858         if (sm != null) {
2859             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2860         }
2861         Field field = searchFields(privateGetDeclaredFields(false), name);
2862         if (field == null) {
2863             throw new NoSuchFieldException(name);
2864         }
2865         return getReflectionFactory().copyField(field);
2866     }
2867      */
2868     @FastNative
getDeclaredField(String name)2869     public native Field getDeclaredField(String name) throws NoSuchFieldException;
2870 
2871     /**
2872      * Returns the subset of getDeclaredFields which are public.
2873      */
2874     @FastNative
getPublicDeclaredFields()2875     private native Field[] getPublicDeclaredFields();
2876 
2877     /**
2878      * Returns a {@code Method} object that reflects the specified
2879      * declared method of the class or interface represented by this
2880      * {@code Class} object. The {@code name} parameter is a
2881      * {@code String} that specifies the simple name of the desired
2882      * method, and the {@code parameterTypes} parameter is an array of
2883      * {@code Class} objects that identify the method's formal parameter
2884      * types, in declared order.  If more than one method with the same
2885      * parameter types is declared in a class, and one of these methods has a
2886      * return type that is more specific than any of the others, that method is
2887      * returned; otherwise one of the methods is chosen arbitrarily.  If the
2888      * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
2889      * is raised.
2890      *
2891      * <p> If this {@code Class} object represents an array type, then this
2892      * method does not find the {@code clone()} method.
2893      *
2894      * @param name the name of the method
2895      * @param parameterTypes the parameter array
2896      * @return  the {@code Method} object for the method of this class
2897      *          matching the specified name and parameters
2898      * @throws  NoSuchMethodException if a matching method is not found.
2899      * @throws  NullPointerException if {@code name} is {@code null}
2900      * @throws  SecurityException
2901      *          If a security manager, <i>s</i>, is present and any of the
2902      *          following conditions is met:
2903      *
2904      *          <ul>
2905      *
2906      *          <li> the caller's class loader is not the same as the
2907      *          class loader of this class and invocation of
2908      *          {@link SecurityManager#checkPermission
2909      *          s.checkPermission} method with
2910      *          {@code RuntimePermission("accessDeclaredMembers")}
2911      *          denies access to the declared method
2912      *
2913      *          <li> the caller's class loader is not the same as or an
2914      *          ancestor of the class loader for the current class and
2915      *          invocation of {@link SecurityManager#checkPackageAccess
2916      *          s.checkPackageAccess()} denies access to the package
2917      *          of this class
2918      *
2919      *          </ul>
2920      *
2921      * @jls 8.2 Class Members
2922      * @jls 8.4 Method Declarations
2923      * @since 1.1
2924      */
2925     @CallerSensitive
getDeclaredMethod(String name, Class<?>... parameterTypes)2926     public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2927         throws NoSuchMethodException, SecurityException {
2928         // Android-changed: ART has a different JNI layer.
2929         return getMethod(name, parameterTypes, false);
2930     }
2931 
2932     // BEGIN Android-added: Internal methods to implement getMethod(...).
getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods)2933     private Method getMethod(String name, Class<?>[] parameterTypes, boolean recursivePublicMethods)
2934             throws NoSuchMethodException {
2935         Objects.requireNonNull(name);
2936         if (parameterTypes == null) {
2937             parameterTypes = EmptyArray.CLASS;
2938         }
2939         for (Class<?> c : parameterTypes) {
2940             if (c == null) {
2941                 throw new NoSuchMethodException("parameter type is null");
2942             }
2943         }
2944         Method result = recursivePublicMethods ? getPublicMethodRecursive(name, parameterTypes)
2945                                                : getDeclaredMethodInternal(name, parameterTypes);
2946         // Fail if we didn't find the method or it was expected to be public.
2947         if (result == null ||
2948             (recursivePublicMethods && !Modifier.isPublic(result.getAccessFlags()))) {
2949             throw new NoSuchMethodException(getName() + "." + name + " "
2950                     + Arrays.toString(parameterTypes));
2951         }
2952         return result;
2953     }
getPublicMethodRecursive(String name, Class<?>[] parameterTypes)2954     private Method getPublicMethodRecursive(String name, Class<?>[] parameterTypes) {
2955         // search superclasses
2956         for (Class<?> c = this; c != null; c = c.getSuperclass()) {
2957             Method result = c.getDeclaredMethodInternal(name, parameterTypes);
2958             if (result != null && Modifier.isPublic(result.getAccessFlags())) {
2959                 return result;
2960             }
2961         }
2962 
2963         return findInterfaceMethod(name, parameterTypes);
2964     }
2965 
2966     /**
2967      * Returns an instance method that's defined on this class or any super classes, regardless
2968      * of its access flags. Constructors are excluded.
2969      *
2970      * This function does not perform access checks and its semantics don't match any dex byte code
2971      * instruction or public reflection API. This is used by {@code MethodHandles.findVirtual}
2972      * which will perform access checks on the returned method.
2973      *
2974      * @hide
2975      */
getInstanceMethod(String name, Class<?>[] parameterTypes)2976     public Method getInstanceMethod(String name, Class<?>[] parameterTypes)
2977             throws NoSuchMethodException, IllegalAccessException {
2978         for (Class<?> c = this; c != null; c = c.getSuperclass()) {
2979             Method result = c.getDeclaredMethodInternal(name, parameterTypes);
2980             if (result != null && !Modifier.isStatic(result.getModifiers())) {
2981                 return result;
2982             }
2983         }
2984 
2985         return findInterfaceMethod(name, parameterTypes);
2986     }
2987 
findInterfaceMethod(String name, Class<?>[] parameterTypes)2988     private Method findInterfaceMethod(String name, Class<?>[] parameterTypes) {
2989         Object[] iftable = ifTable;
2990         if (iftable != null) {
2991             // Search backwards so more specific interfaces are searched first. This ensures that
2992             // the method we return is not overridden by one of it's subtypes that this class also
2993             // implements.
2994             for (int i = iftable.length - 2; i >= 0; i -= 2) {
2995                 Class<?> ifc = (Class<?>) iftable[i];
2996                 Method result = ifc.getPublicMethodRecursive(name, parameterTypes);
2997                 if (result != null && Modifier.isPublic(result.getAccessFlags())) {
2998                     return result;
2999                 }
3000             }
3001         }
3002 
3003         return null;
3004     }
3005     // END Android-added: Internal methods to implement getMethod(...).
3006 
3007     // Android-removed: unused method.
3008     /*
3009      * Returns the list of {@code Method} objects for the declared public
3010      * methods of this class or interface that have the specified method name
3011      * and parameter types.
3012      *
3013      * @param name the name of the method
3014      * @param parameterTypes the parameter array
3015      * @return the list of {@code Method} objects for the public methods of
3016      *         this class matching the specified name and parameters
3017      *
3018     List<Method> getDeclaredPublicMethods(String name, Class<?>... parameterTypes) {
3019         Method[] methods = privateGetDeclaredMethods(/* publicOnly * true);
3020         ReflectionFactory factory = getReflectionFactory();
3021         List<Method> result = new ArrayList<>();
3022         for (Method method : methods) {
3023             if (method.getName().equals(name)
3024                 && Arrays.equals(
3025                     factory.getExecutableSharedParameterTypes(method),
3026                     parameterTypes)) {
3027                 result.add(factory.copyMethod(method));
3028             }
3029         }
3030         return result;
3031     }
3032     */
3033 
3034     /**
3035      * Returns a {@code Constructor} object that reflects the specified
3036      * constructor of the class or interface represented by this
3037      * {@code Class} object.  The {@code parameterTypes} parameter is
3038      * an array of {@code Class} objects that identify the constructor's
3039      * formal parameter types, in declared order.
3040      *
3041      * If this {@code Class} object represents an inner class
3042      * declared in a non-static context, the formal parameter types
3043      * include the explicit enclosing instance as the first parameter.
3044      *
3045      * @param parameterTypes the parameter array
3046      * @return  The {@code Constructor} object for the constructor with the
3047      *          specified parameter list
3048      * @throws  NoSuchMethodException if a matching method is not found.
3049      * @throws  SecurityException
3050      *          If a security manager, <i>s</i>, is present and any of the
3051      *          following conditions is met:
3052      *
3053      *          <ul>
3054      *
3055      *          <li> the caller's class loader is not the same as the
3056      *          class loader of this class and invocation of
3057      *          {@link SecurityManager#checkPermission
3058      *          s.checkPermission} method with
3059      *          {@code RuntimePermission("accessDeclaredMembers")}
3060      *          denies access to the declared constructor
3061      *
3062      *          <li> the caller's class loader is not the same as or an
3063      *          ancestor of the class loader for the current class and
3064      *          invocation of {@link SecurityManager#checkPackageAccess
3065      *          s.checkPackageAccess()} denies access to the package
3066      *          of this class
3067      *
3068      *          </ul>
3069      *
3070      * @since 1.1
3071      */
3072     @CallerSensitive
getDeclaredConstructor(Class<?>.... parameterTypes)3073     public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
3074         throws NoSuchMethodException, SecurityException
3075     {
3076         // Android-changed: Removed SecurityManager check.
3077         return getConstructor0(parameterTypes, Member.DECLARED);
3078     }
3079 
3080     // Android-changed: Removed javadoc related to Module.
3081     /**
3082      * Finds a resource with a given name.
3083      *
3084      * <p> The rules for
3085      * searching resources associated with a given class are implemented by the
3086      * defining {@linkplain ClassLoader class loader} of the class.  This method
3087      * delegates to this {@code Class} object's class loader.
3088      * If this {@code Class} object was loaded by the bootstrap class loader,
3089      * the method delegates to {@link ClassLoader#getSystemResourceAsStream}.
3090      *
3091      * <p> Before delegation, an absolute resource name is constructed from the
3092      * given resource name using this algorithm:
3093      *
3094      * <ul>
3095      *
3096      * <li> If the {@code name} begins with a {@code '/'}
3097      * (<code>'&#92;u002f'</code>), then the absolute name of the resource is the
3098      * portion of the {@code name} following the {@code '/'}.
3099      *
3100      * <li> Otherwise, the absolute name is of the following form:
3101      *
3102      * <blockquote>
3103      *   {@code modified_package_name/name}
3104      * </blockquote>
3105      *
3106      * <p> Where the {@code modified_package_name} is the package name of this
3107      * object with {@code '/'} substituted for {@code '.'}
3108      * (<code>'&#92;u002e'</code>).
3109      *
3110      * </ul>
3111      *
3112      * @param  name name of the desired resource
3113      * @return  A {@link java.io.InputStream} object; {@code null} if no
3114      *          resource with this name is found.
3115      * @throws  NullPointerException If {@code name} is {@code null}
3116      * @since  1.1
3117      * @revised 9
3118      */
3119     @CallerSensitive
getResourceAsStream(String name)3120     public InputStream getResourceAsStream(String name) {
3121         name = resolveName(name);
3122         // unnamed module
3123         // Android-changed: Removed BuiltinClassLoader, Module usage, and SecurityManager check.
3124         ClassLoader cl = getClassLoader();
3125         if (cl == null) {
3126             return ClassLoader.getSystemResourceAsStream(name);
3127         } else {
3128             return cl.getResourceAsStream(name);
3129         }
3130     }
3131 
3132     // Android-changed: Remove javadoc related to the module system.
3133     /**
3134      * Finds a resource with a given name.
3135      *
3136      * <p> The rules for
3137      * searching resources associated with a given class are implemented by the
3138      * defining {@linkplain ClassLoader class loader} of the class.  This method
3139      * delegates to this {@code Class} object's class loader.
3140      * If this {@code Class} object was loaded by the bootstrap class loader,
3141      * the method delegates to {@link ClassLoader#getSystemResource}.
3142      *
3143      * <p> Before delegation, an absolute resource name is constructed from the
3144      * given resource name using this algorithm:
3145      *
3146      * <ul>
3147      *
3148      * <li> If the {@code name} begins with a {@code '/'}
3149      * (<code>'&#92;u002f'</code>), then the absolute name of the resource is the
3150      * portion of the {@code name} following the {@code '/'}.
3151      *
3152      * <li> Otherwise, the absolute name is of the following form:
3153      *
3154      * <blockquote>
3155      *   {@code modified_package_name/name}
3156      * </blockquote>
3157      *
3158      * <p> Where the {@code modified_package_name} is the package name of this
3159      * object with {@code '/'} substituted for {@code '.'}
3160      * (<code>'&#92;u002e'</code>).
3161      *
3162      * </ul>
3163      *
3164      * @param  name name of the desired resource
3165      * @return A {@link java.net.URL} object; {@code null} if no resource with
3166      *         this name is found.
3167      * @throws NullPointerException If {@code name} is {@code null}
3168      * @since  1.1
3169      * @revised 9
3170      */
3171     @CallerSensitive
getResource(String name)3172     public URL getResource(String name) {
3173         name = resolveName(name);
3174         // unnamed module
3175         // Android-changed: Removed BuiltinClassLoader, Module usage, and SecurityManager check.
3176         ClassLoader cl = getClassLoader();
3177         if (cl == null) {
3178             return ClassLoader.getSystemResource(name);
3179         } else {
3180             return cl.getResource(name);
3181         }
3182     }
3183 
3184     // Android-removed: Remove unused method.
3185     /*
3186      * Returns true if a resource with the given name can be located by the
3187      * given caller. All resources in a module can be located by code in
3188      * the module. For other callers, then the package needs to be open to
3189      * the caller.
3190      *
3191     private boolean isOpenToCaller(String name, Class<?> caller) {
3192         // assert getModule().isNamed();
3193         Module thisModule = getModule();
3194         Module callerModule = (caller != null) ? caller.getModule() : null;
3195         if (callerModule != thisModule) {
3196             String pn = Resources.toPackageName(name);
3197             if (thisModule.getDescriptor().packages().contains(pn)) {
3198                 if (callerModule == null && !thisModule.isOpen(pn)) {
3199                     // no caller, package not open
3200                     return false;
3201                 }
3202                 if (!thisModule.isOpen(pn, callerModule)) {
3203                     // package not open to caller
3204                     return false;
3205                 }
3206             }
3207         }
3208         return true;
3209     }
3210 
3211 
3212     /** protection domain returned when the internal domain is null *
3213     private static java.security.ProtectionDomain allPermDomain;
3214     */
3215 
3216     /**
3217      * Returns the {@code ProtectionDomain} of this class.  If there is a
3218      * security manager installed, this method first calls the security
3219      * manager's {@code checkPermission} method with a
3220      * {@code RuntimePermission("getProtectionDomain")} permission to
3221      * ensure it's ok to get the
3222      * {@code ProtectionDomain}.
3223      *
3224      * @return the ProtectionDomain of this class
3225      *
3226      * @throws SecurityException
3227      *        if a security manager exists and its
3228      *        {@code checkPermission} method doesn't allow
3229      *        getting the ProtectionDomain.
3230      *
3231      * @see java.security.ProtectionDomain
3232      * @see SecurityManager#checkPermission
3233      * @see java.lang.RuntimePermission
3234      * @since 1.2
3235      */
getProtectionDomain()3236     public java.security.ProtectionDomain getProtectionDomain() {
3237         // Android-changed: Removed SecurityManager check.
3238         return null;
3239     }
3240 
3241     // Android-removed: Removed SecurityManager check.
3242     /*
3243     // package-private
3244     java.security.ProtectionDomain protectionDomain() {
3245         java.security.ProtectionDomain pd = getProtectionDomain0();
3246         if (pd == null) {
3247             if (allPermDomain == null) {
3248                 java.security.Permissions perms =
3249                     new java.security.Permissions();
3250                 perms.add(SecurityConstants.ALL_PERMISSION);
3251                 allPermDomain =
3252                     new java.security.ProtectionDomain(null, perms);
3253             }
3254             pd = allPermDomain;
3255         }
3256         return pd;
3257     }
3258 
3259     /**
3260      * Returns the ProtectionDomain of this class.
3261      *//*
3262     private native java.security.ProtectionDomain getProtectionDomain0();
3263     */
3264 
3265     /*
3266      * Return the runtime's Class object for the named
3267      * primitive type.
3268      */
3269     @FastNative
getPrimitiveClass(String name)3270     static native Class<?> getPrimitiveClass(String name);
3271 
3272     // Android-removed: Remove unused method.
3273     /*
3274      * Check if client is allowed to access members.  If access is denied,
3275      * throw a SecurityException.
3276      *
3277      * This method also enforces package access.
3278      *
3279      * <p> Default policy: allow all clients access with normal Java access
3280      * control.
3281      *
3282      * <p> NOTE: should only be called if a SecurityManager is installed
3283      *
3284     private void checkMemberAccess(@SuppressWarnings("removal") SecurityManager sm, int which,
3285                                    Class<?> caller, boolean checkProxyInterfaces) {
3286         *//* Default policy allows access to all {@link Member#PUBLIC} members,
3287          * as well as access to classes that have the same class loader as the caller.
3288          * In all other cases, it requires RuntimePermission("accessDeclaredMembers")
3289          * permission.
3290          *//*
3291         final ClassLoader ccl = ClassLoader.getClassLoader(caller);
3292         if (which != Member.PUBLIC) {
3293             final ClassLoader cl = getClassLoader0();
3294             if (ccl != cl) {
3295                 sm.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
3296             }
3297         }
3298         this.checkPackageAccess(sm, ccl, checkProxyInterfaces);
3299     }
3300 
3301     /*
3302      * Checks if a client loaded in ClassLoader ccl is allowed to access this
3303      * class under the current package access policy. If access is denied,
3304      * throw a SecurityException.
3305      *
3306      * NOTE: this method should only be called if a SecurityManager is active
3307      *
3308     private void checkPackageAccess(@SuppressWarnings("removal") SecurityManager sm, final ClassLoader ccl,
3309                                     boolean checkProxyInterfaces) {
3310         final ClassLoader cl = getClassLoader0();
3311 
3312         if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
3313             String pkg = this.getPackageName();
3314             if (!pkg.isEmpty()) {
3315                 // skip the package access check on a proxy class in default proxy package
3316                 if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {
3317                     sm.checkPackageAccess(pkg);
3318                 }
3319             }
3320         }
3321         // check package access on the proxy interfaces
3322         if (checkProxyInterfaces && Proxy.isProxyClass(this)) {
3323             ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());
3324         }
3325     }
3326     */
3327 
3328     /*
3329      * Checks if a client loaded in ClassLoader ccl is allowed to access the provided
3330      * classes under the current package access policy. If access is denied,
3331      * throw a SecurityException.
3332      *
3333      * NOTE: this method should only be called if a SecurityManager is active
3334      *       classes must be non-empty
3335      *       all classes provided must be loaded by the same ClassLoader
3336      * NOTE: this method does not support Proxy classes
3337      *//*
3338     private static void checkPackageAccessForPermittedSubclasses(@SuppressWarnings("removal") SecurityManager sm,
3339                                     final ClassLoader ccl, Class<?>[] subClasses) {
3340         final ClassLoader cl = subClasses[0].getClassLoader0();
3341 
3342         if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
3343             Set<String> packages = new HashSet<>();
3344 
3345             for (Class<?> c : subClasses) {
3346                 if (Proxy.isProxyClass(c))
3347                     throw new InternalError("a permitted subclass should not be a proxy class: " + c);
3348                 String pkg = c.getPackageName();
3349                 if (!pkg.isEmpty()) {
3350                     packages.add(pkg);
3351                 }
3352             }
3353             for (String pkg : packages) {
3354                 sm.checkPackageAccess(pkg);
3355             }
3356         }
3357     }
3358     */
3359 
3360     /**
3361      * Add a package name prefix if the name is not absolute. Remove leading "/"
3362      * if name is absolute
3363      */
resolveName(String name)3364     private String resolveName(String name) {
3365         if (!name.startsWith("/")) {
3366             String baseName = getPackageName();
3367             if (!baseName.isEmpty()) {
3368                 int len = baseName.length() + 1 + name.length();
3369                 StringBuilder sb = new StringBuilder(len);
3370                 name = sb.append(baseName.replace('.', '/'))
3371                     .append('/')
3372                     .append(name)
3373                     .toString();
3374             }
3375         } else {
3376             name = name.substring(1);
3377         }
3378         return name;
3379     }
3380 
getConstructor0(Class<?>[] parameterTypes, int which)3381     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3382                                         int which) throws NoSuchMethodException
3383     {
3384         if (parameterTypes == null) {
3385             parameterTypes = EmptyArray.CLASS;
3386         }
3387         for (Class<?> c : parameterTypes) {
3388             if (c == null) {
3389                 throw new NoSuchMethodException("parameter type is null");
3390             }
3391         }
3392         Constructor<T> result = getDeclaredConstructorInternal(parameterTypes);
3393         if (result == null || which == Member.PUBLIC && !Modifier.isPublic(result.getAccessFlags())) {
3394             throw new NoSuchMethodException(getName() + ".<init> "
3395                     + Arrays.toString(parameterTypes));
3396         }
3397         return result;
3398     }
3399 
3400     /*
3401     /**
3402      * Atomic operations support.
3403      *//*
3404     private static class Atomic {
3405         // initialize Unsafe machinery here, since we need to call Class.class instance method
3406         // and have to avoid calling it in the static initializer of the Class class...
3407         private static final Unsafe unsafe = Unsafe.getUnsafe();
3408         // offset of Class.reflectionData instance field
3409         private static final long reflectionDataOffset
3410                 = unsafe.objectFieldOffset(Class.class, "reflectionData");
3411         // offset of Class.annotationType instance field
3412         private static final long annotationTypeOffset
3413                 = unsafe.objectFieldOffset(Class.class, "annotationType");
3414         // offset of Class.annotationData instance field
3415         private static final long annotationDataOffset
3416                 = unsafe.objectFieldOffset(Class.class, "annotationData");
3417 
3418         static <T> boolean casReflectionData(Class<?> clazz,
3419                                              SoftReference<ReflectionData<T>> oldData,
3420                                              SoftReference<ReflectionData<T>> newData) {
3421             return unsafe.compareAndSetReference(clazz, reflectionDataOffset, oldData, newData);
3422         }
3423 
3424         static boolean casAnnotationType(Class<?> clazz,
3425                                          AnnotationType oldType,
3426                                          AnnotationType newType) {
3427             return unsafe.compareAndSetReference(clazz, annotationTypeOffset, oldType, newType);
3428         }
3429 
3430         static boolean casAnnotationData(Class<?> clazz,
3431                                          AnnotationData oldData,
3432                                          AnnotationData newData) {
3433             return unsafe.compareAndSetReference(clazz, annotationDataOffset, oldData, newData);
3434         }
3435     }
3436 
3437     *//**
3438      * Reflection support.
3439      *//*
3440 
3441     // Reflection data caches various derived names and reflective members. Cached
3442     // values may be invalidated when JVM TI RedefineClasses() is called
3443     private static class ReflectionData<T> {
3444         volatile Field[] declaredFields;
3445         volatile Field[] publicFields;
3446         volatile Method[] declaredMethods;
3447         volatile Method[] publicMethods;
3448         volatile Constructor<T>[] declaredConstructors;
3449         volatile Constructor<T>[] publicConstructors;
3450         // Intermediate results for getFields and getMethods
3451         volatile Field[] declaredPublicFields;
3452         volatile Method[] declaredPublicMethods;
3453         volatile Class<?>[] interfaces;
3454 
3455         // Cached names
3456         String simpleName;
3457         String canonicalName;
3458         static final String NULL_SENTINEL = new String();
3459 
3460         // Value of classRedefinedCount when we created this ReflectionData instance
3461         final int redefinedCount;
3462 
3463         ReflectionData(int redefinedCount) {
3464             this.redefinedCount = redefinedCount;
3465         }
3466     }
3467 
3468     private transient volatile SoftReference<ReflectionData<T>> reflectionData;
3469 
3470     // Incremented by the VM on each call to JVM TI RedefineClasses()
3471     // that redefines this class or a superclass.
3472     private transient volatile int classRedefinedCount;
3473 
3474     // Lazily create and cache ReflectionData
3475     private ReflectionData<T> reflectionData() {
3476         SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
3477         int classRedefinedCount = this.classRedefinedCount;
3478         ReflectionData<T> rd;
3479         if (reflectionData != null &&
3480             (rd = reflectionData.get()) != null &&
3481             rd.redefinedCount == classRedefinedCount) {
3482             return rd;
3483         }
3484         // else no SoftReference or cleared SoftReference or stale ReflectionData
3485         // -> create and replace new instance
3486         return newReflectionData(reflectionData, classRedefinedCount);
3487     }
3488 
3489     private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
3490                                                 int classRedefinedCount) {
3491         while (true) {
3492             ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
3493             // try to CAS it...
3494             if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
3495                 return rd;
3496             }
3497             // else retry
3498             oldReflectionData = this.reflectionData;
3499             classRedefinedCount = this.classRedefinedCount;
3500             if (oldReflectionData != null &&
3501                 (rd = oldReflectionData.get()) != null &&
3502                 rd.redefinedCount == classRedefinedCount) {
3503                 return rd;
3504             }
3505         }
3506     }
3507 
3508     // Generic signature handling
3509     private native String getGenericSignature0();
3510 
3511     // Generic info repository; lazily initialized
3512     private transient volatile ClassRepository genericInfo;
3513 
3514     // accessor for factory
3515     private GenericsFactory getFactory() {
3516         // create scope and factory
3517         return CoreReflectionFactory.make(this, ClassScope.make(this));
3518     }
3519 
3520     // accessor for generic info repository;
3521     // generic info is lazily initialized
3522     private ClassRepository getGenericInfo() {
3523         ClassRepository genericInfo = this.genericInfo;
3524         if (genericInfo == null) {
3525             String signature = getGenericSignature0();
3526             if (signature == null) {
3527                 genericInfo = ClassRepository.NONE;
3528             } else {
3529                 genericInfo = ClassRepository.make(signature, getFactory());
3530             }
3531             this.genericInfo = genericInfo;
3532         }
3533         return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
3534     }
3535 
3536     // Annotations handling
3537     native byte[] getRawAnnotations();
3538     // Since 1.8
3539     native byte[] getRawTypeAnnotations();
3540     static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
3541         return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
3542     }
3543 
3544     native ConstantPool getConstantPool();
3545 
3546     //
3547     //
3548     // java.lang.reflect.Field handling
3549     //
3550     //
3551 
3552     // Returns an array of "root" fields. These Field objects must NOT
3553     // be propagated to the outside world, but must instead be copied
3554     // via ReflectionFactory.copyField.
3555     private Field[] privateGetDeclaredFields(boolean publicOnly) {
3556         Field[] res;
3557         ReflectionData<T> rd = reflectionData();
3558         if (rd != null) {
3559             res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
3560             if (res != null) return res;
3561         }
3562         // No cached value available; request value from VM
3563         res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
3564         if (rd != null) {
3565             if (publicOnly) {
3566                 rd.declaredPublicFields = res;
3567             } else {
3568                 rd.declaredFields = res;
3569             }
3570         }
3571         return res;
3572     }
3573 
3574     // Returns an array of "root" fields. These Field objects must NOT
3575     // be propagated to the outside world, but must instead be copied
3576     // via ReflectionFactory.copyField.
3577     private Field[] privateGetPublicFields() {
3578         Field[] res;
3579         ReflectionData<T> rd = reflectionData();
3580         if (rd != null) {
3581             res = rd.publicFields;
3582             if (res != null) return res;
3583         }
3584 
3585         // Use a linked hash set to ensure order is preserved and
3586         // fields from common super interfaces are not duplicated
3587         LinkedHashSet<Field> fields = new LinkedHashSet<>();
3588 
3589         // Local fields
3590         addAll(fields, privateGetDeclaredFields(true));
3591 
3592         // Direct superinterfaces, recursively
3593         for (Class<?> si : getInterfaces()) {
3594             addAll(fields, si.privateGetPublicFields());
3595         }
3596 
3597         // Direct superclass, recursively
3598         Class<?> sc = getSuperclass();
3599         if (sc != null) {
3600             addAll(fields, sc.privateGetPublicFields());
3601         }
3602 
3603         res = fields.toArray(new Field[0]);
3604         if (rd != null) {
3605             rd.publicFields = res;
3606         }
3607         return res;
3608     }
3609 
3610     private static void addAll(Collection<Field> c, Field[] o) {
3611         for (Field f : o) {
3612             c.add(f);
3613         }
3614     }
3615 
3616 
3617     //
3618     //
3619     // java.lang.reflect.Constructor handling
3620     //
3621     //
3622 
3623     // Returns an array of "root" constructors. These Constructor
3624     // objects must NOT be propagated to the outside world, but must
3625     // instead be copied via ReflectionFactory.copyConstructor.
3626     private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
3627         Constructor<T>[] res;
3628         ReflectionData<T> rd = reflectionData();
3629         if (rd != null) {
3630             res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
3631             if (res != null) return res;
3632         }
3633         // No cached value available; request value from VM
3634         if (isInterface()) {
3635             @SuppressWarnings("unchecked")
3636             Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
3637             res = temporaryRes;
3638         } else {
3639             res = getDeclaredConstructors0(publicOnly);
3640         }
3641         if (rd != null) {
3642             if (publicOnly) {
3643                 rd.publicConstructors = res;
3644             } else {
3645                 rd.declaredConstructors = res;
3646             }
3647         }
3648         return res;
3649     }
3650 
3651     //
3652     //
3653     // java.lang.reflect.Method handling
3654     //
3655     //
3656 
3657     // Returns an array of "root" methods. These Method objects must NOT
3658     // be propagated to the outside world, but must instead be copied
3659     // via ReflectionFactory.copyMethod.
3660     private Method[] privateGetDeclaredMethods(boolean publicOnly) {
3661         Method[] res;
3662         ReflectionData<T> rd = reflectionData();
3663         if (rd != null) {
3664             res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
3665             if (res != null) return res;
3666         }
3667         // No cached value available; request value from VM
3668         res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
3669         if (rd != null) {
3670             if (publicOnly) {
3671                 rd.declaredPublicMethods = res;
3672             } else {
3673                 rd.declaredMethods = res;
3674             }
3675         }
3676         return res;
3677     }
3678 
3679     // Returns an array of "root" methods. These Method objects must NOT
3680     // be propagated to the outside world, but must instead be copied
3681     // via ReflectionFactory.copyMethod.
3682     private Method[] privateGetPublicMethods() {
3683         Method[] res;
3684         ReflectionData<T> rd = reflectionData();
3685         if (rd != null) {
3686             res = rd.publicMethods;
3687             if (res != null) return res;
3688         }
3689 
3690         // No cached value available; compute value recursively.
3691         // Start by fetching public declared methods...
3692         PublicMethods pms = new PublicMethods();
3693         for (Method m : privateGetDeclaredMethods(*//* publicOnly *//* true)) {
3694             pms.merge(m);
3695         }
3696         // ...then recur over superclass methods...
3697         Class<?> sc = getSuperclass();
3698         if (sc != null) {
3699             for (Method m : sc.privateGetPublicMethods()) {
3700                 pms.merge(m);
3701             }
3702         }
3703         // ...and finally over direct superinterfaces.
3704         for (Class<?> intf : getInterfaces(*//* cloneArray *//* false)) {
3705             for (Method m : intf.privateGetPublicMethods()) {
3706                 // static interface methods are not inherited
3707                 if (!Modifier.isStatic(m.getModifiers())) {
3708                     pms.merge(m);
3709                 }
3710             }
3711         }
3712 
3713         res = pms.toArray();
3714         if (rd != null) {
3715             rd.publicMethods = res;
3716         }
3717         return res;
3718     }
3719 
3720 
3721     //
3722     // Helpers for fetchers of one field, method, or constructor
3723     //
3724 
3725     // This method does not copy the returned Field object!
3726     private static Field searchFields(Field[] fields, String name) {
3727         for (Field field : fields) {
3728             if (field.getName().equals(name)) {
3729                 return field;
3730             }
3731         }
3732         return null;
3733     }
3734 
3735     // Returns a "root" Field object. This Field object must NOT
3736     // be propagated to the outside world, but must instead be copied
3737     // via ReflectionFactory.copyField.
3738     private Field getField0(String name) {
3739         // Note: the intent is that the search algorithm this routine
3740         // uses be equivalent to the ordering imposed by
3741         // privateGetPublicFields(). It fetches only the declared
3742         // public fields for each class, however, to reduce the number
3743         // of Field objects which have to be created for the common
3744         // case where the field being requested is declared in the
3745         // class which is being queried.
3746         Field res;
3747         // Search declared public fields
3748         if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
3749             return res;
3750         }
3751         // Direct superinterfaces, recursively
3752         Class<?>[] interfaces = getInterfaces(*//* cloneArray *//* false);
3753         for (Class<?> c : interfaces) {
3754             if ((res = c.getField0(name)) != null) {
3755                 return res;
3756             }
3757         }
3758         // Direct superclass, recursively
3759         if (!isInterface()) {
3760             Class<?> c = getSuperclass();
3761             if (c != null) {
3762                 if ((res = c.getField0(name)) != null) {
3763                     return res;
3764                 }
3765             }
3766         }
3767         return null;
3768     }
3769 
3770     // This method does not copy the returned Method object!
3771     private static Method searchMethods(Method[] methods,
3772                                         String name,
3773                                         Class<?>[] parameterTypes)
3774     {
3775         ReflectionFactory fact = getReflectionFactory();
3776         Method res = null;
3777         for (Method m : methods) {
3778             if (m.getName().equals(name)
3779                 && arrayContentsEq(parameterTypes,
3780                                    fact.getExecutableSharedParameterTypes(m))
3781                 && (res == null
3782                     || (res.getReturnType() != m.getReturnType()
3783                         && res.getReturnType().isAssignableFrom(m.getReturnType()))))
3784                 res = m;
3785         }
3786         return res;
3787     }
3788 
3789     private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
3790 
3791     // Returns a "root" Method object. This Method object must NOT
3792     // be propagated to the outside world, but must instead be copied
3793     // via ReflectionFactory.copyMethod.
3794     private Method getMethod0(String name, Class<?>[] parameterTypes) {
3795         PublicMethods.MethodList res = getMethodsRecursive(
3796             name,
3797             parameterTypes == null ? EMPTY_CLASS_ARRAY : parameterTypes,
3798             *//* includeStatic *//* true);
3799         return res == null ? null : res.getMostSpecific();
3800     }
3801 
3802     // Returns a list of "root" Method objects. These Method objects must NOT
3803     // be propagated to the outside world, but must instead be copied
3804     // via ReflectionFactory.copyMethod.
3805     private PublicMethods.MethodList getMethodsRecursive(String name,
3806                                                          Class<?>[] parameterTypes,
3807                                                          boolean includeStatic) {
3808         // 1st check declared public methods
3809         Method[] methods = privateGetDeclaredMethods(*//* publicOnly *//* true);
3810         PublicMethods.MethodList res = PublicMethods.MethodList
3811             .filter(methods, name, parameterTypes, includeStatic);
3812         // if there is at least one match among declared methods, we need not
3813         // search any further as such match surely overrides matching methods
3814         // declared in superclass(es) or interface(s).
3815         if (res != null) {
3816             return res;
3817         }
3818 
3819         // if there was no match among declared methods,
3820         // we must consult the superclass (if any) recursively...
3821         Class<?> sc = getSuperclass();
3822         if (sc != null) {
3823             res = sc.getMethodsRecursive(name, parameterTypes, includeStatic);
3824         }
3825 
3826         // ...and coalesce the superclass methods with methods obtained
3827         // from directly implemented interfaces excluding static methods...
3828         for (Class<?> intf : getInterfaces(*//* cloneArray *//* false)) {
3829             res = PublicMethods.MethodList.merge(
3830                 res, intf.getMethodsRecursive(name, parameterTypes,
3831                                               *//* includeStatic *//* false));
3832         }
3833 
3834         return res;
3835     }
3836 
3837     // Returns a "root" Constructor object. This Constructor object must NOT
3838     // be propagated to the outside world, but must instead be copied
3839     // via ReflectionFactory.copyConstructor.
3840     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3841                                         int which) throws NoSuchMethodException
3842     {
3843         ReflectionFactory fact = getReflectionFactory();
3844         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3845         for (Constructor<T> constructor : constructors) {
3846             if (arrayContentsEq(parameterTypes,
3847                                 fact.getExecutableSharedParameterTypes(constructor))) {
3848                 return constructor;
3849             }
3850         }
3851         throw new NoSuchMethodException(methodToString("<init>", parameterTypes));
3852     }
3853 
3854     //
3855     // Other helpers and base implementation
3856     //
3857 
3858     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3859         if (a1 == null) {
3860             return a2 == null || a2.length == 0;
3861         }
3862 
3863         if (a2 == null) {
3864             return a1.length == 0;
3865         }
3866 
3867         if (a1.length != a2.length) {
3868             return false;
3869         }
3870 
3871         for (int i = 0; i < a1.length; i++) {
3872             if (a1[i] != a2[i]) {
3873                 return false;
3874             }
3875         }
3876 
3877         return true;
3878     }
3879 
3880     private static Field[] copyFields(Field[] arg) {
3881         Field[] out = new Field[arg.length];
3882         ReflectionFactory fact = getReflectionFactory();
3883         for (int i = 0; i < arg.length; i++) {
3884             out[i] = fact.copyField(arg[i]);
3885         }
3886         return out;
3887     }
3888 
3889     private static Method[] copyMethods(Method[] arg) {
3890         Method[] out = new Method[arg.length];
3891         ReflectionFactory fact = getReflectionFactory();
3892         for (int i = 0; i < arg.length; i++) {
3893             out[i] = fact.copyMethod(arg[i]);
3894         }
3895         return out;
3896     }
3897 
3898     private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
3899         Constructor<U>[] out = arg.clone();
3900         ReflectionFactory fact = getReflectionFactory();
3901         for (int i = 0; i < out.length; i++) {
3902             out[i] = fact.copyConstructor(out[i]);
3903         }
3904         return out;
3905     }
3906 
3907     private native Field[]       getDeclaredFields0(boolean publicOnly);
3908     private native Method[]      getDeclaredMethods0(boolean publicOnly);
3909     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3910     private native Class<?>[]    getDeclaredClasses0();
3911 
3912     */
3913 
3914     /*
3915      * Returns an array containing the components of the Record attribute,
3916      * or null if the attribute is not present.
3917      *
3918      * Note that this method returns non-null array on a class with
3919      * the Record attribute even if this class is not a record.
3920      */
3921     // BEGIN Android-changed: Re-implement getRecordComponents0() on ART.
3922     // private native RecordComponent[] getRecordComponents0();
getRecordComponents0()3923     private RecordComponent[] getRecordComponents0() {
3924         RecordComponents libcoreComponents = new RecordComponents(this);
3925 
3926         // Every component should have a type and a name.
3927         String[] names = libcoreComponents.getNames();
3928         Class<?>[] types = libcoreComponents.getTypes();
3929         if (names == null || types == null) {
3930             // Return non-null array as per getRecordComponent() javadoc if isRecord()
3931             // returns true.
3932             return new RecordComponent[0];
3933         }
3934 
3935         // class_linker.cc should verify that names and types have the same length, or otherwise,
3936         // the class isn't loaded.
3937         int size = Math.min(names.length, types.length);
3938         RecordComponent[] components = new RecordComponent[size];
3939         for (int i = 0; i < size; i++) {
3940             String name = names[i];
3941             Class<?> type = types[i];
3942             components[i] = new RecordComponent(this, name, type, libcoreComponents, i);
3943         }
3944         return components;
3945     }
3946 
3947     /**
3948      * Used by {@link libcore.reflect.RecordComponents}
3949      *
3950      * @hide
3951      */
3952     @FastNative
getRecordAnnotationElement(String elementName, Class<T2[]> arrayClass)3953     public native <T2> T2[] getRecordAnnotationElement(String elementName, Class<T2[]> arrayClass);
3954     // END Android-changed: Re-implement getRecordComponents0() on ART.
3955 
3956     @FastNative
isRecord0()3957     private native boolean       isRecord0();
3958 
3959     /**
3960      * Helper method to get the method name from arguments.
3961      *//*
3962     private String methodToString(String name, Class<?>[] argTypes) {
3963         return getName() + '.' + name +
3964                 ((argTypes == null || argTypes.length == 0) ?
3965                 "()" :
3966                 Arrays.stream(argTypes)
3967                         .map(c -> c == null ? "null" : c.getName())
3968                         .collect(Collectors.joining(",", "(", ")")));
3969     }
3970     */
3971 
3972     /** use serialVersionUID from JDK 1.1 for interoperability */
3973     @java.io.Serial
3974     private static final long serialVersionUID = 3206093459760846163L;
3975 
3976 
3977     /**
3978      * Returns the constructor with the given parameters if it is defined by this class;
3979      * {@code null} otherwise. This may return a non-public member.
3980      *
3981      * @param args the types of the parameters to the constructor.
3982      */
3983     @FastNative
getDeclaredConstructorInternal(Class<?>[] args)3984     private native Constructor<T> getDeclaredConstructorInternal(Class<?>[] args);
3985 
3986     /**
3987      * Returns the assertion status that would be assigned to this
3988      * class if it were to be initialized at the time this method is invoked.
3989      * If this class has had its assertion status set, the most recent
3990      * setting will be returned; otherwise, if any package default assertion
3991      * status pertains to this class, the most recent setting for the most
3992      * specific pertinent package default assertion status is returned;
3993      * otherwise, if this class is not a system class (i.e., it has a
3994      * class loader) its class loader's default assertion status is returned;
3995      * otherwise, the system class default assertion status is returned.
3996      *
3997      * @apiNote
3998      * Few programmers will have any need for this method; it is provided
3999      * for the benefit of the JDK itself.  (It allows a class to determine at
4000      * the time that it is initialized whether assertions should be enabled.)
4001      * Note that this method is not guaranteed to return the actual
4002      * assertion status that was (or will be) associated with the specified
4003      * class when it was (or will be) initialized.
4004      *
4005      * Android-note: AssertionStatuses are unsupported. This method will always return false.
4006      *
4007      * @return the desired assertion status of the specified class.
4008      * @see    java.lang.ClassLoader#setClassAssertionStatus
4009      * @see    java.lang.ClassLoader#setPackageAssertionStatus
4010      * @see    java.lang.ClassLoader#setDefaultAssertionStatus
4011      * @since  1.4
4012      */
desiredAssertionStatus()4013     public boolean desiredAssertionStatus() {
4014         // Android-changaed: AssertionStatuses are unsupported.
4015         return false;
4016     }
4017 
4018     /**
4019      * Returns the simple name of a member or local class, or {@code null} otherwise.
4020      */
4021     @FastNative
getSimpleNameNative()4022     private native String getSimpleNameNative();
4023 
4024     @FastNative
getInnerClassFlags(int defaultValue)4025     private native int getInnerClassFlags(int defaultValue);
4026 
4027     /**
4028      * Returns true if and only if this class was declared as an enum in the
4029      * source code.
4030      *
4031      * Note that {@link java.lang.Enum} is not itself an enum class.
4032      *
4033      * Also note that if an enum constant is declared with a class body,
4034      * the class of that enum constant object is an anonymous class
4035      * and <em>not</em> the class of the declaring enum class. The
4036      * {@link Enum#getDeclaringClass} method of an enum constant can
4037      * be used to get the class of the enum class declaring the
4038      * constant.
4039      *
4040      * @return true if and only if this class was declared as an enum in the
4041      *     source code
4042      * @since 1.5
4043      * @jls 8.9.1 Enum Constants
4044      */
isEnum()4045     public boolean isEnum() {
4046         // An enum must both directly extend java.lang.Enum and have
4047         // the ENUM bit set; classes for specialized enum constants
4048         // don't do the former.
4049         return (this.getModifiers() & ENUM) != 0 &&
4050         this.getSuperclass() == java.lang.Enum.class;
4051     }
4052 
4053     /**
4054      * Returns {@code true} if and only if this class is a record class.
4055      *
4056      * <p> The {@linkplain #getSuperclass() direct superclass} of a record
4057      * class is {@code java.lang.Record}. A record class is {@linkplain
4058      * Modifier#FINAL final}. A record class has (possibly zero) record
4059      * components; {@link #getRecordComponents()} returns a non-null but
4060      * possibly empty value for a record.
4061      *
4062      * <p> Note that class {@link Record} is not a record class and thus
4063      * invoking this method on class {@code Record} returns {@code false}.
4064      *
4065      * @return true if and only if this class is a record class, otherwise false
4066      * @jls 8.10 Record Classes
4067      * @since 16
4068      */
isRecord()4069     public boolean isRecord() {
4070         // this superclass and final modifier check is not strictly necessary
4071         // they are intrinsified and serve as a fast-path check
4072         return getSuperclass() == java.lang.Record.class &&
4073                 (this.getModifiers() & Modifier.FINAL) != 0 &&
4074                 isRecord0();
4075     }
4076 
4077     // Android-remvoed: Remove unsupported ReflectionFactory.
4078     /*
4079     // Fetches the factory for reflective objects
4080     @SuppressWarnings("removal")
4081     private static ReflectionFactory getReflectionFactory() {
4082         if (reflectionFactory == null) {
4083             reflectionFactory =
4084                 java.security.AccessController.doPrivileged
4085                     (new ReflectionFactory.GetReflectionFactoryAction());
4086         }
4087         return reflectionFactory;
4088     }
4089     private static ReflectionFactory reflectionFactory;
4090     */
4091 
4092     /**
4093      * Returns the elements of this enum class or null if this
4094      * Class object does not represent an enum class.
4095      *
4096      * @return an array containing the values comprising the enum class
4097      *     represented by this {@code Class} object in the order they're
4098      *     declared, or null if this {@code Class} object does not
4099      *     represent an enum class
4100      * @since 1.5
4101      * @jls 8.9.1 Enum Constants
4102      */
getEnumConstants()4103     public T[] getEnumConstants() {
4104         T[] values = getEnumConstantsShared();
4105         return (values != null) ? values.clone() : null;
4106     }
4107 
4108     // Android-changed: Made public/hidden instead of using sun.misc.SharedSecrets.
4109     /**
4110      * Returns the elements of this enum class or null if this
4111      * Class object does not represent an enum class;
4112      * identical to getEnumConstants except that the result is
4113      * uncloned, cached, and shared by all callers.
4114      * @hide
4115      */
getEnumConstantsShared()4116     public T[] getEnumConstantsShared() {
4117         if (!isEnum()) return null;
4118         return (T[]) Enum.getSharedConstants((Class) this);
4119     }
4120 
4121     /*
4122     @SuppressWarnings("removal")
4123     T[] getEnumConstantsShared() {
4124         T[] constants = enumConstants;
4125         if (constants == null) {
4126             if (!isEnum()) return null;
4127             try {
4128                 final Method values = getMethod("values");
4129                 java.security.AccessController.doPrivileged(
4130                     new java.security.PrivilegedAction<>() {
4131                         public Void run() {
4132                                 values.setAccessible(true);
4133                                 return null;
4134                             }
4135                         });
4136                 @SuppressWarnings("unchecked")
4137                 T[] temporaryConstants = (T[])values.invoke(null);
4138                 enumConstants = constants = temporaryConstants;
4139             }
4140             // These can happen when users concoct enum-like classes
4141             // that don't comply with the enum spec.
4142             catch (InvocationTargetException | NoSuchMethodException |
4143                    IllegalAccessException ex) { return null; }
4144         }
4145         return constants;
4146     }
4147     private transient volatile T[] enumConstants;
4148     */
4149 
4150     // Android-removed: Remove unused method.
4151     /*
4152     *//**
4153      * Returns a map from simple name to enum constant.  This package-private
4154      * method is used internally by Enum to implement
4155      * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}
4156      * efficiently.  Note that the map is returned by this method is
4157      * created lazily on first use.  Typically it won't ever get created.
4158      *//*
4159     Map<String, T> enumConstantDirectory() {
4160         Map<String, T> directory = enumConstantDirectory;
4161         if (directory == null) {
4162             T[] universe = getEnumConstantsShared();
4163             if (universe == null)
4164                 throw new IllegalArgumentException(
4165                     getName() + " is not an enum class");
4166             directory = new HashMap<>((int)(universe.length / 0.75f) + 1);
4167             for (T constant : universe) {
4168                 directory.put(((Enum<?>)constant).name(), constant);
4169             }
4170             enumConstantDirectory = directory;
4171         }
4172         return directory;
4173     }
4174     private transient volatile Map<String, T> enumConstantDirectory;
4175     */
4176 
4177     /**
4178      * Casts an object to the class or interface represented
4179      * by this {@code Class} object.
4180      *
4181      * @param obj the object to be cast
4182      * @return the object after casting, or null if obj is null
4183      *
4184      * @throws ClassCastException if the object is not
4185      * null and is not assignable to the type T.
4186      *
4187      * @since 1.5
4188      */
4189     @SuppressWarnings("unchecked")
4190     @IntrinsicCandidate
cast(Object obj)4191     public T cast(Object obj) {
4192         if (obj != null && !isInstance(obj))
4193             throw new ClassCastException(cannotCastMsg(obj));
4194         return (T) obj;
4195     }
4196 
cannotCastMsg(Object obj)4197     private String cannotCastMsg(Object obj) {
4198         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
4199     }
4200 
4201     /**
4202      * Casts this {@code Class} object to represent a subclass of the class
4203      * represented by the specified class object.  Checks that the cast
4204      * is valid, and throws a {@code ClassCastException} if it is not.  If
4205      * this method succeeds, it always returns a reference to this {@code Class} object.
4206      *
4207      * <p>This method is useful when a client needs to "narrow" the type of
4208      * a {@code Class} object to pass it to an API that restricts the
4209      * {@code Class} objects that it is willing to accept.  A cast would
4210      * generate a compile-time warning, as the correctness of the cast
4211      * could not be checked at runtime (because generic types are implemented
4212      * by erasure).
4213      *
4214      * @param <U> the type to cast this {@code Class} object to
4215      * @param clazz the class of the type to cast this {@code Class} object to
4216      * @return this {@code Class} object, cast to represent a subclass of
4217      *    the specified class object.
4218      * @throws ClassCastException if this {@code Class} object does not
4219      *    represent a subclass of the specified class (here "subclass" includes
4220      *    the class itself).
4221      * @since 1.5
4222      */
4223     @SuppressWarnings("unchecked")
asSubclass(Class<U> clazz)4224     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
4225         if (clazz.isAssignableFrom(this))
4226             return (Class<? extends U>) this;
4227         else
4228             throw new ClassCastException(this.toString() +
4229                 " cannot be cast to " + clazz.getName());
4230     }
4231 
4232     /**
4233      * {@inheritDoc}
4234      * <p>Note that any annotation returned by this method is a
4235      * declaration annotation.
4236      *
4237      * @throws NullPointerException {@inheritDoc}
4238      * @since 1.5
4239      */
4240     @Override
4241     @SuppressWarnings("unchecked")
getAnnotation(Class<A> annotationClass)4242     public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
4243         Objects.requireNonNull(annotationClass);
4244 
4245         A annotation = getDeclaredAnnotation(annotationClass);
4246         if (annotation != null) {
4247             return annotation;
4248         }
4249 
4250         if (annotationClass.isDeclaredAnnotationPresent(Inherited.class)) {
4251             for (Class<?> sup = getSuperclass(); sup != null; sup = sup.getSuperclass()) {
4252                 annotation = sup.getDeclaredAnnotation(annotationClass);
4253                 if (annotation != null) {
4254                     return annotation;
4255                 }
4256             }
4257         }
4258 
4259         return null;
4260     }
4261 
4262     /**
4263      * {@inheritDoc}
4264      * @throws NullPointerException {@inheritDoc}
4265      * @since 1.5
4266      */
4267     @Override
isAnnotationPresent(Class<? extends Annotation> annotationClass)4268     public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
4269         if (annotationClass == null) {
4270             throw new NullPointerException("annotationClass == null");
4271         }
4272 
4273         if (isDeclaredAnnotationPresent(annotationClass)) {
4274             return true;
4275         }
4276 
4277         if (annotationClass.isDeclaredAnnotationPresent(Inherited.class)) {
4278             for (Class<?> sup = getSuperclass(); sup != null; sup = sup.getSuperclass()) {
4279                 if (sup.isDeclaredAnnotationPresent(annotationClass)) {
4280                     return true;
4281                 }
4282             }
4283         }
4284 
4285         return false;
4286     }
4287 
4288     /**
4289      * {@inheritDoc}
4290      * <p>Note that any annotations returned by this method are
4291      * declaration annotations.
4292      *
4293      * @throws NullPointerException {@inheritDoc}
4294      * @since 1.8
4295      */
4296     @Override
getAnnotationsByType(Class<A> annotationClass)4297     public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {
4298       // Find any associated annotations [directly or repeatably (indirectly) present on this].
4299       A[] annotations = GenericDeclaration.super.getAnnotationsByType(annotationClass);
4300 
4301       if (annotations.length != 0) {
4302         return annotations;
4303       }
4304 
4305       // Nothing was found, attempt looking for associated annotations recursively up to the root
4306       // class if and only if:
4307       // * The annotation class was marked with @Inherited.
4308       //
4309       // Inherited annotations are not coalesced into a single set: the first declaration found is
4310       // returned.
4311 
4312       if (annotationClass.isDeclaredAnnotationPresent(Inherited.class)) {
4313         Class<?> superClass = getSuperclass();  // Returns null if klass's base is Object.
4314         if (superClass != null) {
4315           return superClass.getAnnotationsByType(annotationClass);
4316         }
4317       }
4318 
4319       // Annotated was not marked with @Inherited, or no superclass.
4320       return (A[]) Array.newInstance(annotationClass, 0);  // Safe by construction.
4321     }
4322 
4323     /**
4324      * {@inheritDoc}
4325      * <p>Note that any annotations returned by this method are
4326      * declaration annotations.
4327      *
4328      * @throws NullPointerException {@inheritDoc}
4329      * @since 1.8
4330      */
4331     @Override
getDeclaredAnnotationsByType(Class<A> annotationClass)4332     public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {
4333         Objects.requireNonNull(annotationClass);
4334 
4335         // Android-changed: Altered method implementation for getDeclaredAnnotationsByType(Class).
4336         // return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,
4337         //     annotationClass);
4338         return GenericDeclaration.super.getDeclaredAnnotationsByType(annotationClass);
4339     }
4340 
4341     /**
4342      * {@inheritDoc}
4343      * <p>Note that any annotations returned by this method are
4344      * declaration annotations.
4345      *
4346      * @since 1.5
4347      */
4348     @Override
getAnnotations()4349     public Annotation[] getAnnotations() {
4350         // Android-changed: ART reads annotations from dex files.
4351         // return AnnotationParser.toArray(annotationData().annotations);
4352         /*
4353          * We need to get the annotations declared on this class, plus the
4354          * annotations from superclasses that have the "@Inherited" annotation
4355          * set.  We create a temporary map to use while we accumulate the
4356          * annotations and convert it to an array at the end.
4357          *
4358          * It's possible to have duplicates when annotations are inherited.
4359          * We use a Map to filter those out.
4360          *
4361          * HashMap might be overkill here.
4362          */
4363         HashMap<Class<?>, Annotation> map = new HashMap<Class<?>, Annotation>();
4364         for (Annotation declaredAnnotation : getDeclaredAnnotations()) {
4365             map.put(declaredAnnotation.annotationType(), declaredAnnotation);
4366         }
4367         for (Class<?> sup = getSuperclass(); sup != null; sup = sup.getSuperclass()) {
4368             for (Annotation declaredAnnotation : sup.getDeclaredAnnotations()) {
4369                 Class<? extends Annotation> clazz = declaredAnnotation.annotationType();
4370                 if (!map.containsKey(clazz) && clazz.isDeclaredAnnotationPresent(Inherited.class)) {
4371                     map.put(clazz, declaredAnnotation);
4372                 }
4373             }
4374         }
4375 
4376         /* Convert annotation values from HashMap to array. */
4377         Collection<Annotation> coll = map.values();
4378         return coll.toArray(new Annotation[coll.size()]);
4379     }
4380 
4381     /**
4382      * {@inheritDoc}
4383      * <p>Note that any annotation returned by this method is a
4384      * declaration annotation.
4385      *
4386      * @throws NullPointerException {@inheritDoc}
4387      * @since 1.5
4388      */
4389     // Android-changed: Re-implement on top of ART.
4390     /*
4391     @SuppressWarnings("unchecked")
4392     public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
4393         Objects.requireNonNull(annotationClass);
4394 
4395         return (A) annotationData().declaredAnnotations.get(annotationClass);
4396     }
4397     */
4398     @Override
4399     @FastNative
getDeclaredAnnotation(Class<A> annotationClass)4400     public native <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass);
4401 
4402 
4403     /**
4404      * {@inheritDoc}
4405      * <p>Note that any annotations returned by this method are
4406      * declaration annotations.
4407      *
4408      * @since 1.5
4409      */
4410     /*
4411     public Annotation[] getDeclaredAnnotations()  {
4412         return AnnotationParser.toArray(annotationData().declaredAnnotations);
4413     }
4414     */
4415     @Override
4416     @FastNative
getDeclaredAnnotations()4417     public native Annotation[] getDeclaredAnnotations();
4418 
4419     // Android-removed: Remove unused fields and methods.
4420     /*
4421     // annotation data that might get invalidated when JVM TI RedefineClasses() is called
4422     private static class AnnotationData {
4423         final Map<Class<? extends Annotation>, Annotation> annotations;
4424         final Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
4425 
4426         // Value of classRedefinedCount when we created this AnnotationData instance
4427         final int redefinedCount;
4428 
4429         AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations,
4430                 Map<Class<? extends Annotation>, Annotation> declaredAnnotations,
4431                 int redefinedCount) {
4432             this.annotations = annotations;
4433             this.declaredAnnotations = declaredAnnotations;
4434             this.redefinedCount = redefinedCount;
4435         }
4436     }
4437 
4438     // Annotation interfaces cache their internal (AnnotationType) form
4439 
4440     @SuppressWarnings("UnusedDeclaration")
4441     private transient volatile AnnotationType annotationType;
4442 
4443     boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {
4444         return Atomic.casAnnotationType(this, oldType, newType);
4445     }
4446 
4447     AnnotationType getAnnotationType() {
4448         return annotationType;
4449     }
4450 
4451     Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() {
4452         return annotationData().declaredAnnotations;
4453     }
4454 
4455     *//* Backing store of user-defined values pertaining to this class.
4456      * Maintained by the ClassValue class.
4457      *//*
4458     transient ClassValue.ClassValueMap classValueMap;
4459     */
4460 
4461     // Android-changed: ART doesn't support AnnotatedType.
4462     /*
4463      * Returns an {@code AnnotatedType} object that represents the use of a
4464      * type to specify the superclass of the entity represented by this {@code
4465      * Class} object. (The <em>use</em> of type Foo to specify the superclass
4466      * in '...  extends Foo' is distinct from the <em>declaration</em> of class
4467      * Foo.)
4468      *
4469      * <p> If this {@code Class} object represents a class whose declaration
4470      * does not explicitly indicate an annotated superclass, then the return
4471      * value is an {@code AnnotatedType} object representing an element with no
4472      * annotations.
4473      *
4474      * <p> If this {@code Class} represents either the {@code Object} class, an
4475      * interface type, an array type, a primitive type, or void, the return
4476      * value is {@code null}.
4477      *
4478      * @return an object representing the superclass
4479      * @since 1.8
4480      *//*
4481     public AnnotatedType getAnnotatedSuperclass() {
4482         if (this == Object.class ||
4483                 isInterface() ||
4484                 isArray() ||
4485                 isPrimitive() ||
4486                 this == Void.TYPE) {
4487             return null;
4488         }
4489 
4490         return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
4491     }
4492 
4493      * Returns an array of {@code AnnotatedType} objects that represent the use
4494      * of types to specify superinterfaces of the entity represented by this
4495      * {@code Class} object. (The <em>use</em> of type Foo to specify a
4496      * superinterface in '... implements Foo' is distinct from the
4497      * <em>declaration</em> of interface Foo.)
4498      *
4499      * <p> If this {@code Class} object represents a class, the return value is
4500      * an array containing objects representing the uses of interface types to
4501      * specify interfaces implemented by the class. The order of the objects in
4502      * the array corresponds to the order of the interface types used in the
4503      * 'implements' clause of the declaration of this {@code Class} object.
4504      *
4505      * <p> If this {@code Class} object represents an interface, the return
4506      * value is an array containing objects representing the uses of interface
4507      * types to specify interfaces directly extended by the interface. The
4508      * order of the objects in the array corresponds to the order of the
4509      * interface types used in the 'extends' clause of the declaration of this
4510      * {@code Class} object.
4511      *
4512      * <p> If this {@code Class} object represents a class or interface whose
4513      * declaration does not explicitly indicate any annotated superinterfaces,
4514      * the return value is an array of length 0.
4515      *
4516      * <p> If this {@code Class} object represents either the {@code Object}
4517      * class, an array type, a primitive type, or void, the return value is an
4518      * array of length 0.
4519      *
4520      * @return an array representing the superinterfaces
4521      * @since 1.8
4522      *//*
4523     public AnnotatedType[] getAnnotatedInterfaces() {
4524         return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
4525     }
4526     */
4527 
4528     /**
4529      * Returns true if the annotation exists.
4530      */
4531     @FastNative
isDeclaredAnnotationPresent(Class<? extends Annotation> annotationClass)4532     private native boolean isDeclaredAnnotationPresent(Class<? extends Annotation> annotationClass);
4533 
getSignatureAttribute()4534     private String getSignatureAttribute() {
4535         String[] annotation = getSignatureAnnotation();
4536         if (annotation == null) {
4537             return null;
4538         }
4539         StringBuilder result = new StringBuilder();
4540         for (String s : annotation) {
4541             result.append(s);
4542         }
4543         return result.toString();
4544     }
4545 
4546     @FastNative
getSignatureAnnotation()4547     private native String[] getSignatureAnnotation();
4548 
4549     /**
4550      * Is this a runtime created proxy class?
4551      *
4552      * @hide
4553      */
isProxy()4554     public boolean isProxy() {
4555         return (accessFlags & 0x00040000) != 0;
4556     }
4557 
4558     /**
4559      * @hide
4560      */
getAccessFlags()4561     public int getAccessFlags() {
4562         return accessFlags;
4563     }
4564 
4565     /**
4566      * Returns the method if it is defined by this class; {@code null} otherwise. This may return a
4567      * non-public member.
4568      *
4569      * @param name the method name
4570      * @param args the method's parameter types
4571      */
4572     @FastNative
getDeclaredMethodInternal(String name, Class<?>[] args)4573     private native Method getDeclaredMethodInternal(String name, Class<?>[] args);
4574 
4575     @FastNative
ensureExtDataPresent()4576     native ClassExt ensureExtDataPresent();
4577 
4578     // Android-changed: Removed SecurityException.
4579     /**
4580      * Returns the nest host of the <a href=#nest>nest</a> to which the class
4581      * or interface represented by this {@code Class} object belongs.
4582      * Every class and interface belongs to exactly one nest.
4583      *
4584      * If the nest host of this class or interface has previously
4585      * been determined, then this method returns the nest host.
4586      * If the nest host of this class or interface has
4587      * not previously been determined, then this method determines the nest
4588      * host using the algorithm of JVMS 5.4.4, and returns it.
4589      *
4590      * Often, a class or interface belongs to a nest consisting only of itself,
4591      * in which case this method returns {@code this} to indicate that the class
4592      * or interface is the nest host.
4593      *
4594      * <p>If this {@code Class} object represents a primitive type, an array type,
4595      * or {@code void}, then this method returns {@code this},
4596      * indicating that the represented entity belongs to the nest consisting only of
4597      * itself, and is the nest host.
4598      *
4599      * @return the nest host of this class or interface
4600      * @since 11
4601      * @jvms 4.7.28 The {@code NestHost} Attribute
4602      * @jvms 4.7.29 The {@code NestMembers} Attribute
4603      * @jvms 5.4.4 Access Control
4604      */
getNestHost()4605     public Class<?> getNestHost() {
4606         // Android-removed: Android has a different JNI layer.
4607         /*
4608         if (isPrimitive() || isArray()) {
4609             return this;
4610         }
4611 
4612         Class<?> host = getNestHost0();
4613         if (host == this) {
4614             return this;
4615         }
4616         // returning a different class requires a security check
4617         @SuppressWarnings("removal")
4618         SecurityManager sm = System.getSecurityManager();
4619         if (sm != null) {
4620             checkPackageAccess(sm,
4621                                ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
4622         }
4623         return host;
4624         */
4625         if (isPrimitive() || isArray() || Void.TYPE.equals(this)) {
4626             return this;
4627         }
4628 
4629         Class host = getNestHostFromAnnotation();
4630         if (host == null) {
4631             return this;
4632         }
4633         return (nestHostHasMember(host, this) ? host : this);
4634     }
4635 
nestHostHasMember(Class<?> host, Class<?> member)4636     private static boolean nestHostHasMember(Class<?> host, Class<?> member) {
4637         if (host.equals(member)) {
4638             return true;
4639         }
4640         return nestMembersIncludeMember(host.getNestMembersFromAnnotation(), member);
4641     }
4642 
nestMembersIncludeMember(Class<?>[] members, Class<?> member)4643     private static boolean nestMembersIncludeMember(Class<?>[] members, Class<?> member) {
4644         if (members == null) {
4645             return false;
4646         }
4647         for (Class m : members) {
4648             if (member.equals(m)) {
4649                 return true;
4650             }
4651         }
4652         return false;
4653     }
4654 
4655     @FastNative
getNestHostFromAnnotation()4656     private native Class<?> getNestHostFromAnnotation();
4657 
4658     // Android-changed: This implementation comes from OpenJDK 17.
4659     /**
4660      * Determines if the given {@code Class} is a nestmate of the
4661      * class or interface represented by this {@code Class} object.
4662      * Two classes or interfaces are nestmates
4663      * if they have the same {@linkplain #getNestHost() nest host}.
4664      *
4665      * @param c the class to check
4666      * @return {@code true} if this class and {@code c} are members of
4667      * the same nest; and {@code false} otherwise.
4668      *
4669      * @since 11
4670      */
isNestmateOf(Class<?> c)4671     public boolean isNestmateOf(Class<?> c) {
4672         if (this == c) {
4673             return true;
4674         }
4675         if (isPrimitive() || isArray() ||
4676             c.isPrimitive() || c.isArray()) {
4677             return false;
4678         }
4679 
4680         return getNestHost() == c.getNestHost();
4681     }
4682 
4683     // Android-changed: Removed references to MethodHandles.Lookup#defineHiddenClass.
4684     /**
4685      * Returns an array containing {@code Class} objects representing all the
4686      * classes and interfaces that are members of the nest to which the class
4687      * or interface represented by this {@code Class} object belongs.
4688      *
4689      * First, this method obtains the {@linkplain #getNestHost() nest host},
4690      * {@code H}, of the nest to which the class or interface represented by
4691      * this {@code Class} object belongs. The zeroth element of the returned
4692      * array is {@code H}.
4693      *
4694      * Then, for each class or interface {@code C} which is recorded by {@code H}
4695      * as being a member of its nest, this method attempts to obtain the {@code Class}
4696      * object for {@code C} (using {@linkplain #getClassLoader() the defining class
4697      * loader} of the current {@code Class} object), and then obtains the
4698      * {@linkplain #getNestHost() nest host} of the nest to which {@code C} belongs.
4699      * The classes and interfaces which are recorded by {@code H} as being members
4700      * of its nest, and for which {@code H} can be determined as their nest host,
4701      * are indicated by subsequent elements of the returned array. The order of
4702      * such elements is unspecified. Duplicates are permitted.
4703      *
4704      * <p>If this {@code Class} object represents a primitive type, an array type,
4705      * or {@code void}, then this method returns a single-element array containing
4706      * {@code this}.
4707      *
4708      * @apiNote
4709      * The returned array includes only the nest members recorded in the {@code NestMembers}
4710      * attribute.
4711      *
4712      * @return an array of all classes and interfaces in the same nest as
4713      * this class or interface
4714      *
4715      * @since 11
4716      * @see #getNestHost()
4717      * @jvms 4.7.28 The {@code NestHost} Attribute
4718      * @jvms 4.7.29 The {@code NestMembers} Attribute
4719      */
getNestMembers()4720     public Class<?>[] getNestMembers() {
4721         // Android-changed: ART has a different JNI layer.
4722         /*
4723         if (isPrimitive() || isArray()) {
4724             return new Class<?>[] { this };
4725         }
4726         Class<?>[] members = getNestMembers0();
4727         // Can't actually enable this due to bootstrapping issues
4728         // assert(members.length != 1 || members[0] == this); // expected invariant from VM
4729 
4730         if (members.length > 1) {
4731             // If we return anything other than the current class we need
4732             // a security check
4733             @SuppressWarnings("removal")
4734             SecurityManager sm = System.getSecurityManager();
4735             if (sm != null) {
4736                 checkPackageAccess(sm,
4737                                    ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
4738             }
4739         }
4740         return members;
4741         */
4742         if (isPrimitive() || isArray() || Void.TYPE.equals(this)) {
4743             return new Class[] { this };
4744         }
4745 
4746         Class host = getNestHostFromAnnotation();
4747         if (host != null && !host.equals(this)) {
4748             if (host.isPrimitive() || host.isArray() || Void.TYPE.equals(host)) {
4749                 return new Class[] { this };
4750             }
4751             return host.getNestMembers(this);
4752         }
4753         return getNestMembers(this);
4754     }
4755 
getNestMembers(Class<?> originatingMember)4756     private Class<?>[] getNestMembers(Class<?> originatingMember) {
4757 
4758         Class[] members = getNestMembersFromAnnotation();
4759         if (members == null) {
4760             return new Class[] { originatingMember };
4761         }
4762         if (originatingMember != this && !nestMembersIncludeMember(members, originatingMember)) {
4763             return new Class[] { originatingMember };
4764         }
4765 
4766         Class[] result = new Class[members.length+1];
4767         result[0] = this;
4768         int idx = 1;
4769         for (Class m : members) {
4770             if (m == null || !this.equals(m.getNestHostFromAnnotation())) {
4771                 continue;
4772             }
4773             result[idx] = m;
4774             ++idx;
4775         }
4776 
4777         if (idx < result.length) {
4778             Class[] tmp = new Class[idx];
4779             for (int i = 0; i < tmp.length; ++i) {
4780                 tmp[i] = result[i];
4781             }
4782             result = tmp;
4783         }
4784 
4785         return result;
4786     }
4787 
4788     @FastNative
getNestMembersFromAnnotation()4789     private native Class<?>[] getNestMembersFromAnnotation();
4790 
4791     private static class Caches {
4792         /**
4793          * Cache to avoid frequent recalculation of generic interfaces, which is generally uncommon.
4794          * Sized sufficient to allow ConcurrentHashMapTest to run without recalculating its generic
4795          * interfaces (required to avoid time outs). Validated by running reflection heavy code
4796          * such as applications using Guice-like frameworks.
4797          */
4798         private static final BasicLruCache<Class, Type[]> genericInterfaces
4799             = new BasicLruCache<Class, Type[]>(8);
4800     }
4801 
4802     // Android-changed: Remove javadoc related to hidden classes and ClassDesc.
4803     /**
4804      * Returns the descriptor string of the entity (class, interface, array class,
4805      * primitive type, or {@code void}) represented by this {@code Class} object.
4806      *
4807      * <p> If this {@code Class} object represents a class or interface,
4808      * not an array class, then:
4809      * <ul>
4810      * <li> The result is a field descriptor (JVMS {@jvms 4.3.2})
4811      *      for the class or interface.
4812      * </ul>
4813      *
4814      * <p> If this {@code Class} object represents an array class, then
4815      * the result is a string consisting of one or more '{@code [}' characters
4816      * representing the depth of the array nesting, followed by the
4817      * descriptor string of the element type.
4818      * <ul>
4819      * <li> This array class can be described nominally.
4820      * </ul>
4821      *
4822      * <p> If this {@code Class} object represents a primitive type or
4823      * {@code void}, then the result is a field descriptor string which
4824      * is a one-letter code corresponding to a primitive type or {@code void}
4825      * ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}).
4826      *
4827      * @apiNote
4828      * This is not a strict inverse of {@link #forName};
4829      * distinct classes which share a common name but have different class loaders
4830      * will have identical descriptor strings.
4831      *
4832      * @return the descriptor string for this {@code Class} object
4833      * @jvms 4.3.2 Field Descriptors
4834      * @since 12
4835      */
4836     @Override
descriptorString()4837     public String descriptorString() {
4838         if (isPrimitive())
4839             return Wrapper.forPrimitiveType(this).basicTypeString();
4840 
4841         if (isArray()) {
4842             return "[" + componentType.descriptorString();
4843         } else if (isHidden()) {
4844             String name = getName();
4845             int index = name.indexOf('/');
4846             return new StringBuilder(name.length() + 2)
4847                     .append('L')
4848                     .append(name.substring(0, index).replace('.', '/'))
4849                     .append('.')
4850                     .append(name, index + 1, name.length())
4851                     .append(';')
4852                     .toString();
4853         } else {
4854             String name = getName().replace('.', '/');
4855             return new StringBuilder(name.length() + 2)
4856                     .append('L')
4857                     .append(name)
4858                     .append(';')
4859                     .toString();
4860         }
4861     }
4862 
4863     /**
4864      * Returns the component type of this {@code Class}, if it describes
4865      * an array type, or {@code null} otherwise.
4866      *
4867      * @implSpec
4868      * Equivalent to {@link Class#getComponentType()}.
4869      *
4870      * @return a {@code Class} describing the component type, or {@code null}
4871      * if this {@code Class} does not describe an array type
4872      * @since 12
4873      */
4874     @Override
componentType()4875     public Class<?> componentType() {
4876         return isArray() ? componentType : null;
4877     }
4878 
4879     /**
4880      * Returns a {@code Class} for an array type whose component type
4881      * is described by this {@linkplain Class}.
4882      *
4883      * @return a {@code Class} describing the array type
4884      * @since 12
4885      */
4886     @Override
arrayType()4887     public Class<?> arrayType() {
4888         return Array.newInstance(this, 0).getClass();
4889     }
4890 
4891     /**
4892      * Returns a nominal descriptor for this instance, if one can be
4893      * constructed, or an empty {@link Optional} if one cannot be.
4894      *
4895      * @return An {@link Optional} containing the resulting nominal descriptor,
4896      * or an empty {@link Optional} if one cannot be constructed.
4897      * @since 12
4898      * @hide
4899      */
4900     @Override
describeConstable()4901     public Optional<ClassDesc> describeConstable() {
4902         Class<?> c = isArray() ? elementType() : this;
4903         return c.isHidden() ? Optional.empty()
4904                             : Optional.of(ClassDesc.ofDescriptor(descriptorString()));
4905    }
4906 
4907     /**
4908      * Returns {@code true} if and only if the underlying class is a hidden class.
4909      *
4910      * @return {@code true} if and only if this class is a hidden class.
4911      *
4912      * @since 15
4913      * @see MethodHandles.Lookup#defineHiddenClass
4914      * @hide
4915      */
4916     // Android-changed: Android doesn't support hidden classes yet.
4917     // public native boolean isHidden();
4918     @IntrinsicCandidate
4919     // Android-changed: Android has not implemented the hidden class feature yet.
4920     // public native boolean isHidden();
isHidden()4921     public boolean isHidden() {
4922         return false;
4923     }
4924 
4925     // Android-changed: Removed @jls tags.
4926     /**
4927      * Returns an array containing {@code Class} objects representing the
4928      * direct subinterfaces or subclasses permitted to extend or
4929      * implement this class or interface if it is sealed.  The order of such elements
4930      * is unspecified. The array is empty if this sealed class or interface has no
4931      * permitted subclass. If this {@code Class} object represents a primitive type,
4932      * {@code void}, an array type, or a class or interface that is not sealed,
4933      * that is {@link #isSealed()} returns {@code false}, then this method returns {@code null}.
4934      * Conversely, if {@link #isSealed()} returns {@code true}, then this method
4935      * returns a non-null value.
4936      *
4937      * For each class or interface {@code C} which is recorded as a permitted
4938      * direct subinterface or subclass of this class or interface,
4939      * this method attempts to obtain the {@code Class}
4940      * object for {@code C} (using {@linkplain #getClassLoader() the defining class
4941      * loader} of the current {@code Class} object).
4942      * The {@code Class} objects which can be obtained and which are direct
4943      * subinterfaces or subclasses of this class or interface,
4944      * are indicated by elements of the returned array. If a {@code Class} object
4945      * cannot be obtained, it is silently ignored, and not included in the result
4946      * array.
4947      *
4948      * @return an array of {@code Class} objects of the permitted subclasses of this class or interface,
4949      *         or {@code null} if this class or interface is not sealed.
4950      *
4951      * @since 17
4952      */
4953     // Android-removed: CallerSensitive annotation
4954     // @CallerSensitive
getPermittedSubclasses()4955     public Class<?>[] getPermittedSubclasses() {
4956         Class<?>[] subClasses;
4957         // Android-changed: A final class cannot be sealed.
4958         // if (isArray() || isPrimitive() || (subClasses = getPermittedSubclassesFromAnnotation()) == null) {
4959         if (isArray() || isPrimitive() || Modifier.isFinal( getModifiers() ) ||
4960                 (subClasses = getPermittedSubclassesFromAnnotation()) == null) {
4961             return null;
4962         }
4963         // Android-changed: Avoid using lambdas.
4964         /*
4965         if (subClasses.length > 0) {
4966             if (Arrays.stream(subClasses).anyMatch(c -> !isDirectSubType(c))) {
4967                 subClasses = Arrays.stream(subClasses)
4968                                    .filter(this::isDirectSubType)
4969                                    .toArray(s -> new Class<?>[s]);
4970             }
4971         }
4972         */
4973         int directSubClassCount = getDirectSubClassCount(subClasses);
4974         if (directSubClassCount < subClasses.length) {
4975             Class[] tmp = new Class[directSubClassCount];
4976             int idx = 0;
4977             for (Class<?> c : subClasses) {
4978                 if (isDirectSubType(c)) {
4979                     tmp[idx] = c;
4980                     ++idx;
4981                 }
4982             }
4983             subClasses = tmp;
4984         }
4985 
4986         // Android-removed: SecurityManager usage.
4987         /*
4988         if (subClasses.length > 0) {
4989             // If we return some classes we need a security check:
4990             @SuppressWarnings("removal")
4991             SecurityManager sm = System.getSecurityManager();
4992             if (sm != null) {
4993                 checkPackageAccessForPermittedSubclasses(sm,
4994                                              ClassLoader.getClassLoader(Reflection.getCallerClass()),
4995                                              subClasses);
4996             }
4997         }
4998         */
4999         return subClasses;
5000     }
5001 
getDirectSubClassCount(Class<?>[] subClasses)5002     private int getDirectSubClassCount(Class<?>[] subClasses) {
5003         int result = 0;
5004         for (Class<?> c : subClasses) {
5005             if (isDirectSubType(c)) {
5006                  ++result;
5007             }
5008         }
5009         return result;
5010     }
5011 
isDirectSubType(Class<?> c)5012     private boolean isDirectSubType(Class<?> c) {
5013         if (isInterface()) {
5014             // Android-changed: Use of getInterfaces
5015             //for (Class<?> i : c.getInterfaces(/* cloneArray */ false)) {
5016             for (Class<?> i : c.getInterfaces()) {
5017                 if (i == this) {
5018                     return true;
5019                 }
5020             }
5021         } else {
5022             return c.getSuperclass() == this;
5023         }
5024         return false;
5025     }
5026 
5027     // Android-changed: Removed @jls tags.
5028     /**
5029      * Returns {@code true} if and only if this {@code Class} object represents
5030      * a sealed class or interface. If this {@code Class} object represents a
5031      * primitive type, {@code void}, or an array type, this method returns
5032      * {@code false}. A sealed class or interface has (possibly zero) permitted
5033      * subclasses; {@link #getPermittedSubclasses()} returns a non-null but
5034      * possibly empty value for a sealed class or interface.
5035      *
5036      * @return {@code true} if and only if this {@code Class} object represents
5037      * a sealed class or interface.
5038      *
5039      * @since 17
5040      */
isSealed()5041     public boolean isSealed() {
5042         if (isArray() || isPrimitive()) {
5043             return false;
5044         }
5045         return getPermittedSubclasses() != null;
5046     }
5047 
5048     // Android-changed: Implement permitted classes on top of ART.
5049     // private native Class<?>[] getPermittedSubclasses0();
5050     @FastNative
getPermittedSubclassesFromAnnotation()5051     private native Class<?>[] getPermittedSubclassesFromAnnotation();
5052 }
5053