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