1 /*
2  * Copyright (c) 1994, 2019, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */

25
26 package java.lang;
27
28 import java.lang.annotation.Annotation;
29 import java.lang.module.ModuleReader;
30 import java.lang.ref.SoftReference;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.ObjectStreamField;
34 import java.lang.reflect.AnnotatedElement;
35 import java.lang.reflect.AnnotatedType;
36 import java.lang.reflect.Array;
37 import java.lang.reflect.Constructor;
38 import java.lang.reflect.Executable;
39 import java.lang.reflect.Field;
40 import java.lang.reflect.GenericArrayType;
41 import java.lang.reflect.GenericDeclaration;
42 import java.lang.reflect.InvocationTargetException;
43 import java.lang.reflect.Member;
44 import java.lang.reflect.Method;
45 import java.lang.reflect.Modifier;
46 import java.lang.reflect.Proxy;
47 import java.lang.reflect.Type;
48 import java.lang.reflect.TypeVariable;
49 import java.net.URL;
50 import java.security.AccessController;
51 import java.security.PrivilegedAction;
52 import java.util.ArrayList;
53 import java.util.Arrays;
54 import java.util.Collection;
55 import java.util.HashMap;
56 import java.util.LinkedHashMap;
57 import java.util.LinkedHashSet;
58 import java.util.List;
59 import java.util.Map;
60 import java.util.Objects;
61 import java.util.StringJoiner;
62
63 import jdk.internal.HotSpotIntrinsicCandidate;
64 import jdk.internal.loader.BootLoader;
65 import jdk.internal.loader.BuiltinClassLoader;
66 import jdk.internal.misc.Unsafe;
67 import jdk.internal.misc.VM;
68 import jdk.internal.module.Resources;
69 import jdk.internal.reflect.CallerSensitive;
70 import jdk.internal.reflect.ConstantPool;
71 import jdk.internal.reflect.Reflection;
72 import jdk.internal.reflect.ReflectionFactory;
73 import jdk.internal.vm.annotation.ForceInline;
74 import sun.reflect.generics.factory.CoreReflectionFactory;
75 import sun.reflect.generics.factory.GenericsFactory;
76 import sun.reflect.generics.repository.ClassRepository;
77 import sun.reflect.generics.repository.MethodRepository;
78 import sun.reflect.generics.repository.ConstructorRepository;
79 import sun.reflect.generics.scope.ClassScope;
80 import sun.security.util.SecurityConstants;
81 import sun.reflect.annotation.*;
82 import sun.reflect.misc.ReflectUtil;
83
84 /**
85  * Instances of the class {@code Class} represent classes and interfaces
86  * in a running Java application. An enum type is a kind of class and an
87  * annotation type is a kind of interface. Every array also
88  * belongs to a class that is reflected as a {@code Class} object
89  * that is shared by all arrays with the same element type and number
90  * of dimensions.  The primitive Java types ({@code boolean},
91  * {@code byte}, {@code char}, {@code short},
92  * {@code int}, {@code long}, {@code float}, and
93  * {@code double}), and the keyword {@code void} are also
94  * represented as {@code Class} objects.
95  *
96  * <p> {@code Class} has no public constructor. Instead a {@code Class}
97  * object is constructed automatically by the Java Virtual Machine
98  * when a class loader invokes one of the
99  * {@link ClassLoader#defineClass(String,byte[], int,int) defineClass} methods
100  * and passes the bytes of a {@code class} file.
101  *
102  * <p> The methods of class {@code Class} expose many characteristics of a
103  * class or interface. Most characteristics are derived from the {@code class}
104  * file that the class loader passed to the Java Virtual Machine. A few
105  * characteristics are determined by the class loading environment at run time,
106  * such as the module returned by {@link #getModule() getModule()}.
107  *
108  * <p> Some methods of class {@code Class} expose whether the declaration of
109  * a class or interface in Java source code was <em>enclosed</em> within
110  * another declaration. Other methods describe how a class or interface
111  * is situated in a <em>nest</em>. A <a id="nest">nest</a> is a set of
112  * classes and interfaces, in the same run-time package, that
113  * allow mutual access to their {@code private} members.
114  * The classes and interfaces are known as <em>nestmates</em>.
115  * One nestmate acts as the
116  * <em>nest host</em>, and enumerates the other nestmates which
117  * belong to the nest; each of them in turn records it as the nest host.
118  * The classes and interfaces which belong to a nest, including its host, are
119  * determined when
120  * {@code class} files are generated, for example, a Java compiler
121  * will typically record a top-level class as the host of a nest where the
122  * other members are the classes and interfaces whose declarations are
123  * enclosed within the top-level class declaration.
124  *
125  * <p> The following example uses a {@code Class} object to print the
126  * class name of an object:
127  *
128  * <blockquote><pre>
129  *     void printClassName(Object obj) {
130  *         System.out.println("The class of " + obj +
131  *                            " is " + obj.getClass().getName());
132  *     }
133  * </pre></blockquote>
134  *
135  * <p> It is also possible to get the {@code Class} object for a named
136  * type (or for void) using a class literal.  See Section 15.8.2 of
137  * <cite>The Java&trade; Language Specification</cite>.
138  * For example:
139  *
140  * <blockquote>
141  *     {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
142  * </blockquote>
143  *
144  * @param <T> the type of the class modeled by this {@code Class}
145  * object.  For example, the type of {@code String.class} is {@code
146  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
147  * unknown.
148  *
149  * @author  unascribed
150  * @see     java.lang.ClassLoader#defineClass(byte[], intint)
151  * @since   1.0
152  */

153 public final class Class<T> implements java.io.Serializable,
154                               GenericDeclaration,
155                               Type,
156                               AnnotatedElement {
157     private static final int ANNOTATION= 0x00002000;
158     private static final int ENUM      = 0x00004000;
159     private static final int SYNTHETIC = 0x00001000;
160
161     private static native void registerNatives();
162     static {
163         registerNatives();
164     }
165
166     /*
167      * Private constructor. Only the Java Virtual Machine creates Class objects.
168      * This constructor is not used and prevents the default constructor being
169      * generated.
170      */

171     private Class(ClassLoader loader, Class<?> arrayComponentType) {
172         // Initialize final field for classLoader.  The initialization value of non-null
173         // prevents future JIT optimizations from assuming this final field is null.
174         classLoader = loader;
175         componentType = arrayComponentType;
176     }
177
178     /**
179      * Converts the object to a string. The string representation is the
180      * string "class" or "interface", followed by a space, and then by the
181      * fully qualified name of the class in the format returned by
182      * {@code getName}.  If this {@code Class} object represents a
183      * primitive type, this method returns the name of the primitive type.  If
184      * this {@code Class} object represents void this method returns
185      * "void". If this {@code Class} object represents an array type,
186      * this method returns "class " followed by {@code getName}.
187      *
188      * @return a string representation of this class object.
189      */

190     public String toString() {
191         return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
192             + getName();
193     }
194
195     /**
196      * Returns a string describing this {@code Class}, including
197      * information about modifiers and type parameters.
198      *
199      * The string is formatted as a list of type modifiers, if any,
200      * followed by the kind of type (empty string for primitive types
201      * and {@code class}, {@code enum}, {@code interface}, or
202      * <code>&#64;</code>{@code interface}, as appropriate), followed
203      * by the type's name, followed by an angle-bracketed
204      * comma-separated list of the type's type parameters, if any.
205      *
206      * A space is used to separate modifiers from one another and to
207      * separate any modifiers from the kind of type. The modifiers
208      * occur in canonical order. If there are no type parameters, the
209      * type parameter list is elided.
210      *
211      * For an array type, the string starts with the type name,
212      * followed by an angle-bracketed comma-separated list of the
213      * type's type parameters, if any, followed by a sequence of
214      * {@code []} characters, one set of brackets per dimension of
215      * the array.
216      *
217      * <p>Note that since information about the runtime representation
218      * of a type is being generated, modifiers not present on the
219      * originating source code or illegal on the originating source
220      * code may be present.
221      *
222      * @return a string describing this {@code Class}, including
223      * information about modifiers and type parameters
224      *
225      * @since 1.8
226      */

227     public String toGenericString() {
228         if (isPrimitive()) {
229             return toString();
230         } else {
231             StringBuilder sb = new StringBuilder();
232             Class<?> component = this;
233             int arrayDepth = 0;
234
235             if (isArray()) {
236                 do {
237                     arrayDepth++;
238                     component = component.getComponentType();
239                 } while (component.isArray());
240                 sb.append(component.getName());
241             } else {
242                 // Class modifiers are a superset of interface modifiers
243                 int modifiers = getModifiers() & Modifier.classModifiers();
244                 if (modifiers != 0) {
245                     sb.append(Modifier.toString(modifiers));
246                     sb.append(' ');
247                 }
248
249                 if (isAnnotation()) {
250                     sb.append('@');
251                 }
252                 if (isInterface()) { // Note: all annotation types are interfaces
253                     sb.append("interface");
254                 } else {
255                     if (isEnum())
256                         sb.append("enum");
257                     else
258                         sb.append("class");
259                 }
260                 sb.append(' ');
261                 sb.append(getName());
262             }
263
264             TypeVariable<?>[] typeparms = component.getTypeParameters();
265             if (typeparms.length > 0) {
266                 StringJoiner sj = new StringJoiner(",""<"">");
267                 for(TypeVariable<?> typeparm: typeparms) {
268                     sj.add(typeparm.getTypeName());
269                 }
270                 sb.append(sj.toString());
271             }
272
273             for (int i = 0; i < arrayDepth; i++)
274                 sb.append("[]");
275
276             return sb.toString();
277         }
278     }
279
280     /**
281      * Returns the {@code Class} object associated with the class or
282      * interface with the given string name.  Invoking this method is
283      * equivalent to:
284      *
285      * <blockquote>
286      *  {@code Class.forName(className, true, currentLoader)}
287      * </blockquote>
288      *
289      * where {@code currentLoader} denotes the defining class loader of
290      * the current class.
291      *
292      * <p> For example, the following code fragment returns the
293      * runtime {@code Class} descriptor for the class named
294      * {@code java.lang.Thread}:
295      *
296      * <blockquote>
297      *   {@code Class t = Class.forName("java.lang.Thread")}
298      * </blockquote>
299      * <p>
300      * A call to {@code forName("X")} causes the class named
301      * {@code X} to be initialized.
302      *
303      * @param      className   the fully qualified name of the desired class.
304      * @return     the {@code Class} object for the class with the
305      *             specified name.
306      * @exception LinkageError if the linkage fails
307      * @exception ExceptionInInitializerError if the initialization provoked
308      *            by this method fails
309      * @exception ClassNotFoundException if the class cannot be located
310      */

311     @CallerSensitive
312     public static Class<?> forName(String className)
313                 throws ClassNotFoundException {
314         Class<?> caller = Reflection.getCallerClass();
315         return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
316     }
317
318
319     /**
320      * Returns the {@code Class} object associated with the class or
321      * interface with the given string name, using the given class loader.
322      * Given the fully qualified name for a class or interface (in the same
323      * format returned by {@code getName}) this method attempts to
324      * locate, load, and link the class or interface.  The specified class
325      * loader is used to load the class or interface.  If the parameter
326      * {@code loader} is null, the class is loaded through the bootstrap
327      * class loader.  The class is initialized only if the
328      * {@code initialize} parameter is {@code true} and if it has
329      * not been initialized earlier.
330      *
331      * <p> If {@code name} denotes a primitive type or void, an attempt
332      * will be made to locate a user-defined class in the unnamed package whose
333      * name is {@code name}. Therefore, this method cannot be used to
334      * obtain any of the {@code Class} objects representing primitive
335      * types or void.
336      *
337      * <p> If {@code name} denotes an array class, the component type of
338      * the array class is loaded but not initialized.
339      *
340      * <p> For example, in an instance method the expression:
341      *
342      * <blockquote>
343      *  {@code Class.forName("Foo")}
344      * </blockquote>
345      *
346      * is equivalent to:
347      *
348      * <blockquote>
349      *  {@code Class.forName("Foo"truethis.getClass().getClassLoader())}
350      * </blockquote>
351      *
352      * Note that this method throws errors related to loading, linking or
353      * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
354      * Java Language Specification</em>.
355      * Note that this method does not check whether the requested class
356      * is accessible to its caller.
357      *
358      * @param name       fully qualified name of the desired class
359      * @param initialize if {@code true} the class will be initialized.
360      *                   See Section 12.4 of <em>The Java Language Specification</em>.
361      * @param loader     class loader from which the class must be loaded
362      * @return           class object representing the desired class
363      *
364      * @exception LinkageError if the linkage fails
365      * @exception ExceptionInInitializerError if the initialization provoked
366      *            by this method fails
367      * @exception ClassNotFoundException if the class cannot be located by
368      *            the specified class loader
369      * @exception SecurityException
370      *            if a security manager is present, and the {@code loader} is
371      *            {@code null}, and the caller's class loader is not
372      *            {@code null}, and the caller does not have the
373      *            {@link RuntimePermission}{@code ("getClassLoader")}
374      *
375      * @see       java.lang.Class#forName(String)
376      * @see       java.lang.ClassLoader
377      * @since     1.2
378      */

379     @CallerSensitive
380     public static Class<?> forName(String name, boolean initialize,
381                                    ClassLoader loader)
382         throws ClassNotFoundException
383     {
384         Class<?> caller = null;
385         SecurityManager sm = System.getSecurityManager();
386         if (sm != null) {
387             // Reflective call to get caller class is only needed if a security manager
388             // is present.  Avoid the overhead of making this call otherwise.
389             caller = Reflection.getCallerClass();
390             if (loader == null) {
391                 ClassLoader ccl = ClassLoader.getClassLoader(caller);
392                 if (ccl != null) {
393                     sm.checkPermission(
394                         SecurityConstants.GET_CLASSLOADER_PERMISSION);
395                 }
396             }
397         }
398         return forName0(name, initialize, loader, caller);
399     }
400
401     /** Called after security check for system loader access checks have been made. */
402     private static native Class<?> forName0(String name, boolean initialize,
403                                             ClassLoader loader,
404                                             Class<?> caller)
405         throws ClassNotFoundException;
406
407
408     /**
409      * Returns the {@code Class} with the given <a href="ClassLoader.html#name">
410      * binary name</a> in the given module.
411      *
412      * <p> This method attempts to locate, load, and link the class or interface.
413      * It does not run the class initializer.  If the class is not found, this
414      * method returns {@code null}. </p>
415      *
416      * <p> If the class loader of the given module defines other modules and
417      * the given name is a class defined in a different module, this method
418      * returns {@code null} after the class is loaded. </p>
419      *
420      * <p> This method does not check whether the requested class is
421      * accessible to its caller. </p>
422      *
423      * @apiNote
424      * This method returns {@code null} on failure rather than
425      * throwing a {@link ClassNotFoundException}, as is done by
426      * the {@link #forName(String, boolean, ClassLoader)} method.
427      * The security check is a stack-based permission check if the caller
428      * loads a class in another module.
429      *
430      * @param  module   A module
431      * @param  name     The <a href="ClassLoader.html#name">binary name</a>
432      *                  of the class
433      * @return {@code Class} object of the given name defined in the given module;
434      *         {@code nullif not found.
435      *
436      * @throws NullPointerException if the given module or name is {@code null}
437      *
438      * @throws LinkageError if the linkage fails
439      *
440      * @throws SecurityException
441      *         <ul>
442      *         <li> if the caller is not the specified module and
443      *         {@code RuntimePermission("getClassLoader")} permission is denied; or</li>
444      *         <li> access to the module content is denied. For example,
445      *         permission check will be performed when a class loader calls
446      *         {@link ModuleReader#open(String)} to read the bytes of a class file
447      *         in a module.</li>
448      *         </ul>
449      *
450      * @since 9
451      * @spec JPMS
452      */

453     @CallerSensitive
454     public static Class<?> forName(Module module, String name) {
455         Objects.requireNonNull(module);
456         Objects.requireNonNull(name);
457
458         ClassLoader cl;
459         SecurityManager sm = System.getSecurityManager();
460         if (sm != null) {
461             Class<?> caller = Reflection.getCallerClass();
462             if (caller != null && caller.getModule() != module) {
463                 // if caller is null, Class.forName is the last java frame on the stack.
464                 // java.base has all permissions
465                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
466             }
467             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
468             cl = AccessController.doPrivileged(pa);
469         } else {
470             cl = module.getClassLoader();
471         }
472
473         if (cl != null) {
474             return cl.loadClass(module, name);
475         } else {
476             return BootLoader.loadClass(module, name);
477         }
478     }
479
480     /**
481      * Creates a new instance of the class represented by this {@code Class}
482      * object.  The class is instantiated as if by a {@code new}
483      * expression with an empty argument list.  The class is initialized if it
484      * has not already been initialized.
485      *
486      * @deprecated This method propagates any exception thrown by the
487      * nullary constructor, including a checked exception.  Use of
488      * this method effectively bypasses the compile-time exception
489      * checking that would otherwise be performed by the compiler.
490      * The {@link
491      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
492      * Constructor.newInstance} method avoids this problem by wrapping
493      * any exception thrown by the constructor in a (checked) {@link
494      * java.lang.reflect.InvocationTargetException}.
495      *
496      * <p>The call
497      *
498      * <pre>{@code
499      * clazz.newInstance()
500      * }</pre>
501      *
502      * can be replaced by
503      *
504      * <pre>{@code
505      * clazz.getDeclaredConstructor().newInstance()
506      * }</pre>
507      *
508      * The latter sequence of calls is inferred to be able to throw
509      * the additional exception types {@link
510      * InvocationTargetException} and {@link
511      * NoSuchMethodException}. Both of these exception types are
512      * subclasses of {@link ReflectiveOperationException}.
513      *
514      * @return  a newly allocated instance of the class represented by this
515      *          object.
516      * @throws  IllegalAccessException  if the class or its nullary
517      *          constructor is not accessible.
518      * @throws  InstantiationException
519      *          if this {@code Class} represents an abstract class,
520      *          an interface, an array class, a primitive type, or void;
521      *          or if the class has no nullary constructor;
522      *          or if the instantiation fails for some other reason.
523      * @throws  ExceptionInInitializerError if the initialization
524      *          provoked by this method fails.
525      * @throws  SecurityException
526      *          If a security manager, <i>s</i>, is present and
527      *          the caller's class loader is not the same as or an
528      *          ancestor of the class loader for the current class and
529      *          invocation of {@link SecurityManager#checkPackageAccess
530      *          s.checkPackageAccess()} denies access to the package
531      *          of this class.
532      */

533     @CallerSensitive
534     @Deprecated(since="9")
535     public T newInstance()
536         throws InstantiationException, IllegalAccessException
537     {
538         SecurityManager sm = System.getSecurityManager();
539         if (sm != null) {
540             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false);
541         }
542
543         // NOTE: the following code may not be strictly correct under
544         // the current Java memory model.
545
546         // Constructor lookup
547         if (cachedConstructor == null) {
548             if (this == Class.class) {
549                 throw new IllegalAccessException(
550                     "Can not call newInstance() on the Class for java.lang.Class"
551                 );
552             }
553             try {
554                 Class<?>[] empty = {};
555                 final Constructor<T> c = getReflectionFactory().copyConstructor(
556                     getConstructor0(empty, Member.DECLARED));
557                 // Disable accessibility checks on the constructor
558                 // since we have to do the security check here anyway
559                 // (the stack depth is wrong for the Constructor's
560                 // security check to work)
561                 java.security.AccessController.doPrivileged(
562                     new java.security.PrivilegedAction<>() {
563                         public Void run() {
564                                 c.setAccessible(true);
565                                 return null;
566                             }
567                         });
568                 cachedConstructor = c;
569             } catch (NoSuchMethodException e) {
570                 throw (InstantiationException)
571                     new InstantiationException(getName()).initCause(e);
572             }
573         }
574         Constructor<T> tmpConstructor = cachedConstructor;
575         // Security check (same as in java.lang.reflect.Constructor)
576         Class<?> caller = Reflection.getCallerClass();
577         if (newInstanceCallerCache != caller) {
578             int modifiers = tmpConstructor.getModifiers();
579             Reflection.ensureMemberAccess(caller, thisthis, modifiers);
580             newInstanceCallerCache = caller;
581         }
582         // Run constructor
583         try {
584             return tmpConstructor.newInstance((Object[])null);
585         } catch (InvocationTargetException e) {
586             Unsafe.getUnsafe().throwException(e.getTargetException());
587             // Not reached
588             return null;
589         }
590     }
591     private transient volatile Constructor<T> cachedConstructor;
592     private transient volatile Class<?>       newInstanceCallerCache;
593
594
595     /**
596      * Determines if the specified {@code Object} is assignment-compatible
597      * with the object represented by this {@code Class}.  This method is
598      * the dynamic equivalent of the Java language {@code instanceof}
599      * operator. The method returns {@code trueif the specified
600      * {@code Object} argument is non-null and can be cast to the
601      * reference type represented by this {@code Class} object without
602      * raising a {@code ClassCastException.} It returns {@code false}
603      * otherwise.
604      *
605      * <p> Specifically, if this {@code Class} object represents a
606      * declared classthis method returns {@code trueif the specified
607      * {@code Object} argument is an instance of the represented class (or
608      * of any of its subclasses); it returns {@code false} otherwise. If
609      * this {@code Class} object represents an array classthis method
610      * returns {@code trueif the specified {@code Object} argument
611      * can be converted to an object of the array class by an identity
612      * conversion or by a widening reference conversion; it returns
613      * {@code false} otherwise. If this {@code Class} object
614      * represents an interfacethis method returns {@code trueif the
615      * class or any superclass of the specified {@code Object} argument
616      * implements this interface; it returns {@code false} otherwise. If
617      * this {@code Class} object represents a primitive type, this method
618      * returns {@code false}.
619      *
620      * @param   obj the object to check
621      * @return  true if {@code obj} is an instance of this class
622      *
623      * @since 1.1
624      */

625     @HotSpotIntrinsicCandidate
626     public native boolean isInstance(Object obj);
627
628
629     /**
630      * Determines if the class or interface represented by this
631      * {@code Class} object is either the same as, or is a superclass or
632      * superinterface of, the class or interface represented by the specified
633      * {@code Class} parameter. It returns {@code trueif so;
634      * otherwise it returns {@code false}. If this {@code Class}
635      * object represents a primitive type, this method returns
636      * {@code trueif the specified {@code Class} parameter is
637      * exactly this {@code Class} object; otherwise it returns
638      * {@code false}.
639      *
640      * <p> Specifically, this method tests whether the type represented by the
641      * specified {@code Class} parameter can be converted to the type
642      * represented by this {@code Class} object via an identity conversion
643      * or via a widening reference conversion. See <em>The Java Language
644      * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
645      *
646      * @param cls the {@code Class} object to be checked
647      * @return the {@code boolean} value indicating whether objects of the
648      * type {@code cls} can be assigned to objects of this class
649      * @exception NullPointerException if the specified Class parameter is
650      *            null.
651      * @since 1.1
652      */

653     @HotSpotIntrinsicCandidate
654     public native boolean isAssignableFrom(Class<?> cls);
655
656
657     /**
658      * Determines if the specified {@code Class} object represents an
659      * interface type.
660      *
661      * @return  {@code trueif this object represents an interface;
662      *          {@code false} otherwise.
663      */

664     @HotSpotIntrinsicCandidate
665     public native boolean isInterface();
666
667
668     /**
669      * Determines if this {@code Class} object represents an array class.
670      *
671      * @return  {@code trueif this object represents an array class;
672      *          {@code false} otherwise.
673      * @since   1.1
674      */

675     @HotSpotIntrinsicCandidate
676     public native boolean isArray();
677
678
679     /**
680      * Determines if the specified {@code Class} object represents a
681      * primitive type.
682      *
683      * <p> There are nine predefined {@code Class} objects to represent
684      * the eight primitive types and void.  These are created by the Java
685      * Virtual Machine, and have the same names as the primitive types that
686      * they represent, namely {@code boolean}, {@code byte},
687      * {@code char}, {@code short}, {@code int},
688      * {@code long}, {@code float}, and {@code double}.
689      *
690      * <p> These objects may only be accessed via the following public static
691      * final variables, and are the only {@code Class} objects for which
692      * this method returns {@code true}.
693      *
694      * @return true if and only if this class represents a primitive type
695      *
696      * @see     java.lang.Boolean#TYPE
697      * @see     java.lang.Character#TYPE
698      * @see     java.lang.Byte#TYPE
699      * @see     java.lang.Short#TYPE
700      * @see     java.lang.Integer#TYPE
701      * @see     java.lang.Long#TYPE
702      * @see     java.lang.Float#TYPE
703      * @see     java.lang.Double#TYPE
704      * @see     java.lang.Void#TYPE
705      * @since 1.1
706      */

707     @HotSpotIntrinsicCandidate
708     public native boolean isPrimitive();
709
710     /**
711      * Returns true if this {@code Class} object represents an annotation
712      * type.  Note that if this method returns true, {@link #isInterface()}
713      * would also return true, as all annotation types are also interfaces.
714      *
715      * @return {@code trueif this class object represents an annotation
716      *      type; {@code false} otherwise
717      * @since 1.5
718      */

719     public boolean isAnnotation() {
720         return (getModifiers() & ANNOTATION) != 0;
721     }
722
723     /**
724      * Returns {@code trueif this class is a synthetic class;
725      * returns {@code false} otherwise.
726      * @return {@code trueif and only if this class is a synthetic class as
727      *         defined by the Java Language Specification.
728      * @jls 13.1 The Form of a Binary
729      * @since 1.5
730      */

731     public boolean isSynthetic() {
732         return (getModifiers() & SYNTHETIC) != 0;
733     }
734
735     /**
736      * Returns the  name of the entity (classinterface, array class,
737      * primitive type, or void) represented by this {@code Class} object,
738      * as a {@code String}.
739      *
740      * <p> If this class object represents a reference type that is not an
741      * array type then the binary name of the class is returned, as specified
742      * by
743      * <cite>The Java&trade; Language Specification</cite>.
744      *
745      * <p> If this class object represents a primitive type or void, then the
746      * name returned is a {@code String} equal to the Java language
747      * keyword corresponding to the primitive type or void.
748      *
749      * <p> If this class object represents a class of arrays, then the internal
750      * form of the name consists of the name of the element type preceded by
751      * one or more '{@code [}' characters representing the depth of the array
752      * nesting.  The encoding of element type names is as follows:
753      *
754      * <blockquote><table class="striped">
755      * <caption style="display:none">Element types and encodings</caption>
756      * <thead>
757      * <tr><th scope="col"> Element Type <th scope="col"> Encoding
758      * </thead>
759      * <tbody style="text-align:left">
760      * <tr><th scope="row"boolean      <td style="text-align:center"> Z
761      * <tr><th scope="row"byte         <td style="text-align:center"> B
762      * <tr><th scope="row"char         <td style="text-align:center"> C
763      * <tr><th scope="row"class or interface
764      *                                   <td style="text-align:center"> L<i>classname</i>;
765      * <tr><th scope="row"double       <td style="text-align:center"> D
766      * <tr><th scope="row"float        <td style="text-align:center"> F
767      * <tr><th scope="row"int          <td style="text-align:center"> I
768      * <tr><th scope="row"long         <td style="text-align:center"> J
769      * <tr><th scope="row"short        <td style="text-align:center"> S
770      * </tbody>
771      * </table></blockquote>
772      *
773      * <p> The class or interface name <i>classname</i> is the binary name of
774      * the class specified above.
775      *
776      * <p> Examples:
777      * <blockquote><pre>
778      * String.class.getName()
779      *     returns "java.lang.String"
780      * byte.class.getName()
781      *     returns "byte"
782      * (new Object[3]).getClass().getName()
783      *     returns "[Ljava.lang.Object;"
784      * (new int[3][4][5][6][7][8][9]).getClass().getName()
785      *     returns "[[[[[[[I"
786      * </pre></blockquote>
787      *
788      * @return  the name of the class or interface
789      *          represented by this object.
790      */

791     public String getName() {
792         String name = this.name;
793         return name != null ? name : initClassName();
794     }
795
796     // Cache the name to reduce the number of calls into the VM.
797     // This field would be set by VM itself during initClassName call.
798     private transient String name;
799     private native String initClassName();
800
801     /**
802      * Returns the class loader for the class.  Some implementations may use
803      * null to represent the bootstrap class loader. This method will return
804      * null in such implementations if this class was loaded by the bootstrap
805      * class loader.
806      *
807      * <p>If this object
808      * represents a primitive type or voidnull is returned.
809      *
810      * @return  the class loader that loaded the class or interface
811      *          represented by this object.
812      * @throws  SecurityException
813      *          if a security manager is present, and the caller's class loader
814      *          is not {@code null} and is not the same as or an ancestor of the
815      *          class loader for the class whose class loader is requested,
816      *          and the caller does not have the
817      *          {@link RuntimePermission}{@code ("getClassLoader")}
818      * @see java.lang.ClassLoader
819      * @see SecurityManager#checkPermission
820      * @see java.lang.RuntimePermission
821      */

822     @CallerSensitive
823     @ForceInline // to ensure Reflection.getCallerClass optimization
824     public ClassLoader getClassLoader() {
825         ClassLoader cl = getClassLoader0();
826         if (cl == null)
827             return null;
828         SecurityManager sm = System.getSecurityManager();
829         if (sm != null) {
830             ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass());
831         }
832         return cl;
833     }
834
835     // Package-private to allow ClassLoader access
836     ClassLoader getClassLoader0() { return classLoader; }
837
838     /**
839      * Returns the module that this class or interface is a member of.
840      *
841      * If this class represents an array type then this method returns the
842      * {@code Module} for the element type. If this class represents a
843      * primitive type or void, then the {@code Module} object for the
844      * {@code java.base} module is returned.
845      *
846      * If this class is in an unnamed module then the {@linkplain
847      * ClassLoader#getUnnamedModule() unnamed} {@code Module} of the class
848      * loader for this class is returned.
849      *
850      * @return the module that this class or interface is a member of
851      *
852      * @since 9
853      * @spec JPMS
854      */

855     public Module getModule() {
856         return module;
857     }
858
859     // set by VM
860     private transient Module module;
861
862     // Initialized in JVM not by private constructor
863     // This field is filtered from reflection access, i.e. getDeclaredField
864     // will throw NoSuchFieldException
865     private final ClassLoader classLoader;
866
867     /**
868      * Returns an array of {@code TypeVariable} objects that represent the
869      * type variables declared by the generic declaration represented by this
870      * {@code GenericDeclaration} object, in declaration order.  Returns an
871      * array of length 0 if the underlying generic declaration declares no type
872      * variables.
873      *
874      * @return an array of {@code TypeVariable} objects that represent
875      *     the type variables declared by this generic declaration
876      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
877      *     signature of this generic declaration does not conform to
878      *     the format specified in
879      *     <cite>The Java&trade; Virtual Machine Specification</cite>
880      * @since 1.5
881      */

882     @SuppressWarnings("unchecked")
883     public TypeVariable<Class<T>>[] getTypeParameters() {
884         ClassRepository info = getGenericInfo();
885         if (info != null)
886             return (TypeVariable<Class<T>>[])info.getTypeParameters();
887         else
888             return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];
889     }
890
891
892     /**
893      * Returns the {@code Class} representing the direct superclass of the
894      * entity (classinterface, primitive type or void) represented by
895      * this {@code Class}.  If this {@code Class} represents either the
896      * {@code Object} class, an interface, a primitive type, or void, then
897      * null is returned.  If this object represents an array class then the
898      * {@code Class} object representing the {@code Object} class is
899      * returned.
900      *
901      * @return the direct superclass of the class represented by this object
902      */

903     @HotSpotIntrinsicCandidate
904     public native Class<? super T> getSuperclass();
905
906
907     /**
908      * Returns the {@code Type} representing the direct superclass of
909      * the entity (classinterface, primitive type or void) represented by
910      * this {@code Class}.
911      *
912      * <p>If the superclass is a parameterized type, the {@code Type}
913      * object returned must accurately reflect the actual type
914      * parameters used in the source code. The parameterized type
915      * representing the superclass is created if it had not been
916      * created before. See the declaration of {@link
917      * java.lang.reflect.ParameterizedType ParameterizedType} for the
918      * semantics of the creation process for parameterized types.  If
919      * this {@code Class} represents either the {@code Object}
920      * class, an interface, a primitive type, or void, then null is
921      * returned.  If this object represents an array class then the
922      * {@code Class} object representing the {@code Object} class is
923      * returned.
924      *
925      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
926      *     class signature does not conform to the format specified in
927      *     <cite>The Java&trade; Virtual Machine Specification</cite>
928      * @throws TypeNotPresentException if the generic superclass
929      *     refers to a non-existent type declaration
930      * @throws java.lang.reflect.MalformedParameterizedTypeException if the
931      *     generic superclass refers to a parameterized type that cannot be
932      *     instantiated  for any reason
933      * @return the direct superclass of the class represented by this object
934      * @since 1.5
935      */

936     public Type getGenericSuperclass() {
937         ClassRepository info = getGenericInfo();
938         if (info == null) {
939             return getSuperclass();
940         }
941
942         // Historical irregularity:
943         // Generic signature marks interfaces with superclass = Object
944         // but this API returns null for interfaces
945         if (isInterface()) {
946             return null;
947         }
948
949         return info.getSuperclass();
950     }
951
952     /**
953      * Gets the package of this class.
954      *
955      * <p>If this class represents an array type, a primitive type or void,
956      * this method returns {@code null}.
957      *
958      * @return the package of this class.
959      * @revised 9
960      * @spec JPMS
961      */

962     public Package getPackage() {
963         if (isPrimitive() || isArray()) {
964             return null;
965         }
966         ClassLoader cl = getClassLoader0();
967         return cl != null ? cl.definePackage(this)
968                           : BootLoader.definePackage(this);
969     }
970
971     /**
972      * Returns the fully qualified package name.
973      *
974      * <p> If this class is a top level class, then this method returns the fully
975      * qualified name of the package that the class is a member of, or the
976      * empty string if the class is in an unnamed package.
977      *
978      * <p> If this class is a member class, then this method is equivalent to
979      * invoking {@code getPackageName()} on the {@linkplain #getEnclosingClass
980      * enclosing class}.
981      *
982      * <p> If this class is a {@linkplain #isLocalClass local class} or an {@linkplain
983      * #isAnonymousClass() anonymous class}, then this method is equivalent to
984      * invoking {@code getPackageName()} on the {@linkplain #getDeclaringClass
985      * declaring class} of the {@linkplain #getEnclosingMethod enclosing method} or
986      * {@linkplain #getEnclosingConstructor enclosing constructor}.
987      *
988      * <p> If this class represents an array type then this method returns the
989      * package name of the element type. If this class represents a primitive
990      * type or void then the package name "{@code java.lang}" is returned.
991      *
992      * @return the fully qualified package name
993      *
994      * @since 9
995      * @spec JPMS
996      * @jls 6.7  Fully Qualified Names
997      */

998     public String getPackageName() {
999         String pn = this.packageName;
1000         if (pn == null) {
1001             Class<?> c = this;
1002             while (c.isArray()) {
1003                 c = c.getComponentType();
1004             }
1005             if (c.isPrimitive()) {
1006                 pn = "java.lang";
1007             } else {
1008                 String cn = c.getName();
1009                 int dot = cn.lastIndexOf('.');
1010                 pn = (dot != -1) ? cn.substring(0, dot).intern() : "";
1011             }
1012             this.packageName = pn;
1013         }
1014         return pn;
1015     }
1016
1017     // cached package name
1018     private transient String packageName;
1019
1020     /**
1021      * Returns the interfaces directly implemented by the class or interface
1022      * represented by this object.
1023      *
1024      * <p>If this object represents a class, the return value is an array
1025      * containing objects representing all interfaces directly implemented by
1026      * the class.  The order of the interface objects in the array corresponds
1027      * to the order of the interface names in the {@code implements} clause of
1028      * the declaration of the class represented by this object.  For example,
1029      * given the declaration:
1030      * <blockquote>
1031      * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
1032      * </blockquote>
1033      * suppose the value of {@code s} is an instance of
1034      * {@code Shimmer}; the value of the expression:
1035      * <blockquote>
1036      * {@code s.getClass().getInterfaces()[0]}
1037      * </blockquote>
1038      * is the {@code Class} object that represents interface
1039      * {@code FloorWax}; and the value of:
1040      * <blockquote>
1041      * {@code s.getClass().getInterfaces()[1]}
1042      * </blockquote>
1043      * is the {@code Class} object that represents interface
1044      * {@code DessertTopping}.
1045      *
1046      * <p>If this object represents an interface, the array contains objects
1047      * representing all interfaces directly extended by the interface.  The
1048      * order of the interface objects in the array corresponds to the order of
1049      * the interface names in the {@code extends} clause of the declaration of
1050      * the interface represented by this object.
1051      *
1052      * <p>If this object represents a class or interface that implements no
1053      * interfaces, the method returns an array of length 0.
1054      *
1055      * <p>If this object represents a primitive type or void, the method
1056      * returns an array of length 0.
1057      *
1058      * <p>If this {@code Class} object represents an array type, the
1059      * interfaces {@code Cloneable} and {@code java.io.Serializable} are
1060      * returned in that order.
1061      *
1062      * @return an array of interfaces directly implemented by this class
1063      */

1064     public Class<?>[] getInterfaces() {
1065         // defensively copy before handing over to user code
1066         return getInterfaces(true);
1067     }
1068
1069     private Class<?>[] getInterfaces(boolean cloneArray) {
1070         ReflectionData<T> rd = reflectionData();
1071         if (rd == null) {
1072             // no cloning required
1073             return getInterfaces0();
1074         } else {
1075             Class<?>[] interfaces = rd.interfaces;
1076             if (interfaces == null) {
1077                 interfaces = getInterfaces0();
1078                 rd.interfaces = interfaces;
1079             }
1080             // defensively copy if requested
1081             return cloneArray ? interfaces.clone() : interfaces;
1082         }
1083     }
1084
1085     private native Class<?>[] getInterfaces0();
1086
1087     /**
1088      * Returns the {@code Type}s representing the interfaces
1089      * directly implemented by the class or interface represented by
1090      * this object.
1091      *
1092      * <p>If a superinterface is a parameterized type, the
1093      * {@code Type} object returned for it must accurately reflect
1094      * the actual type parameters used in the source code. The
1095      * parameterized type representing each superinterface is created
1096      * if it had not been created before. See the declaration of
1097      * {@link java.lang.reflect.ParameterizedType ParameterizedType}
1098      * for the semantics of the creation process for parameterized
1099      * types.
1100      *
1101      * <p>If this object represents a class, the return value is an array
1102      * containing objects representing all interfaces directly implemented by
1103      * the class.  The order of the interface objects in the array corresponds
1104      * to the order of the interface names in the {@code implements} clause of
1105      * the declaration of the class represented by this object.
1106      *
1107      * <p>If this object represents an interface, the array contains objects
1108      * representing all interfaces directly extended by the interface.  The
1109      * order of the interface objects in the array corresponds to the order of
1110      * the interface names in the {@code extends} clause of the declaration of
1111      * the interface represented by this object.
1112      *
1113      * <p>If this object represents a class or interface that implements no
1114      * interfaces, the method returns an array of length 0.
1115      *
1116      * <p>If this object represents a primitive type or void, the method
1117      * returns an array of length 0.
1118      *
1119      * <p>If this {@code Class} object represents an array type, the
1120      * interfaces {@code Cloneable} and {@code java.io.Serializable} are
1121      * returned in that order.
1122      *
1123      * @throws java.lang.reflect.GenericSignatureFormatError
1124      *     if the generic class signature does not conform to the format
1125      *     specified in
1126      *     <cite>The Java&trade; Virtual Machine Specification</cite>
1127      * @throws TypeNotPresentException if any of the generic
1128      *     superinterfaces refers to a non-existent type declaration
1129      * @throws java.lang.reflect.MalformedParameterizedTypeException
1130      *     if any of the generic superinterfaces refer to a parameterized
1131      *     type that cannot be instantiated for any reason
1132      * @return an array of interfaces directly implemented by this class
1133      * @since 1.5
1134      */

1135     public Type[] getGenericInterfaces() {
1136         ClassRepository info = getGenericInfo();
1137         return (info == null) ?  getInterfaces() : info.getSuperInterfaces();
1138     }
1139
1140
1141     /**
1142      * Returns the {@code Class} representing the component type of an
1143      * array.  If this class does not represent an array class this method
1144      * returns null.
1145      *
1146      * @return the {@code Class} representing the component type of this
1147      * class if this class is an array
1148      * @see     java.lang.reflect.Array
1149      * @since 1.1
1150      */

1151     public Class<?> getComponentType() {
1152         // Only return for array types. Storage may be reused for Class for instance types.
1153         if (isArray()) {
1154             return componentType;
1155         } else {
1156             return null;
1157         }
1158     }
1159
1160     private final Class<?> componentType;
1161
1162
1163     /**
1164      * Returns the Java language modifiers for this class or interface, encoded
1165      * in an integer. The modifiers consist of the Java Virtual Machine's
1166      * constants for {@code public}, {@code protected},
1167      * {@code private}, {@code final}, {@code static},
1168      * {@code abstract} and {@code interface}; they should be decoded
1169      * using the methods of class {@code Modifier}.
1170      *
1171      * <p> If the underlying class is an array class, then its
1172      * {@code public}, {@code private} and {@code protected}
1173      * modifiers are the same as those of its component type.  If this
1174      * {@code Class} represents a primitive type or void, its
1175      * {@code public} modifier is always {@code true}, and its
1176      * {@code protected} and {@code private} modifiers are always
1177      * {@code false}. If this object represents an array class, a
1178      * primitive type or void, then its {@code final} modifier is always
1179      * {@code true} and its interface modifier is always
1180      * {@code false}. The values of its other modifiers are not determined
1181      * by this specification.
1182      *
1183      * <p> The modifier encodings are defined in <em>The Java Virtual Machine
1184      * Specification</em>, table 4.1.
1185      *
1186      * @return the {@code int} representing the modifiers for this class
1187      * @see     java.lang.reflect.Modifier
1188      * @since 1.1
1189      */

1190     @HotSpotIntrinsicCandidate
1191     public native int getModifiers();
1192
1193
1194     /**
1195      * Gets the signers of this class.
1196      *
1197      * @return  the signers of this class, or null if there are no signers.  In
1198      *          particular, this method returns null if this object represents
1199      *          a primitive type or void.
1200      * @since   1.1
1201      */

1202     public native Object[] getSigners();
1203
1204
1205     /**
1206      * Set the signers of this class.
1207      */

1208     native void setSigners(Object[] signers);
1209
1210
1211     /**
1212      * If this {@code Class} object represents a local or anonymous
1213      * class within a method, returns a {@link
1214      * java.lang.reflect.Method Method} object representing the
1215      * immediately enclosing method of the underlying class. Returns
1216      * {@code null} otherwise.
1217      *
1218      * In particular, this method returns {@code nullif the underlying
1219      * class is a local or anonymous class immediately enclosed by a type
1220      * declaration, instance initializer or static initializer.
1221      *
1222      * @return the immediately enclosing method of the underlying classif
1223      *     that class is a local or anonymous class; otherwise {@code null}.
1224      *
1225      * @throws SecurityException
1226      *         If a security manager, <i>s</i>, is present and any of the
1227      *         following conditions is met:
1228      *
1229      *         <ul>
1230      *
1231      *         <li> the caller's class loader is not the same as the
1232      *         class loader of the enclosing class and invocation of
1233      *         {@link SecurityManager#checkPermission
1234      *         s.checkPermission} method with
1235      *         {@code RuntimePermission("accessDeclaredMembers")}
1236      *         denies access to the methods within the enclosing class
1237      *
1238      *         <li> the caller's class loader is not the same as or an
1239      *         ancestor of the class loader for the enclosing class and
1240      *         invocation of {@link SecurityManager#checkPackageAccess
1241      *         s.checkPackageAccess()} denies access to the package
1242      *         of the enclosing class
1243      *
1244      *         </ul>
1245      * @since 1.5
1246      */

1247     @CallerSensitive
1248     public Method getEnclosingMethod() throws SecurityException {
1249         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1250
1251         if (enclosingInfo == null)
1252             return null;
1253         else {
1254             if (!enclosingInfo.isMethod())
1255                 return null;
1256
1257             MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
1258                                                               getFactory());
1259             Class<?>   returnType       = toClass(typeInfo.getReturnType());
1260             Type []    parameterTypes   = typeInfo.getParameterTypes();
1261             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1262
1263             // Convert Types to Classes; returned types *should*
1264             // be class objects since the methodDescriptor's used
1265             // don't have generics information
1266             for(int i = 0; i < parameterClasses.length; i++)
1267                 parameterClasses[i] = toClass(parameterTypes[i]);
1268
1269             // Perform access check
1270             final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1271             SecurityManager sm = System.getSecurityManager();
1272             if (sm != null) {
1273                 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED,
1274                                                      Reflection.getCallerClass(), true);
1275             }
1276             Method[] candidates = enclosingCandidate.privateGetDeclaredMethods(false);
1277
1278             /*
1279              * Loop over all declared methods; match method name,
1280              * number of and type of parameters, *and* return
1281              * type.  Matching return type is also necessary
1282              * because of covariant returns, etc.
1283              */

1284             ReflectionFactory fact = getReflectionFactory();
1285             for (Method m : candidates) {
1286                 if (m.getName().equals(enclosingInfo.getName()) &&
1287                     arrayContentsEq(parameterClasses,
1288                                     fact.getExecutableSharedParameterTypes(m))) {
1289                     // finally, check return type
1290                     if (m.getReturnType().equals(returnType)) {
1291                         return fact.copyMethod(m);
1292                     }
1293                 }
1294             }
1295
1296             throw new InternalError("Enclosing method not found");
1297         }
1298     }
1299
1300     private native Object[] getEnclosingMethod0();
1301
1302     private EnclosingMethodInfo getEnclosingMethodInfo() {
1303         Object[] enclosingInfo = getEnclosingMethod0();
1304         if (enclosingInfo == null)
1305             return null;
1306         else {
1307             return new EnclosingMethodInfo(enclosingInfo);
1308         }
1309     }
1310
1311     private static final class EnclosingMethodInfo {
1312         private final Class<?> enclosingClass;
1313         private final String name;
1314         private final String descriptor;
1315
1316         static void validate(Object[] enclosingInfo) {
1317             if (enclosingInfo.length != 3)
1318                 throw new InternalError("Malformed enclosing method information");
1319             try {
1320                 // The array is expected to have three elements:
1321
1322                 // the immediately enclosing class
1323                 Class<?> enclosingClass = (Class<?>)enclosingInfo[0];
1324                 assert(enclosingClass != null);
1325
1326                 // the immediately enclosing method or constructor's
1327                 // name (can be null).
1328                 String name = (String)enclosingInfo[1];
1329
1330                 // the immediately enclosing method or constructor's
1331                 // descriptor (null iff name is).
1332                 String descriptor = (String)enclosingInfo[2];
1333                 assert((name != null && descriptor != null) || name == descriptor);
1334             } catch (ClassCastException cce) {
1335                 throw new InternalError("Invalid type in enclosing method information", cce);
1336             }
1337         }
1338
1339         EnclosingMethodInfo(Object[] enclosingInfo) {
1340             validate(enclosingInfo);
1341             this.enclosingClass = (Class<?>)enclosingInfo[0];
1342             this.name = (String)enclosingInfo[1];
1343             this.descriptor = (String)enclosingInfo[2];
1344         }
1345
1346         boolean isPartial() {
1347             return enclosingClass == null || name == null || descriptor == null;
1348         }
1349
1350         boolean isConstructor() { return !isPartial() && "<init>".equals(name); }
1351
1352         boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }
1353
1354         Class<?> getEnclosingClass() { return enclosingClass; }
1355
1356         String getName() { return name; }
1357
1358         String getDescriptor() { return descriptor; }
1359
1360     }
1361
1362     private static Class<?> toClass(Type o) {
1363         if (o instanceof GenericArrayType)
1364             return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
1365                                      0)
1366                 .getClass();
1367         return (Class<?>)o;
1368      }
1369
1370     /**
1371      * If this {@code Class} object represents a local or anonymous
1372      * class within a constructor, returns a {@link
1373      * java.lang.reflect.Constructor Constructor} object representing
1374      * the immediately enclosing constructor of the underlying
1375      * class. Returns {@code null} otherwise.  In particular, this
1376      * method returns {@code nullif the underlying class is a local
1377      * or anonymous class immediately enclosed by a type declaration,
1378      * instance initializer or static initializer.
1379      *
1380      * @return the immediately enclosing constructor of the underlying classif
1381      *     that class is a local or anonymous class; otherwise {@code null}.
1382      * @throws SecurityException
1383      *         If a security manager, <i>s</i>, is present and any of the
1384      *         following conditions is met:
1385      *
1386      *         <ul>
1387      *
1388      *         <li> the caller's class loader is not the same as the
1389      *         class loader of the enclosing class and invocation of
1390      *         {@link SecurityManager#checkPermission
1391      *         s.checkPermission} method with
1392      *         {@code RuntimePermission("accessDeclaredMembers")}
1393      *         denies access to the constructors within the enclosing class
1394      *
1395      *         <li> the caller's class loader is not the same as or an
1396      *         ancestor of the class loader for the enclosing class and
1397      *         invocation of {@link SecurityManager#checkPackageAccess
1398      *         s.checkPackageAccess()} denies access to the package
1399      *         of the enclosing class
1400      *
1401      *         </ul>
1402      * @since 1.5
1403      */

1404     @CallerSensitive
1405     public Constructor<?> getEnclosingConstructor() throws SecurityException {
1406         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1407
1408         if (enclosingInfo == null)
1409             return null;
1410         else {
1411             if (!enclosingInfo.isConstructor())
1412                 return null;
1413
1414             ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
1415                                                                         getFactory());
1416             Type []    parameterTypes   = typeInfo.getParameterTypes();
1417             Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1418
1419             // Convert Types to Classes; returned types *should*
1420             // be class objects since the methodDescriptor's used
1421             // don't have generics information
1422             for(int i = 0; i < parameterClasses.length; i++)
1423                 parameterClasses[i] = toClass(parameterTypes[i]);
1424
1425             // Perform access check
1426             final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1427             SecurityManager sm = System.getSecurityManager();
1428             if (sm != null) {
1429                 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED,
1430                                                      Reflection.getCallerClass(), true);
1431             }
1432
1433             Constructor<?>[] candidates = enclosingCandidate
1434                     .privateGetDeclaredConstructors(false);
1435             /*
1436              * Loop over all declared constructors; match number
1437              * of and type of parameters.
1438              */

1439             ReflectionFactory fact = getReflectionFactory();
1440             for (Constructor<?> c : candidates) {
1441                 if (arrayContentsEq(parameterClasses,
1442                                     fact.getExecutableSharedParameterTypes(c))) {
1443                     return fact.copyConstructor(c);
1444                 }
1445             }
1446
1447             throw new InternalError("Enclosing constructor not found");
1448         }
1449     }
1450
1451
1452     /**
1453      * If the class or interface represented by this {@code Class} object
1454      * is a member of another class, returns the {@code Class} object
1455      * representing the class in which it was declared.  This method returns
1456      * null if this class or interface is not a member of any other class.  If
1457      * this {@code Class} object represents an array class, a primitive
1458      * type, or void,then this method returns null.
1459      *
1460      * @return the declaring class for this class
1461      * @throws SecurityException
1462      *         If a security manager, <i>s</i>, is present and the caller's
1463      *         class loader is not the same as or an ancestor of the class
1464      *         loader for the declaring class and invocation of {@link
1465      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
1466      *         denies access to the package of the declaring class
1467      * @since 1.1
1468      */

1469     @CallerSensitive
1470     public Class<?> getDeclaringClass() throws SecurityException {
1471         final Class<?> candidate = getDeclaringClass0();
1472
1473         if (candidate != null) {
1474             SecurityManager sm = System.getSecurityManager();
1475             if (sm != null) {
1476                 candidate.checkPackageAccess(sm,
1477                     ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
1478             }
1479         }
1480         return candidate;
1481     }
1482
1483     private native Class<?> getDeclaringClass0();
1484
1485
1486     /**
1487      * Returns the immediately enclosing class of the underlying
1488      * class.  If the underlying class is a top level class this
1489      * method returns {@code null}.
1490      * @return the immediately enclosing class of the underlying class
1491      * @exception  SecurityException
1492      *             If a security manager, <i>s</i>, is present and the caller's
1493      *             class loader is not the same as or an ancestor of the class
1494      *             loader for the enclosing class and invocation of {@link
1495      *             SecurityManager#checkPackageAccess s.checkPackageAccess()}
1496      *             denies access to the package of the enclosing class
1497      * @since 1.5
1498      */

1499     @CallerSensitive
1500     public Class<?> getEnclosingClass() throws SecurityException {
1501         // There are five kinds of classes (or interfaces):
1502         // a) Top level classes
1503         // b) Nested classes (static member classes)
1504         // c) Inner classes (non-static member classes)
1505         // d) Local classes (named classes declared within a method)
1506         // e) Anonymous classes
1507
1508
1509         // JVM Spec 4.7.7: A class must have an EnclosingMethod
1510         // attribute if and only if it is a local class or an
1511         // anonymous class.
1512         EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1513         Class<?> enclosingCandidate;
1514
1515         if (enclosingInfo == null) {
1516             // This is a top level or a nested class or an inner class (a, b, or c)
1517             enclosingCandidate = getDeclaringClass0();
1518         } else {
1519             Class<?> enclosingClass = enclosingInfo.getEnclosingClass();
1520             // This is a local class or an anonymous class (d or e)
1521             if (enclosingClass == this || enclosingClass == null)
1522                 throw new InternalError("Malformed enclosing method information");
1523             else
1524                 enclosingCandidate = enclosingClass;
1525         }
1526
1527         if (enclosingCandidate != null) {
1528             SecurityManager sm = System.getSecurityManager();
1529             if (sm != null) {
1530                 enclosingCandidate.checkPackageAccess(sm,
1531                     ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
1532             }
1533         }
1534         return enclosingCandidate;
1535     }
1536
1537     /**
1538      * Returns the simple name of the underlying class as given in the
1539      * source code. Returns an empty string if the underlying class is
1540      * anonymous.
1541      *
1542      * <p>The simple name of an array is the simple name of the
1543      * component type with "[]" appended.  In particular the simple
1544      * name of an array whose component type is anonymous is "[]".
1545      *
1546      * @return the simple name of the underlying class
1547      * @since 1.5
1548      */

1549     public String getSimpleName() {
1550         ReflectionData<T> rd = reflectionData();
1551         String simpleName = rd.simpleName;
1552         if (simpleName == null) {
1553             rd.simpleName = simpleName = getSimpleName0();
1554         }
1555         return simpleName;
1556     }
1557
1558     private String getSimpleName0() {
1559         if (isArray()) {
1560             return getComponentType().getSimpleName() + "[]";
1561         }
1562         String simpleName = getSimpleBinaryName();
1563         if (simpleName == null) { // top level class
1564             simpleName = getName();
1565             simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1566         }
1567         return simpleName;
1568     }
1569
1570     /**
1571      * Return an informative string for the name of this type.
1572      *
1573      * @return an informative string for the name of this type
1574      * @since 1.8
1575      */

1576     public String getTypeName() {
1577         if (isArray()) {
1578             try {
1579                 Class<?> cl = this;
1580                 int dimensions = 0;
1581                 do {
1582                     dimensions++;
1583                     cl = cl.getComponentType();
1584                 } while (cl.isArray());
1585                 StringBuilder sb = new StringBuilder();
1586                 sb.append(cl.getName());
1587                 for (int i = 0; i < dimensions; i++) {
1588                     sb.append("[]");
1589                 }
1590                 return sb.toString();
1591             } catch (Throwable e) { /*FALLTHRU*/ }
1592         }
1593         return getName();
1594     }
1595
1596     /**
1597      * Returns the canonical name of the underlying class as
1598      * defined by the Java Language Specification.  Returns null if
1599      * the underlying class does not have a canonical name (i.e., if
1600      * it is a local or anonymous class or an array whose component
1601      * type does not have a canonical name).
1602      * @return the canonical name of the underlying class if it exists, and
1603      * {@code null} otherwise.
1604      * @since 1.5
1605      */

1606     public String getCanonicalName() {
1607         ReflectionData<T> rd = reflectionData();
1608         String canonicalName = rd.canonicalName;
1609         if (canonicalName == null) {
1610             rd.canonicalName = canonicalName = getCanonicalName0();
1611         }
1612         return canonicalName == ReflectionData.NULL_SENTINEL? null : canonicalName;
1613     }
1614
1615     private String getCanonicalName0() {
1616         if (isArray()) {
1617             String canonicalName = getComponentType().getCanonicalName();
1618             if (canonicalName != null)
1619                 return canonicalName + "[]";
1620             else
1621                 return ReflectionData.NULL_SENTINEL;
1622         }
1623         if (isLocalOrAnonymousClass())
1624             return ReflectionData.NULL_SENTINEL;
1625         Class<?> enclosingClass = getEnclosingClass();
1626         if (enclosingClass == null) { // top level class
1627             return getName();
1628         } else {
1629             String enclosingName = enclosingClass.getCanonicalName();
1630             if (enclosingName == null)
1631                 return ReflectionData.NULL_SENTINEL;
1632             return enclosingName + "." + getSimpleName();
1633         }
1634     }
1635
1636     /**
1637      * Returns {@code trueif and only if the underlying class
1638      * is an anonymous class.
1639      *
1640      * @return {@code trueif and only if this class is an anonymous class.
1641      * @since 1.5
1642      */

1643     public boolean isAnonymousClass() {
1644         return !isArray() && isLocalOrAnonymousClass() &&
1645                 getSimpleBinaryName0() == null;
1646     }
1647
1648     /**
1649      * Returns {@code trueif and only if the underlying class
1650      * is a local class.
1651      *
1652      * @return {@code trueif and only if this class is a local class.
1653      * @since 1.5
1654      */

1655     public boolean isLocalClass() {
1656         return isLocalOrAnonymousClass() &&
1657                 (isArray() || getSimpleBinaryName0() != null);
1658     }
1659
1660     /**
1661      * Returns {@code trueif and only if the underlying class
1662      * is a member class.
1663      *
1664      * @return {@code trueif and only if this class is a member class.
1665      * @since 1.5
1666      */

1667     public boolean isMemberClass() {
1668         return !isLocalOrAnonymousClass() && getDeclaringClass0() != null;
1669     }
1670
1671     /**
1672      * Returns the "simple binary name" of the underlying class, i.e.,
1673      * the binary name without the leading enclosing class name.
1674      * Returns {@code nullif the underlying class is a top level
1675      * class.
1676      */

1677     private String getSimpleBinaryName() {
1678         if (isTopLevelClass())
1679             return null;
1680         String name = getSimpleBinaryName0();
1681         if (name == null// anonymous class
1682             return "";
1683         return name;
1684     }
1685
1686     private native String getSimpleBinaryName0();
1687
1688     /**
1689      * Returns {@code trueif this is a top level class.  Returns {@code false}
1690      * otherwise.
1691      */

1692     private boolean isTopLevelClass() {
1693         return !isLocalOrAnonymousClass() && getDeclaringClass0() == null;
1694     }
1695
1696     /**
1697      * Returns {@code trueif this is a local class or an anonymous
1698      * class.  Returns {@code false} otherwise.
1699      */

1700     private boolean isLocalOrAnonymousClass() {
1701         // JVM Spec 4.7.7: A class must have an EnclosingMethod
1702         // attribute if and only if it is a local class or an
1703         // anonymous class.
1704         return hasEnclosingMethodInfo();
1705     }
1706
1707     private boolean hasEnclosingMethodInfo() {
1708         Object[] enclosingInfo = getEnclosingMethod0();
1709         if (enclosingInfo != null) {
1710             EnclosingMethodInfo.validate(enclosingInfo);
1711             return true;
1712         }
1713         return false;
1714     }
1715
1716     /**
1717      * Returns an array containing {@code Class} objects representing all
1718      * the public classes and interfaces that are members of the class
1719      * represented by this {@code Class} object.  This includes public
1720      * class and interface members inherited from superclasses and public class
1721      * and interface members declared by the class.  This method returns an
1722      * array of length 0 if this {@code Class} object has no public member
1723      * classes or interfaces.  This method also returns an array of length 0 if
1724      * this {@code Class} object represents a primitive type, an array
1725      * class, or void.
1726      *
1727      * @return the array of {@code Class} objects representing the public
1728      *         members of this class
1729      * @throws SecurityException
1730      *         If a security manager, <i>s</i>, is present and
1731      *         the caller's class loader is not the same as or an
1732      *         ancestor of the class loader for the current class and
1733      *         invocation of {@link SecurityManager#checkPackageAccess
1734      *         s.checkPackageAccess()} denies access to the package
1735      *         of this class.
1736      *
1737      * @since 1.1
1738      */

1739     @CallerSensitive
1740     public Class<?>[] getClasses() {
1741         SecurityManager sm = System.getSecurityManager();
1742         if (sm != null) {
1743             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false);
1744         }
1745
1746         // Privileged so this implementation can look at DECLARED classes,
1747         // something the caller might not have privilege to do.  The code here
1748         // is allowed to look at DECLARED classes because (1) it does not hand
1749         // out anything other than public members and (2) public member access
1750         // has already been ok'd by the SecurityManager.
1751
1752         return java.security.AccessController.doPrivileged(
1753             new java.security.PrivilegedAction<>() {
1754                 public Class<?>[] run() {
1755                     List<Class<?>> list = new ArrayList<>();
1756                     Class<?> currentClass = Class.this;
1757                     while (currentClass != null) {
1758                         for (Class<?> m : currentClass.getDeclaredClasses()) {
1759                             if (Modifier.isPublic(m.getModifiers())) {
1760                                 list.add(m);
1761                             }
1762                         }
1763                         currentClass = currentClass.getSuperclass();
1764                     }
1765                     return list.toArray(new Class<?>[0]);
1766                 }
1767             });
1768     }
1769
1770
1771     /**
1772      * Returns an array containing {@code Field} objects reflecting all
1773      * the accessible public fields of the class or interface represented by
1774      * this {@code Class} object.
1775      *
1776      * <p> If this {@code Class} object represents a class or interface with
1777      * no accessible public fields, then this method returns an array of length
1778      * 0.
1779      *
1780      * <p> If this {@code Class} object represents a class, then this method
1781      * returns the public fields of the class and of all its superclasses and
1782      * superinterfaces.
1783      *
1784      * <p> If this {@code Class} object represents an interface, then this
1785      * method returns the fields of the interface and of all its
1786      * superinterfaces.
1787      *
1788      * <p> If this {@code Class} object represents an array type, a primitive
1789      * type, or void, then this method returns an array of length 0.
1790      *
1791      * <p> The elements in the returned array are not sorted and are not in any
1792      * particular order.
1793      *
1794      * @return the array of {@code Field} objects representing the
1795      *         public fields
1796      * @throws SecurityException
1797      *         If a security manager, <i>s</i>, is present and
1798      *         the caller's class loader is not the same as or an
1799      *         ancestor of the class loader for the current class and
1800      *         invocation of {@link SecurityManager#checkPackageAccess
1801      *         s.checkPackageAccess()} denies access to the package
1802      *         of this class.
1803      *
1804      * @since 1.1
1805      * @jls 8.2 Class Members
1806      * @jls 8.3 Field Declarations
1807      */

1808     @CallerSensitive
1809     public Field[] getFields() throws SecurityException {
1810         SecurityManager sm = System.getSecurityManager();
1811         if (sm != null) {
1812             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
1813         }
1814         return copyFields(privateGetPublicFields());
1815     }
1816
1817
1818     /**
1819      * Returns an array containing {@code Method} objects reflecting all the
1820      * public methods of the class or interface represented by this {@code
1821      * Class} object, including those declared by the class or interface and
1822      * those inherited from superclasses and superinterfaces.
1823      *
1824      * <p> If this {@code Class} object represents an array type, then the
1825      * returned array has a {@code Method} object for each of the public
1826      * methods inherited by the array type from {@code Object}. It does not
1827      * contain a {@code Method} object for {@code clone()}.
1828      *
1829      * <p> If this {@code Class} object represents an interface then the
1830      * returned array does not contain any implicitly declared methods from
1831      * {@code Object}. Therefore, if no methods are explicitly declared in
1832      * this interface or any of its superinterfaces then the returned array
1833      * has length 0. (Note that a {@code Class} object which represents a class
1834      * always has public methods, inherited from {@code Object}.)
1835      *
1836      * <p> The returned array never contains methods with names "{@code <init>}"
1837      * or "{@code <clinit>}".
1838      *
1839      * <p> The elements in the returned array are not sorted and are not in any
1840      * particular order.
1841      *
1842      * <p> Generally, the result is computed as with the following 4 step algorithm.
1843      * Let C be the class or interface represented by this {@code Class} object:
1844      * <ol>
1845      * <li> A union of methods is composed of:
1846      *   <ol type="a">
1847      *   <li> C's declared public instance and static methods as returned by
1848      *        {@link #getDeclaredMethods()} and filtered to include only public
1849      *        methods.</li>
1850      *   <li> If C is a class other than {@code Object}, then include the result
1851      *        of invoking this algorithm recursively on the superclass of C.</li>
1852      *   <li> Include the results of invoking this algorithm recursively on all
1853      *        direct superinterfaces of C, but include only instance methods.</li>
1854      *   </ol></li>
1855      * <li> Union from step 1 is partitioned into subsets of methods with same
1856      *      signature (name, parameter types) and return type.</li>
1857      * <li> Within each such subset only the most specific methods are selected.
1858      *      Let method M be a method from a set of methods with same signature
1859      *      and return type. M is most specific if there is no such method
1860      *      N != M from the same set, such that N is more specific than M.
1861      *      N is more specific than M if:
1862      *   <ol type="a">
1863      *   <li> N is declared by a class and M is declared by an interface; or</li>
1864      *   <li> N and M are both declared by classes or both by interfaces and
1865      *        N's declaring type is the same as or a subtype of M's declaring type
1866      *        (clearly, if M's and N's declaring types are the same type, then
1867      *        M and N are the same method).</li>
1868      *   </ol></li>
1869      * <li> The result of this algorithm is the union of all selected methods from
1870      *      step 3.</li>
1871      * </ol>
1872      *
1873      * @apiNote There may be more than one method with a particular name
1874      * and parameter types in a class because while the Java language forbids a
1875      * class to declare multiple methods with the same signature but different
1876      * return types, the Java virtual machine does not.  This
1877      * increased flexibility in the virtual machine can be used to
1878      * implement various language features.  For example, covariant
1879      * returns can be implemented with {@linkplain
1880      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
1881      * method and the overriding method would have the same
1882      * signature but different return types.
1883      *
1884      * @return the array of {@code Method} objects representing the
1885      *         public methods of this class
1886      * @throws SecurityException
1887      *         If a security manager, <i>s</i>, is present and
1888      *         the caller's class loader is not the same as or an
1889      *         ancestor of the class loader for the current class and
1890      *         invocation of {@link SecurityManager#checkPackageAccess
1891      *         s.checkPackageAccess()} denies access to the package
1892      *         of this class.
1893      *
1894      * @jls 8.2 Class Members
1895      * @jls 8.4 Method Declarations
1896      * @since 1.1
1897      */

1898     @CallerSensitive
1899     public Method[] getMethods() throws SecurityException {
1900         SecurityManager sm = System.getSecurityManager();
1901         if (sm != null) {
1902             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
1903         }
1904         return copyMethods(privateGetPublicMethods());
1905     }
1906
1907
1908     /**
1909      * Returns an array containing {@code Constructor} objects reflecting
1910      * all the public constructors of the class represented by this
1911      * {@code Class} object.  An array of length 0 is returned if the
1912      * class has no public constructors, or if the class is an array class, or
1913      * if the class reflects a primitive type or void.
1914      *
1915      * Note that while this method returns an array of {@code
1916      * Constructor<T>} objects (that is an array of constructors from
1917      * this class), the return type of this method is {@code
1918      * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
1919      * might be expected.  This less informative return type is
1920      * necessary since after being returned from this method, the
1921      * array could be modified to hold {@code Constructor} objects for
1922      * different classes, which would violate the type guarantees of
1923      * {@code Constructor<T>[]}.
1924      *
1925      * @return the array of {@code Constructor} objects representing the
1926      *         public constructors of this class
1927      * @throws SecurityException
1928      *         If a security manager, <i>s</i>, is present and
1929      *         the caller's class loader is not the same as or an
1930      *         ancestor of the class loader for the current class and
1931      *         invocation of {@link SecurityManager#checkPackageAccess
1932      *         s.checkPackageAccess()} denies access to the package
1933      *         of this class.
1934      *
1935      * @since 1.1
1936      */

1937     @CallerSensitive
1938     public Constructor<?>[] getConstructors() throws SecurityException {
1939         SecurityManager sm = System.getSecurityManager();
1940         if (sm != null) {
1941             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
1942         }
1943         return copyConstructors(privateGetDeclaredConstructors(true));
1944     }
1945
1946
1947     /**
1948      * Returns a {@code Field} object that reflects the specified public member
1949      * field of the class or interface represented by this {@code Class}
1950      * object. The {@code name} parameter is a {@code String} specifying the
1951      * simple name of the desired field.
1952      *
1953      * <p> The field to be reflected is determined by the algorithm that
1954      * follows.  Let C be the class or interface represented by this object:
1955      *
1956      * <OL>
1957      * <LI> If C declares a public field with the name specified, that is the
1958      *      field to be reflected.</LI>
1959      * <LI> If no field was found in step 1 above, this algorithm is applied
1960      *      recursively to each direct superinterface of C. The direct
1961      *      superinterfaces are searched in the order they were declared.</LI>
1962      * <LI> If no field was found in steps 1 and 2 above, and C has a
1963      *      superclass S, then this algorithm is invoked recursively upon S.
1964      *      If C has no superclass, then a {@code NoSuchFieldException}
1965      *      is thrown.</LI>
1966      * </OL>
1967      *
1968      * <p> If this {@code Class} object represents an array type, then this
1969      * method does not find the {@code length} field of the array type.
1970      *
1971      * @param name the field name
1972      * @return the {@code Field} object of this class specified by
1973      *         {@code name}
1974      * @throws NoSuchFieldException if a field with the specified name is
1975      *         not found.
1976      * @throws NullPointerException if {@code name} is {@code null}
1977      * @throws SecurityException
1978      *         If a security manager, <i>s</i>, is present and
1979      *         the caller's class loader is not the same as or an
1980      *         ancestor of the class loader for the current class and
1981      *         invocation of {@link SecurityManager#checkPackageAccess
1982      *         s.checkPackageAccess()} denies access to the package
1983      *         of this class.
1984      *
1985      * @since 1.1
1986      * @jls 8.2 Class Members
1987      * @jls 8.3 Field Declarations
1988      */

1989     @CallerSensitive
1990     public Field getField(String name)
1991         throws NoSuchFieldException, SecurityException {
1992         Objects.requireNonNull(name);
1993         SecurityManager sm = System.getSecurityManager();
1994         if (sm != null) {
1995             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
1996         }
1997         Field field = getField0(name);
1998         if (field == null) {
1999             throw new NoSuchFieldException(name);
2000         }
2001         return getReflectionFactory().copyField(field);
2002     }
2003
2004
2005     /**
2006      * Returns a {@code Method} object that reflects the specified public
2007      * member method of the class or interface represented by this
2008      * {@code Class} object. The {@code name} parameter is a
2009      * {@code String} specifying the simple name of the desired method. The
2010      * {@code parameterTypes} parameter is an array of {@code Class}
2011      * objects that identify the method's formal parameter types, in declared
2012      * order. If {@code parameterTypes} is {@code null}, it is
2013      * treated as if it were an empty array.
2014      *
2015      * <p> If this {@code Class} object represents an array type, then this
2016      * method finds any public method inherited by the array type from
2017      * {@code Object} except method {@code clone()}.
2018      *
2019      * <p> If this {@code Class} object represents an interface then this
2020      * method does not find any implicitly declared method from
2021      * {@code Object}. Therefore, if no methods are explicitly declared in
2022      * this interface or any of its superinterfaces, then this method does not
2023      * find any method.
2024      *
2025      * <p> This method does not find any method with name "{@code <init>}" or
2026      * "{@code <clinit>}".
2027      *
2028      * <p> Generally, the method to be reflected is determined by the 4 step
2029      * algorithm that follows.
2030      * Let C be the class or interface represented by this {@code Class} object:
2031      * <ol>
2032      * <li> A union of methods is composed of:
2033      *   <ol type="a">
2034      *   <li> C's declared public instance and static methods as returned by
2035      *        {@link #getDeclaredMethods()} and filtered to include only public
2036      *        methods that match given {@code name} and {@code parameterTypes}</li>
2037      *   <li> If C is a class other than {@code Object}, then include the result
2038      *        of invoking this algorithm recursively on the superclass of C.</li>
2039      *   <li> Include the results of invoking this algorithm recursively on all
2040      *        direct superinterfaces of C, but include only instance methods.</li>
2041      *   </ol></li>
2042      * <li> This union is partitioned into subsets of methods with same
2043      *      return type (the selection of methods from step 1 also guarantees that
2044      *      they have the same method name and parameter types).</li>
2045      * <li> Within each such subset only the most specific methods are selected.
2046      *      Let method M be a method from a set of methods with same VM
2047      *      signature (return type, name, parameter types).
2048      *      M is most specific if there is no such method N != M from the same
2049      *      set, such that N is more specific than M. N is more specific than M
2050      *      if:
2051      *   <ol type="a">
2052      *   <li> N is declared by a class and M is declared by an interface; or</li>
2053      *   <li> N and M are both declared by classes or both by interfaces and
2054      *        N's declaring type is the same as or a subtype of M's declaring type
2055      *        (clearly, if M's and N's declaring types are the same type, then
2056      *        M and N are the same method).</li>
2057      *   </ol></li>
2058      * <li> The result of this algorithm is chosen arbitrarily from the methods
2059      *      with most specific return type among all selected methods from step 3.
2060      *      Let R be a return type of a method M from the set of all selected methods
2061      *      from step 3. M is a method with most specific return type if there is
2062      *      no such method N != M from the same set, having return type S != R,
2063      *      such that S is a subtype of R as determined by
2064      *      R.class.{@link #isAssignableFrom}(S.class).
2065      * </ol>
2066      *
2067      * @apiNote There may be more than one method with matching name and
2068      * parameter types in a class because while the Java language forbids a
2069      * class to declare multiple methods with the same signature but different
2070      * return types, the Java virtual machine does not.  This
2071      * increased flexibility in the virtual machine can be used to
2072      * implement various language features.  For example, covariant
2073      * returns can be implemented with {@linkplain
2074      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
2075      * method and the overriding method would have the same
2076      * signature but different return types. This method would return the
2077      * overriding method as it would have a more specific return type.
2078      *
2079      * @param name the name of the method
2080      * @param parameterTypes the list of parameters
2081      * @return the {@code Method} object that matches the specified
2082      *         {@code name} and {@code parameterTypes}
2083      * @throws NoSuchMethodException if a matching method is not found
2084      *         or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
2085      * @throws NullPointerException if {@code name} is {@code null}
2086      * @throws SecurityException
2087      *         If a security manager, <i>s</i>, is present and
2088      *         the caller's class loader is not the same as or an
2089      *         ancestor of the class loader for the current class and
2090      *         invocation of {@link SecurityManager#checkPackageAccess
2091      *         s.checkPackageAccess()} denies access to the package
2092      *         of this class.
2093      *
2094      * @jls 8.2 Class Members
2095      * @jls 8.4 Method Declarations
2096      * @since 1.1
2097      */

2098     @CallerSensitive
2099     public Method getMethod(String name, Class<?>... parameterTypes)
2100         throws NoSuchMethodException, SecurityException {
2101         Objects.requireNonNull(name);
2102         SecurityManager sm = System.getSecurityManager();
2103         if (sm != null) {
2104             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
2105         }
2106         Method method = getMethod0(name, parameterTypes);
2107         if (method == null) {
2108             throw new NoSuchMethodException(methodToString(name, parameterTypes));
2109         }
2110         return getReflectionFactory().copyMethod(method);
2111     }
2112
2113     /**
2114      * Returns a {@code Constructor} object that reflects the specified
2115      * public constructor of the class represented by this {@code Class}
2116      * object. The {@code parameterTypes} parameter is an array of
2117      * {@code Class} objects that identify the constructor's formal
2118      * parameter types, in declared order.
2119      *
2120      * If this {@code Class} object represents an inner class
2121      * declared in a non-static context, the formal parameter types
2122      * include the explicit enclosing instance as the first parameter.
2123      *
2124      * <p> The constructor to reflect is the public constructor of the class
2125      * represented by this {@code Class} object whose formal parameter
2126      * types match those specified by {@code parameterTypes}.
2127      *
2128      * @param parameterTypes the parameter array
2129      * @return the {@code Constructor} object of the public constructor that
2130      *         matches the specified {@code parameterTypes}
2131      * @throws NoSuchMethodException if a matching method is not found.
2132      * @throws SecurityException
2133      *         If a security manager, <i>s</i>, is present and
2134      *         the caller's class loader is not the same as or an
2135      *         ancestor of the class loader for the current class and
2136      *         invocation of {@link SecurityManager#checkPackageAccess
2137      *         s.checkPackageAccess()} denies access to the package
2138      *         of this class.
2139      *
2140      * @since 1.1
2141      */

2142     @CallerSensitive
2143     public Constructor<T> getConstructor(Class<?>... parameterTypes)
2144         throws NoSuchMethodException, SecurityException
2145     {
2146         SecurityManager sm = System.getSecurityManager();
2147         if (sm != null) {
2148             checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);
2149         }
2150         return getReflectionFactory().copyConstructor(
2151             getConstructor0(parameterTypes, Member.PUBLIC));
2152     }
2153
2154
2155     /**
2156      * Returns an array of {@code Class} objects reflecting all the
2157      * classes and interfaces declared as members of the class represented by
2158      * this {@code Class} object. This includes publicprotecteddefault
2159      * (package) access, and private classes and interfaces declared by the
2160      * class, but excludes inherited classes and interfaces.  This method
2161      * returns an array of length 0 if the class declares no classes or
2162      * interfaces as members, or if this {@code Class} object represents a
2163      * primitive type, an array class, or void.
2164      *
2165      * @return the array of {@code Class} objects representing all the
2166      *         declared members of this class
2167      * @throws SecurityException
2168      *         If a security manager, <i>s</i>, is present and any of the
2169      *         following conditions is met:
2170      *
2171      *         <ul>
2172      *
2173      *         <li> the caller's class loader is not the same as the
2174      *         class loader of this class and invocation of
2175      *         {@link SecurityManager#checkPermission
2176      *         s.checkPermission} method with
2177      *         {@code RuntimePermission("accessDeclaredMembers")}
2178      *         denies access to the declared classes within this class
2179      *
2180      *         <li> the caller's class loader is not the same as or an
2181      *         ancestor of the class loader for the current class and
2182      *         invocation of {@link SecurityManager#checkPackageAccess
2183      *         s.checkPackageAccess()} denies access to the package
2184      *         of this class
2185      *
2186      *         </ul>
2187      *
2188      * @since 1.1
2189      */

2190     @CallerSensitive
2191     public Class<?>[] getDeclaredClasses() throws SecurityException {
2192         SecurityManager sm = System.getSecurityManager();
2193         if (sm != null) {
2194             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), false);
2195         }
2196         return getDeclaredClasses0();
2197     }
2198
2199
2200     /**
2201      * Returns an array of {@code Field} objects reflecting all the fields
2202      * declared by the class or interface represented by this
2203      * {@code Class} object. This includes publicprotecteddefault
2204      * (package) access, and private fields, but excludes inherited fields.
2205      *
2206      * <p> If this {@code Class} object represents a class or interface with no
2207      * declared fields, then this method returns an array of length 0.
2208      *
2209      * <p> If this {@code Class} object represents an array type, a primitive
2210      * type, or void, then this method returns an array of length 0.
2211      *
2212      * <p> The elements in the returned array are not sorted and are not in any
2213      * particular order.
2214      *
2215      * @return  the array of {@code Field} objects representing all the
2216      *          declared fields of this class
2217      * @throws  SecurityException
2218      *          If a security manager, <i>s</i>, is present and any of the
2219      *          following conditions is met:
2220      *
2221      *          <ul>
2222      *
2223      *          <li> the caller's class loader is not the same as the
2224      *          class loader of this class and invocation of
2225      *          {@link SecurityManager#checkPermission
2226      *          s.checkPermission} method with
2227      *          {@code RuntimePermission("accessDeclaredMembers")}
2228      *          denies access to the declared fields within this class
2229      *
2230      *          <li> the caller's class loader is not the same as or an
2231      *          ancestor of the class loader for the current class and
2232      *          invocation of {@link SecurityManager#checkPackageAccess
2233      *          s.checkPackageAccess()} denies access to the package
2234      *          of this class
2235      *
2236      *          </ul>
2237      *
2238      * @since 1.1
2239      * @jls 8.2 Class Members
2240      * @jls 8.3 Field Declarations
2241      */

2242     @CallerSensitive
2243     public Field[] getDeclaredFields() throws SecurityException {
2244         SecurityManager sm = System.getSecurityManager();
2245         if (sm != null) {
2246             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2247         }
2248         return copyFields(privateGetDeclaredFields(false));
2249     }
2250
2251
2252     /**
2253      * Returns an array containing {@code Method} objects reflecting all the
2254      * declared methods of the class or interface represented by this {@code
2255      * Class} object, including publicprotecteddefault (package)
2256      * access, and private methods, but excluding inherited methods.
2257      *
2258      * <p> If this {@code Class} object represents a type that has multiple
2259      * declared methods with the same name and parameter types, but different
2260      * return types, then the returned array has a {@code Method} object for
2261      * each such method.
2262      *
2263      * <p> If this {@code Class} object represents a type that has a class
2264      * initialization method {@code <clinit>}, then the returned array does
2265      * <em>not</em> have a corresponding {@code Method} object.
2266      *
2267      * <p> If this {@code Class} object represents a class or interface with no
2268      * declared methods, then the returned array has length 0.
2269      *
2270      * <p> If this {@code Class} object represents an array type, a primitive
2271      * type, or void, then the returned array has length 0.
2272      *
2273      * <p> The elements in the returned array are not sorted and are not in any
2274      * particular order.
2275      *
2276      * @return  the array of {@code Method} objects representing all the
2277      *          declared methods of this class
2278      * @throws  SecurityException
2279      *          If a security manager, <i>s</i>, is present and any of the
2280      *          following conditions is met:
2281      *
2282      *          <ul>
2283      *
2284      *          <li> the caller's class loader is not the same as the
2285      *          class loader of this class and invocation of
2286      *          {@link SecurityManager#checkPermission
2287      *          s.checkPermission} method with
2288      *          {@code RuntimePermission("accessDeclaredMembers")}
2289      *          denies access to the declared methods within this class
2290      *
2291      *          <li> the caller's class loader is not the same as or an
2292      *          ancestor of the class loader for the current class and
2293      *          invocation of {@link SecurityManager#checkPackageAccess
2294      *          s.checkPackageAccess()} denies access to the package
2295      *          of this class
2296      *
2297      *          </ul>
2298      *
2299      * @jls 8.2 Class Members
2300      * @jls 8.4 Method Declarations
2301      * @since 1.1
2302      */

2303     @CallerSensitive
2304     public Method[] getDeclaredMethods() throws SecurityException {
2305         SecurityManager sm = System.getSecurityManager();
2306         if (sm != null) {
2307             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2308         }
2309         return copyMethods(privateGetDeclaredMethods(false));
2310     }
2311
2312
2313     /**
2314      * Returns an array of {@code Constructor} objects reflecting all the
2315      * constructors declared by the class represented by this
2316      * {@code Class} object. These are publicprotecteddefault
2317      * (package) access, and private constructors.  The elements in the array
2318      * returned are not sorted and are not in any particular order.  If the
2319      * class has a default constructor, it is included in the returned array.
2320      * This method returns an array of length 0 if this {@code Class}
2321      * object represents an interface, a primitive type, an array class, or
2322      * void.
2323      *
2324      * <p> See <em>The Java Language Specification</em>, section 8.2.
2325      *
2326      * @return  the array of {@code Constructor} objects representing all the
2327      *          declared constructors of this class
2328      * @throws  SecurityException
2329      *          If a security manager, <i>s</i>, is present and any of the
2330      *          following conditions is met:
2331      *
2332      *          <ul>
2333      *
2334      *          <li> the caller's class loader is not the same as the
2335      *          class loader of this class and invocation of
2336      *          {@link SecurityManager#checkPermission
2337      *          s.checkPermission} method with
2338      *          {@code RuntimePermission("accessDeclaredMembers")}
2339      *          denies access to the declared constructors within this class
2340      *
2341      *          <li> the caller's class loader is not the same as or an
2342      *          ancestor of the class loader for the current class and
2343      *          invocation of {@link SecurityManager#checkPackageAccess
2344      *          s.checkPackageAccess()} denies access to the package
2345      *          of this class
2346      *
2347      *          </ul>
2348      *
2349      * @since 1.1
2350      */

2351     @CallerSensitive
2352     public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
2353         SecurityManager sm = System.getSecurityManager();
2354         if (sm != null) {
2355             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2356         }
2357         return copyConstructors(privateGetDeclaredConstructors(false));
2358     }
2359
2360
2361     /**
2362      * Returns a {@code Field} object that reflects the specified declared
2363      * field of the class or interface represented by this {@code Class}
2364      * object. The {@code name} parameter is a {@code String} that specifies
2365      * the simple name of the desired field.
2366      *
2367      * <p> If this {@code Class} object represents an array type, then this
2368      * method does not find the {@code length} field of the array type.
2369      *
2370      * @param name the name of the field
2371      * @return  the {@code Field} object for the specified field in this
2372      *          class
2373      * @throws  NoSuchFieldException if a field with the specified name is
2374      *          not found.
2375      * @throws  NullPointerException if {@code name} is {@code null}
2376      * @throws  SecurityException
2377      *          If a security manager, <i>s</i>, is present and any of the
2378      *          following conditions is met:
2379      *
2380      *          <ul>
2381      *
2382      *          <li> the caller's class loader is not the same as the
2383      *          class loader of this class and invocation of
2384      *          {@link SecurityManager#checkPermission
2385      *          s.checkPermission} method with
2386      *          {@code RuntimePermission("accessDeclaredMembers")}
2387      *          denies access to the declared field
2388      *
2389      *          <li> the caller's class loader is not the same as or an
2390      *          ancestor of the class loader for the current class and
2391      *          invocation of {@link SecurityManager#checkPackageAccess
2392      *          s.checkPackageAccess()} denies access to the package
2393      *          of this class
2394      *
2395      *          </ul>
2396      *
2397      * @since 1.1
2398      * @jls 8.2 Class Members
2399      * @jls 8.3 Field Declarations
2400      */

2401     @CallerSensitive
2402     public Field getDeclaredField(String name)
2403         throws NoSuchFieldException, SecurityException {
2404         Objects.requireNonNull(name);
2405         SecurityManager sm = System.getSecurityManager();
2406         if (sm != null) {
2407             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2408         }
2409         Field field = searchFields(privateGetDeclaredFields(false), name);
2410         if (field == null) {
2411             throw new NoSuchFieldException(name);
2412         }
2413         return getReflectionFactory().copyField(field);
2414     }
2415
2416
2417     /**
2418      * Returns a {@code Method} object that reflects the specified
2419      * declared method of the class or interface represented by this
2420      * {@code Class} object. The {@code name} parameter is a
2421      * {@code String} that specifies the simple name of the desired
2422      * method, and the {@code parameterTypes} parameter is an array of
2423      * {@code Class} objects that identify the method's formal parameter
2424      * types, in declared order.  If more than one method with the same
2425      * parameter types is declared in a class, and one of these methods has a
2426      * return type that is more specific than any of the others, that method is
2427      * returned; otherwise one of the methods is chosen arbitrarily.  If the
2428      * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
2429      * is raised.
2430      *
2431      * <p> If this {@code Class} object represents an array type, then this
2432      * method does not find the {@code clone()} method.
2433      *
2434      * @param name the name of the method
2435      * @param parameterTypes the parameter array
2436      * @return  the {@code Method} object for the method of this class
2437      *          matching the specified name and parameters
2438      * @throws  NoSuchMethodException if a matching method is not found.
2439      * @throws  NullPointerException if {@code name} is {@code null}
2440      * @throws  SecurityException
2441      *          If a security manager, <i>s</i>, is present and any of the
2442      *          following conditions is met:
2443      *
2444      *          <ul>
2445      *
2446      *          <li> the caller's class loader is not the same as the
2447      *          class loader of this class and invocation of
2448      *          {@link SecurityManager#checkPermission
2449      *          s.checkPermission} method with
2450      *          {@code RuntimePermission("accessDeclaredMembers")}
2451      *          denies access to the declared method
2452      *
2453      *          <li> the caller's class loader is not the same as or an
2454      *          ancestor of the class loader for the current class and
2455      *          invocation of {@link SecurityManager#checkPackageAccess
2456      *          s.checkPackageAccess()} denies access to the package
2457      *          of this class
2458      *
2459      *          </ul>
2460      *
2461      * @jls 8.2 Class Members
2462      * @jls 8.4 Method Declarations
2463      * @since 1.1
2464      */

2465     @CallerSensitive
2466     public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2467         throws NoSuchMethodException, SecurityException {
2468         Objects.requireNonNull(name);
2469         SecurityManager sm = System.getSecurityManager();
2470         if (sm != null) {
2471             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2472         }
2473         Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
2474         if (method == null) {
2475             throw new NoSuchMethodException(methodToString(name, parameterTypes));
2476         }
2477         return getReflectionFactory().copyMethod(method);
2478     }
2479
2480     /**
2481      * Returns the list of {@code Method} objects for the declared public
2482      * methods of this class or interface that have the specified method name
2483      * and parameter types.
2484      *
2485      * @param name the name of the method
2486      * @param parameterTypes the parameter array
2487      * @return the list of {@code Method} objects for the public methods of
2488      *         this class matching the specified name and parameters
2489      */

2490     List<Method> getDeclaredPublicMethods(String name, Class<?>... parameterTypes) {
2491         Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);
2492         ReflectionFactory factory = getReflectionFactory();
2493         List<Method> result = new ArrayList<>();
2494         for (Method method : methods) {
2495             if (method.getName().equals(name)
2496                 && Arrays.equals(
2497                     factory.getExecutableSharedParameterTypes(method),
2498                     parameterTypes)) {
2499                 result.add(factory.copyMethod(method));
2500             }
2501         }
2502         return result;
2503     }
2504
2505     /**
2506      * Returns a {@code Constructor} object that reflects the specified
2507      * constructor of the class or interface represented by this
2508      * {@code Class} object.  The {@code parameterTypes} parameter is
2509      * an array of {@code Class} objects that identify the constructor's
2510      * formal parameter types, in declared order.
2511      *
2512      * If this {@code Class} object represents an inner class
2513      * declared in a non-static context, the formal parameter types
2514      * include the explicit enclosing instance as the first parameter.
2515      *
2516      * @param parameterTypes the parameter array
2517      * @return  The {@code Constructor} object for the constructor with the
2518      *          specified parameter list
2519      * @throws  NoSuchMethodException if a matching method is not found.
2520      * @throws  SecurityException
2521      *          If a security manager, <i>s</i>, is present and any of the
2522      *          following conditions is met:
2523      *
2524      *          <ul>
2525      *
2526      *          <li> the caller's class loader is not the same as the
2527      *          class loader of this class and invocation of
2528      *          {@link SecurityManager#checkPermission
2529      *          s.checkPermission} method with
2530      *          {@code RuntimePermission("accessDeclaredMembers")}
2531      *          denies access to the declared constructor
2532      *
2533      *          <li> the caller's class loader is not the same as or an
2534      *          ancestor of the class loader for the current class and
2535      *          invocation of {@link SecurityManager#checkPackageAccess
2536      *          s.checkPackageAccess()} denies access to the package
2537      *          of this class
2538      *
2539      *          </ul>
2540      *
2541      * @since 1.1
2542      */

2543     @CallerSensitive
2544     public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
2545         throws NoSuchMethodException, SecurityException
2546     {
2547         SecurityManager sm = System.getSecurityManager();
2548         if (sm != null) {
2549             checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);
2550         }
2551
2552         return getReflectionFactory().copyConstructor(
2553             getConstructor0(parameterTypes, Member.DECLARED));
2554     }
2555
2556     /**
2557      * Finds a resource with a given name.
2558      *
2559      * <p> If this class is in a named {@link Module Module} then this method
2560      * will attempt to find the resource in the module. This is done by
2561      * delegating to the module's class loader {@link
2562      * ClassLoader#findResource(String,String) findResource(String,String)}
2563      * method, invoking it with the module name and the absolute name of the
2564      * resource. Resources in named modules are subject to the rules for
2565      * encapsulation specified in the {@code Module} {@link
2566      * Module#getResourceAsStream getResourceAsStream} method and so this
2567      * method returns {@code null} when the resource is a
2568      * non-"{@code .class}" resource in a package that is not open to the
2569      * caller's module.
2570      *
2571      * <p> Otherwise, if this class is not in a named module then the rules for
2572      * searching resources associated with a given class are implemented by the
2573      * defining {@linkplain ClassLoader class loader} of the class.  This method
2574      * delegates to this object's class loader.  If this object was loaded by
2575      * the bootstrap class loader, the method delegates to {@link
2576      * ClassLoader#getSystemResourceAsStream}.
2577      *
2578      * <p> Before delegation, an absolute resource name is constructed from the
2579      * given resource name using this algorithm:
2580      *
2581      * <ul>
2582      *
2583      * <li> If the {@code name} begins with a {@code '/'}
2584      * (<code>'&#92;u002f'</code>), then the absolute name of the resource is the
2585      * portion of the {@code name} following the {@code '/'}.
2586      *
2587      * <li> Otherwise, the absolute name is of the following form:
2588      *
2589      * <blockquote>
2590      *   {@code modified_package_name/name}
2591      * </blockquote>
2592      *
2593      * <p> Where the {@code modified_package_name} is the package name of this
2594      * object with {@code '/'} substituted for {@code '.'}
2595      * (<code>'&#92;u002e'</code>).
2596      *
2597      * </ul>
2598      *
2599      * @param  name name of the desired resource
2600      * @return  A {@link java.io.InputStream} object; {@code nullif no
2601      *          resource with this name is found, the resource is in a package
2602      *          that is not {@linkplain Module#isOpen(String, Module) open} to at
2603      *          least the caller module, or access to the resource is denied
2604      *          by the security manager.
2605      * @throws  NullPointerException If {@code name} is {@code null}
2606      *
2607      * @see Module#getResourceAsStream(String)
2608      * @since  1.1
2609      * @revised 9
2610      * @spec JPMS
2611      */

2612     @CallerSensitive
2613     public InputStream getResourceAsStream(String name) {
2614         name = resolveName(name);
2615
2616         Module thisModule = getModule();
2617         if (thisModule.isNamed()) {
2618             // check if resource can be located by caller
2619             if (Resources.canEncapsulate(name)
2620                 && !isOpenToCaller(name, Reflection.getCallerClass())) {
2621                 return null;
2622             }
2623
2624             // resource not encapsulated or in package open to caller
2625             String mn = thisModule.getName();
2626             ClassLoader cl = getClassLoader0();
2627             try {
2628
2629                 // special-case built-in class loaders to avoid the
2630                 // need for a URL connection
2631                 if (cl == null) {
2632                     return BootLoader.findResourceAsStream(mn, name);
2633                 } else if (cl instanceof BuiltinClassLoader) {
2634                     return ((BuiltinClassLoader) cl).findResourceAsStream(mn, name);
2635                 } else {
2636                     URL url = cl.findResource(mn, name);
2637                     return (url != null) ? url.openStream() : null;
2638                 }
2639
2640             } catch (IOException | SecurityException e) {
2641                 return null;
2642             }
2643         }
2644
2645         // unnamed module
2646         ClassLoader cl = getClassLoader0();
2647         if (cl == null) {
2648             return ClassLoader.getSystemResourceAsStream(name);
2649         } else {
2650             return cl.getResourceAsStream(name);
2651         }
2652     }
2653
2654     /**
2655      * Finds a resource with a given name.
2656      *
2657      * <p> If this class is in a named {@link Module Module} then this method
2658      * will attempt to find the resource in the module. This is done by
2659      * delegating to the module's class loader {@link
2660      * ClassLoader#findResource(String,String) findResource(String,String)}
2661      * method, invoking it with the module name and the absolute name of the
2662      * resource. Resources in named modules are subject to the rules for
2663      * encapsulation specified in the {@code Module} {@link
2664      * Module#getResourceAsStream getResourceAsStream} method and so this
2665      * method returns {@code null} when the resource is a
2666      * non-"{@code .class}" resource in a package that is not open to the
2667      * caller's module.
2668      *
2669      * <p> Otherwise, if this class is not in a named module then the rules for
2670      * searching resources associated with a given class are implemented by the
2671      * defining {@linkplain ClassLoader class loader} of the class.  This method
2672      * delegates to this object's class loader. If this object was loaded by
2673      * the bootstrap class loader, the method delegates to {@link
2674      * ClassLoader#getSystemResource}.
2675      *
2676      * <p> Before delegation, an absolute resource name is constructed from the
2677      * given resource name using this algorithm:
2678      *
2679      * <ul>
2680      *
2681      * <li> If the {@code name} begins with a {@code '/'}
2682      * (<code>'&#92;u002f'</code>), then the absolute name of the resource is the
2683      * portion of the {@code name} following the {@code '/'}.
2684      *
2685      * <li> Otherwise, the absolute name is of the following form:
2686      *
2687      * <blockquote>
2688      *   {@code modified_package_name/name}
2689      * </blockquote>
2690      *
2691      * <p> Where the {@code modified_package_name} is the package name of this
2692      * object with {@code '/'} substituted for {@code '.'}
2693      * (<code>'&#92;u002e'</code>).
2694      *
2695      * </ul>
2696      *
2697      * @param  name name of the desired resource
2698      * @return A {@link java.net.URL} object; {@code nullif no resource with
2699      *         this name is found, the resource cannot be located by a URL, the
2700      *         resource is in a package that is not
2701      *         {@linkplain Module#isOpen(String, Module) open} to at least the caller
2702      *         module, or access to the resource is denied by the security
2703      *         manager.
2704      * @throws NullPointerException If {@code name} is {@code null}
2705      * @since  1.1
2706      * @revised 9
2707      * @spec JPMS
2708      */

2709     @CallerSensitive
2710     public URL getResource(String name) {
2711         name = resolveName(name);
2712
2713         Module thisModule = getModule();
2714         if (thisModule.isNamed()) {
2715             // check if resource can be located by caller
2716             if (Resources.canEncapsulate(name)
2717                 && !isOpenToCaller(name, Reflection.getCallerClass())) {
2718                 return null;
2719             }
2720
2721             // resource not encapsulated or in package open to caller
2722             String mn = thisModule.getName();
2723             ClassLoader cl = getClassLoader0();
2724             try {
2725                 if (cl == null) {
2726                     return BootLoader.findResource(mn, name);
2727                 } else {
2728                     return cl.findResource(mn, name);
2729                 }
2730             } catch (IOException ioe) {
2731                 return null;
2732             }
2733         }
2734
2735         // unnamed module
2736         ClassLoader cl = getClassLoader0();
2737         if (cl == null) {
2738             return ClassLoader.getSystemResource(name);
2739         } else {
2740             return cl.getResource(name);
2741         }
2742     }
2743
2744     /**
2745      * Returns true if a resource with the given name can be located by the
2746      * given caller. All resources in a module can be located by code in
2747      * the module. For other callers, then the package needs to be open to
2748      * the caller.
2749      */

2750     private boolean isOpenToCaller(String name, Class<?> caller) {
2751         // assert getModule().isNamed();
2752         Module thisModule = getModule();
2753         Module callerModule = (caller != null) ? caller.getModule() : null;
2754         if (callerModule != thisModule) {
2755             String pn = Resources.toPackageName(name);
2756             if (thisModule.getDescriptor().packages().contains(pn)) {
2757                 if (callerModule == null && !thisModule.isOpen(pn)) {
2758                     // no caller, package not open
2759                     return false;
2760                 }
2761                 if (!thisModule.isOpen(pn, callerModule)) {
2762                     // package not open to caller
2763                     return false;
2764                 }
2765             }
2766         }
2767         return true;
2768     }
2769
2770
2771     /** protection domain returned when the internal domain is null */
2772     private static java.security.ProtectionDomain allPermDomain;
2773
2774     /**
2775      * Returns the {@code ProtectionDomain} of this class.  If there is a
2776      * security manager installed, this method first calls the security
2777      * manager's {@code checkPermission} method with a
2778      * {@code RuntimePermission("getProtectionDomain")} permission to
2779      * ensure it's ok to get the
2780      * {@code ProtectionDomain}.
2781      *
2782      * @return the ProtectionDomain of this class
2783      *
2784      * @throws SecurityException
2785      *        if a security manager exists and its
2786      *        {@code checkPermission} method doesn't allow
2787      *        getting the ProtectionDomain.
2788      *
2789      * @see java.security.ProtectionDomain
2790      * @see SecurityManager#checkPermission
2791      * @see java.lang.RuntimePermission
2792      * @since 1.2
2793      */

2794     public java.security.ProtectionDomain getProtectionDomain() {
2795         SecurityManager sm = System.getSecurityManager();
2796         if (sm != null) {
2797             sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
2798         }
2799         java.security.ProtectionDomain pd = getProtectionDomain0();
2800         if (pd == null) {
2801             if (allPermDomain == null) {
2802                 java.security.Permissions perms =
2803                     new java.security.Permissions();
2804                 perms.add(SecurityConstants.ALL_PERMISSION);
2805                 allPermDomain =
2806                     new java.security.ProtectionDomain(null, perms);
2807             }
2808             pd = allPermDomain;
2809         }
2810         return pd;
2811     }
2812
2813
2814     /**
2815      * Returns the ProtectionDomain of this class.
2816      */

2817     private native java.security.ProtectionDomain getProtectionDomain0();
2818
2819     /*
2820      * Return the Virtual Machine's Class object for the named
2821      * primitive type.
2822      */

2823     static native Class<?> getPrimitiveClass(String name);
2824
2825     /*
2826      * Check if client is allowed to access members.  If access is denied,
2827      * throw a SecurityException.
2828      *
2829      * This method also enforces package access.
2830      *
2831      * <p> Default policy: allow all clients access with normal Java access
2832      * control.
2833      *
2834      * <p> NOTE: should only be called if a SecurityManager is installed
2835      */

2836     private void checkMemberAccess(SecurityManager sm, int which,
2837                                    Class<?> caller, boolean checkProxyInterfaces) {
2838         /* Default policy allows access to all {@link Member#PUBLIC} members,
2839          * as well as access to classes that have the same class loader as the caller.
2840          * In all other cases, it requires RuntimePermission("accessDeclaredMembers")
2841          * permission.
2842          */

2843         final ClassLoader ccl = ClassLoader.getClassLoader(caller);
2844         if (which != Member.PUBLIC) {
2845             final ClassLoader cl = getClassLoader0();
2846             if (ccl != cl) {
2847                 sm.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
2848             }
2849         }
2850         this.checkPackageAccess(sm, ccl, checkProxyInterfaces);
2851     }
2852
2853     /*
2854      * Checks if a client loaded in ClassLoader ccl is allowed to access this
2855      * class under the current package access policy. If access is denied,
2856      * throw a SecurityException.
2857      *
2858      * NOTE: this method should only be called if a SecurityManager is active
2859      */

2860     private void checkPackageAccess(SecurityManager sm, final ClassLoader ccl,
2861                                     boolean checkProxyInterfaces) {
2862         final ClassLoader cl = getClassLoader0();
2863
2864         if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {
2865             String pkg = this.getPackageName();
2866             if (pkg != null && !pkg.isEmpty()) {
2867                 // skip the package access check on a proxy class in default proxy package
2868                 if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {
2869                     sm.checkPackageAccess(pkg);
2870                 }
2871             }
2872         }
2873         // check package access on the proxy interfaces
2874         if (checkProxyInterfaces && Proxy.isProxyClass(this)) {
2875             ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());
2876         }
2877     }
2878
2879     /**
2880      * Add a package name prefix if the name is not absolute Remove leading "/"
2881      * if name is absolute
2882      */

2883     private String resolveName(String name) {
2884         if (!name.startsWith("/")) {
2885             Class<?> c = this;
2886             while (c.isArray()) {
2887                 c = c.getComponentType();
2888             }
2889             String baseName = c.getPackageName();
2890             if (baseName != null && !baseName.isEmpty()) {
2891                 name = baseName.replace('.', '/') + "/" + name;
2892             }
2893         } else {
2894             name = name.substring(1);
2895         }
2896         return name;
2897     }
2898
2899     /**
2900      * Atomic operations support.
2901      */

2902     private static class Atomic {
2903         // initialize Unsafe machinery here, since we need to call Class.class instance method
2904         // and have to avoid calling it in the static initializer of the Class class...
2905         private static final Unsafe unsafe = Unsafe.getUnsafe();
2906         // offset of Class.reflectionData instance field
2907         private static final long reflectionDataOffset
2908                 = unsafe.objectFieldOffset(Class.class"reflectionData");
2909         // offset of Class.annotationType instance field
2910         private static final long annotationTypeOffset
2911                 = unsafe.objectFieldOffset(Class.class"annotationType");
2912         // offset of Class.annotationData instance field
2913         private static final long annotationDataOffset
2914                 = unsafe.objectFieldOffset(Class.class"annotationData");
2915
2916         static <T> boolean casReflectionData(Class<?> clazz,
2917                                              SoftReference<ReflectionData<T>> oldData,
2918                                              SoftReference<ReflectionData<T>> newData) {
2919             return unsafe.compareAndSetObject(clazz, reflectionDataOffset, oldData, newData);
2920         }
2921
2922         static <T> boolean casAnnotationType(Class<?> clazz,
2923                                              AnnotationType oldType,
2924                                              AnnotationType newType) {
2925             return unsafe.compareAndSetObject(clazz, annotationTypeOffset, oldType, newType);
2926         }
2927
2928         static <T> boolean casAnnotationData(Class<?> clazz,
2929                                              AnnotationData oldData,
2930                                              AnnotationData newData) {
2931             return unsafe.compareAndSetObject(clazz, annotationDataOffset, oldData, newData);
2932         }
2933     }
2934
2935     /**
2936      * Reflection support.
2937      */

2938
2939     // Reflection data caches various derived names and reflective members. Cached
2940     // values may be invalidated when JVM TI RedefineClasses() is called
2941     private static class ReflectionData<T> {
2942         volatile Field[] declaredFields;
2943         volatile Field[] publicFields;
2944         volatile Method[] declaredMethods;
2945         volatile Method[] publicMethods;
2946         volatile Constructor<T>[] declaredConstructors;
2947         volatile Constructor<T>[] publicConstructors;
2948         // Intermediate results for getFields and getMethods
2949         volatile Field[] declaredPublicFields;
2950         volatile Method[] declaredPublicMethods;
2951         volatile Class<?>[] interfaces;
2952
2953         // Cached names
2954         String simpleName;
2955         String canonicalName;
2956         static final String NULL_SENTINEL = new String();
2957
2958         // Value of classRedefinedCount when we created this ReflectionData instance
2959         final int redefinedCount;
2960
2961         ReflectionData(int redefinedCount) {
2962             this.redefinedCount = redefinedCount;
2963         }
2964     }
2965
2966     private transient volatile SoftReference<ReflectionData<T>> reflectionData;
2967
2968     // Incremented by the VM on each call to JVM TI RedefineClasses()
2969     // that redefines this class or a superclass.
2970     private transient volatile int classRedefinedCount;
2971
2972     // Lazily create and cache ReflectionData
2973     private ReflectionData<T> reflectionData() {
2974         SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
2975         int classRedefinedCount = this.classRedefinedCount;
2976         ReflectionData<T> rd;
2977         if (reflectionData != null &&
2978             (rd = reflectionData.get()) != null &&
2979             rd.redefinedCount == classRedefinedCount) {
2980             return rd;
2981         }
2982         // else no SoftReference or cleared SoftReference or stale ReflectionData
2983         // -> create and replace new instance
2984         return newReflectionData(reflectionData, classRedefinedCount);
2985     }
2986
2987     private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
2988                                                 int classRedefinedCount) {
2989         while (true) {
2990             ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
2991             // try to CAS it...
2992             if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
2993                 return rd;
2994             }
2995             // else retry
2996             oldReflectionData = this.reflectionData;
2997             classRedefinedCount = this.classRedefinedCount;
2998             if (oldReflectionData != null &&
2999                 (rd = oldReflectionData.get()) != null &&
3000                 rd.redefinedCount == classRedefinedCount) {
3001                 return rd;
3002             }
3003         }
3004     }
3005
3006     // Generic signature handling
3007     private native String getGenericSignature0();
3008
3009     // Generic info repository; lazily initialized
3010     private transient volatile ClassRepository genericInfo;
3011
3012     // accessor for factory
3013     private GenericsFactory getFactory() {
3014         // create scope and factory
3015         return CoreReflectionFactory.make(this, ClassScope.make(this));
3016     }
3017
3018     // accessor for generic info repository;
3019     // generic info is lazily initialized
3020     private ClassRepository getGenericInfo() {
3021         ClassRepository genericInfo = this.genericInfo;
3022         if (genericInfo == null) {
3023             String signature = getGenericSignature0();
3024             if (signature == null) {
3025                 genericInfo = ClassRepository.NONE;
3026             } else {
3027                 genericInfo = ClassRepository.make(signature, getFactory());
3028             }
3029             this.genericInfo = genericInfo;
3030         }
3031         return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
3032     }
3033
3034     // Annotations handling
3035     native byte[] getRawAnnotations();
3036     // Since 1.8
3037     native byte[] getRawTypeAnnotations();
3038     static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
3039         return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
3040     }
3041
3042     native ConstantPool getConstantPool();
3043
3044     //
3045     //
3046     // java.lang.reflect.Field handling
3047     //
3048     //
3049
3050     // Returns an array of "root" fields. These Field objects must NOT
3051     // be propagated to the outside world, but must instead be copied
3052     // via ReflectionFactory.copyField.
3053     private Field[] privateGetDeclaredFields(boolean publicOnly) {
3054         Field[] res;
3055         ReflectionData<T> rd = reflectionData();
3056         if (rd != null) {
3057             res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
3058             if (res != nullreturn res;
3059         }
3060         // No cached value available; request value from VM
3061         res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
3062         if (rd != null) {
3063             if (publicOnly) {
3064                 rd.declaredPublicFields = res;
3065             } else {
3066                 rd.declaredFields = res;
3067             }
3068         }
3069         return res;
3070     }
3071
3072     // Returns an array of "root" fields. These Field objects must NOT
3073     // be propagated to the outside world, but must instead be copied
3074     // via ReflectionFactory.copyField.
3075     private Field[] privateGetPublicFields() {
3076         Field[] res;
3077         ReflectionData<T> rd = reflectionData();
3078         if (rd != null) {
3079             res = rd.publicFields;
3080             if (res != nullreturn res;
3081         }
3082
3083         // Use a linked hash set to ensure order is preserved and
3084         // fields from common super interfaces are not duplicated
3085         LinkedHashSet<Field> fields = new LinkedHashSet<>();
3086
3087         // Local fields
3088         addAll(fields, privateGetDeclaredFields(true));
3089
3090         // Direct superinterfaces, recursively
3091         for (Class<?> si : getInterfaces()) {
3092             addAll(fields, si.privateGetPublicFields());
3093         }
3094
3095         // Direct superclass, recursively
3096         Class<?> sc = getSuperclass();
3097         if (sc != null) {
3098             addAll(fields, sc.privateGetPublicFields());
3099         }
3100
3101         res = fields.toArray(new Field[0]);
3102         if (rd != null) {
3103             rd.publicFields = res;
3104         }
3105         return res;
3106     }
3107
3108     private static void addAll(Collection<Field> c, Field[] o) {
3109         for (Field f : o) {
3110             c.add(f);
3111         }
3112     }
3113
3114
3115     //
3116     //
3117     // java.lang.reflect.Constructor handling
3118     //
3119     //
3120
3121     // Returns an array of "root" constructors. These Constructor
3122     // objects must NOT be propagated to the outside world, but must
3123     // instead be copied via ReflectionFactory.copyConstructor.
3124     private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
3125         Constructor<T>[] res;
3126         ReflectionData<T> rd = reflectionData();
3127         if (rd != null) {
3128             res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
3129             if (res != nullreturn res;
3130         }
3131         // No cached value available; request value from VM
3132         if (isInterface()) {
3133             @SuppressWarnings("unchecked")
3134             Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
3135             res = temporaryRes;
3136         } else {
3137             res = getDeclaredConstructors0(publicOnly);
3138         }
3139         if (rd != null) {
3140             if (publicOnly) {
3141                 rd.publicConstructors = res;
3142             } else {
3143                 rd.declaredConstructors = res;
3144             }
3145         }
3146         return res;
3147     }
3148
3149     //
3150     //
3151     // java.lang.reflect.Method handling
3152     //
3153     //
3154
3155     // Returns an array of "root" methods. These Method objects must NOT
3156     // be propagated to the outside world, but must instead be copied
3157     // via ReflectionFactory.copyMethod.
3158     private Method[] privateGetDeclaredMethods(boolean publicOnly) {
3159         Method[] res;
3160         ReflectionData<T> rd = reflectionData();
3161         if (rd != null) {
3162             res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
3163             if (res != nullreturn res;
3164         }
3165         // No cached value available; request value from VM
3166         res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
3167         if (rd != null) {
3168             if (publicOnly) {
3169                 rd.declaredPublicMethods = res;
3170             } else {
3171                 rd.declaredMethods = res;
3172             }
3173         }
3174         return res;
3175     }
3176
3177     // Returns an array of "root" methods. These Method objects must NOT
3178     // be propagated to the outside world, but must instead be copied
3179     // via ReflectionFactory.copyMethod.
3180     private Method[] privateGetPublicMethods() {
3181         Method[] res;
3182         ReflectionData<T> rd = reflectionData();
3183         if (rd != null) {
3184             res = rd.publicMethods;
3185             if (res != nullreturn res;
3186         }
3187
3188         // No cached value available; compute value recursively.
3189         // Start by fetching public declared methods...
3190         PublicMethods pms = new PublicMethods();
3191         for (Method m : privateGetDeclaredMethods(/* publicOnly */ true)) {
3192             pms.merge(m);
3193         }
3194         // ...then recur over superclass methods...
3195         Class<?> sc = getSuperclass();
3196         if (sc != null) {
3197             for (Method m : sc.privateGetPublicMethods()) {
3198                 pms.merge(m);
3199             }
3200         }
3201         // ...and finally over direct superinterfaces.
3202         for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
3203             for (Method m : intf.privateGetPublicMethods()) {
3204                 // static interface methods are not inherited
3205                 if (!Modifier.isStatic(m.getModifiers())) {
3206                     pms.merge(m);
3207                 }
3208             }
3209         }
3210
3211         res = pms.toArray();
3212         if (rd != null) {
3213             rd.publicMethods = res;
3214         }
3215         return res;
3216     }
3217
3218
3219     //
3220     // Helpers for fetchers of one field, method, or constructor
3221     //
3222
3223     // This method does not copy the returned Field object!
3224     private static Field searchFields(Field[] fields, String name) {
3225         for (Field field : fields) {
3226             if (field.getName().equals(name)) {
3227                 return field;
3228             }
3229         }
3230         return null;
3231     }
3232
3233     // Returns a "root" Field object. This Field object must NOT
3234     // be propagated to the outside world, but must instead be copied
3235     // via ReflectionFactory.copyField.
3236     private Field getField0(String name) {
3237         // Note: the intent is that the search algorithm this routine
3238         // uses be equivalent to the ordering imposed by
3239         // privateGetPublicFields(). It fetches only the declared
3240         // public fields for each class, however, to reduce the number
3241         // of Field objects which have to be created for the common
3242         // case where the field being requested is declared in the
3243         // class which is being queried.
3244         Field res;
3245         // Search declared public fields
3246         if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
3247             return res;
3248         }
3249         // Direct superinterfaces, recursively
3250         Class<?>[] interfaces = getInterfaces(/* cloneArray */ false);
3251         for (Class<?> c : interfaces) {
3252             if ((res = c.getField0(name)) != null) {
3253                 return res;
3254             }
3255         }
3256         // Direct superclass, recursively
3257         if (!isInterface()) {
3258             Class<?> c = getSuperclass();
3259             if (c != null) {
3260                 if ((res = c.getField0(name)) != null) {
3261                     return res;
3262                 }
3263             }
3264         }
3265         return null;
3266     }
3267
3268     // This method does not copy the returned Method object!
3269     private static Method searchMethods(Method[] methods,
3270                                         String name,
3271                                         Class<?>[] parameterTypes)
3272     {
3273         ReflectionFactory fact = getReflectionFactory();
3274         Method res = null;
3275         for (Method m : methods) {
3276             if (m.getName().equals(name)
3277                 && arrayContentsEq(parameterTypes,
3278                                    fact.getExecutableSharedParameterTypes(m))
3279                 && (res == null
3280                     || (res.getReturnType() != m.getReturnType()
3281                         && res.getReturnType().isAssignableFrom(m.getReturnType()))))
3282                 res = m;
3283         }
3284         return res;
3285     }
3286
3287     private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
3288
3289     // Returns a "root" Method object. This Method object must NOT
3290     // be propagated to the outside world, but must instead be copied
3291     // via ReflectionFactory.copyMethod.
3292     private Method getMethod0(String name, Class<?>[] parameterTypes) {
3293         PublicMethods.MethodList res = getMethodsRecursive(
3294             name,
3295             parameterTypes == null ? EMPTY_CLASS_ARRAY : parameterTypes,
3296             /* includeStatic */ true);
3297         return res == null ? null : res.getMostSpecific();
3298     }
3299
3300     // Returns a list of "root" Method objects. These Method objects must NOT
3301     // be propagated to the outside world, but must instead be copied
3302     // via ReflectionFactory.copyMethod.
3303     private PublicMethods.MethodList getMethodsRecursive(String name,
3304                                                          Class<?>[] parameterTypes,
3305                                                          boolean includeStatic) {
3306         // 1st check declared public methods
3307         Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);
3308         PublicMethods.MethodList res = PublicMethods.MethodList
3309             .filter(methods, name, parameterTypes, includeStatic);
3310         // if there is at least one match among declared methods, we need not
3311         // search any further as such match surely overrides matching methods
3312         // declared in superclass(es) or interface(s).
3313         if (res != null) {
3314             return res;
3315         }
3316
3317         // if there was no match among declared methods,
3318         // we must consult the superclass (if any) recursively...
3319         Class<?> sc = getSuperclass();
3320         if (sc != null) {
3321             res = sc.getMethodsRecursive(name, parameterTypes, includeStatic);
3322         }
3323
3324         // ...and coalesce the superclass methods with methods obtained
3325         // from directly implemented interfaces excluding static methods...
3326         for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
3327             res = PublicMethods.MethodList.merge(
3328                 res, intf.getMethodsRecursive(name, parameterTypes,
3329                                               /* includeStatic */ false));
3330         }
3331
3332         return res;
3333     }
3334
3335     // Returns a "root" Constructor object. This Constructor object must NOT
3336     // be propagated to the outside world, but must instead be copied
3337     // via ReflectionFactory.copyConstructor.
3338     private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3339                                         int which) throws NoSuchMethodException
3340     {
3341         ReflectionFactory fact = getReflectionFactory();
3342         Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3343         for (Constructor<T> constructor : constructors) {
3344             if (arrayContentsEq(parameterTypes,
3345                                 fact.getExecutableSharedParameterTypes(constructor))) {
3346                 return constructor;
3347             }
3348         }
3349         throw new NoSuchMethodException(methodToString("<init>", parameterTypes));
3350     }
3351
3352     //
3353     // Other helpers and base implementation
3354     //
3355
3356     private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3357         if (a1 == null) {
3358             return a2 == null || a2.length == 0;
3359         }
3360
3361         if (a2 == null) {
3362             return a1.length == 0;
3363         }
3364
3365         if (a1.length != a2.length) {
3366             return false;
3367         }
3368
3369         for (int i = 0; i < a1.length; i++) {
3370             if (a1[i] != a2[i]) {
3371                 return false;
3372             }
3373         }
3374
3375         return true;
3376     }
3377
3378     private static Field[] copyFields(Field[] arg) {
3379         Field[] out = new Field[arg.length];
3380         ReflectionFactory fact = getReflectionFactory();
3381         for (int i = 0; i < arg.length; i++) {
3382             out[i] = fact.copyField(arg[i]);
3383         }
3384         return out;
3385     }
3386
3387     private static Method[] copyMethods(Method[] arg) {
3388         Method[] out = new Method[arg.length];
3389         ReflectionFactory fact = getReflectionFactory();
3390         for (int i = 0; i < arg.length; i++) {
3391             out[i] = fact.copyMethod(arg[i]);
3392         }
3393         return out;
3394     }
3395
3396     private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
3397         Constructor<U>[] out = arg.clone();
3398         ReflectionFactory fact = getReflectionFactory();
3399         for (int i = 0; i < out.length; i++) {
3400             out[i] = fact.copyConstructor(out[i]);
3401         }
3402         return out;
3403     }
3404
3405     private native Field[]       getDeclaredFields0(boolean publicOnly);
3406     private native Method[]      getDeclaredMethods0(boolean publicOnly);
3407     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3408     private native Class<?>[]   getDeclaredClasses0();
3409
3410     /**
3411      * Helper method to get the method name from arguments.
3412      */

3413     private String methodToString(String name, Class<?>[] argTypes) {
3414         StringJoiner sj = new StringJoiner(", ", getName() + "." + name + "("")");
3415         if (argTypes != null) {
3416             for (int i = 0; i < argTypes.length; i++) {
3417                 Class<?> c = argTypes[i];
3418                 sj.add((c == null) ? "null" : c.getName());
3419             }
3420         }
3421         return sj.toString();
3422     }
3423
3424     /** use serialVersionUID from JDK 1.1 for interoperability */
3425     private static final long serialVersionUID = 3206093459760846163L;
3426
3427
3428     /**
3429      * Class Class is special cased within the Serialization Stream Protocol.
3430      *
3431      * A Class instance is written initially into an ObjectOutputStream in the
3432      * following format:
3433      * <pre>
3434      *      {@code TC_CLASS} ClassDescriptor
3435      *      A ClassDescriptor is a special cased serialization of
3436      *      a {@code java.io.ObjectStreamClass} instance.
3437      * </pre>
3438      * A new handle is generated for the initial time the class descriptor
3439      * is written into the stream. Future references to the class descriptor
3440      * are written as references to the initial class descriptor instance.
3441      *
3442      * @see java.io.ObjectStreamClass
3443      */

3444     private static final ObjectStreamField[] serialPersistentFields =
3445         new ObjectStreamField[0];
3446
3447
3448     /**
3449      * Returns the assertion status that would be assigned to this
3450      * class if it were to be initialized at the time this method is invoked.
3451      * If this class has had its assertion status set, the most recent
3452      * setting will be returned; otherwise, if any package default assertion
3453      * status pertains to this class, the most recent setting for the most
3454      * specific pertinent package default assertion status is returned;
3455      * otherwise, if this class is not a system class (i.e., it has a
3456      * class loader) its class loader's default assertion status is returned;
3457      * otherwise, the system class default assertion status is returned.
3458      * <p>
3459      * Few programmers will have any need for this method; it is provided
3460      * for the benefit of the JRE itself.  (It allows a class to determine at
3461      * the time that it is initialized whether assertions should be enabled.)
3462      * Note that this method is not guaranteed to return the actual
3463      * assertion status that was (or will be) associated with the specified
3464      * class when it was (or will be) initialized.
3465      *
3466      * @return the desired assertion status of the specified class.
3467      * @see    java.lang.ClassLoader#setClassAssertionStatus
3468      * @see    java.lang.ClassLoader#setPackageAssertionStatus
3469      * @see    java.lang.ClassLoader#setDefaultAssertionStatus
3470      * @since  1.4
3471      */

3472     public boolean desiredAssertionStatus() {
3473         ClassLoader loader = getClassLoader0();
3474         // If the loader is null this is a system class, so ask the VM
3475         if (loader == null)
3476             return desiredAssertionStatus0(this);
3477
3478         // If the classloader has been initialized with the assertion
3479         // directives, ask it. Otherwise, ask the VM.
3480         synchronized(loader.assertionLock) {
3481             if (loader.classAssertionStatus != null) {
3482                 return loader.desiredAssertionStatus(getName());
3483             }
3484         }
3485         return desiredAssertionStatus0(this);
3486     }
3487
3488     // Retrieves the desired assertion status of this class from the VM
3489     private static native boolean desiredAssertionStatus0(Class<?> clazz);
3490
3491     /**
3492      * Returns true if and only if this class was declared as an enum in the
3493      * source code.
3494      *
3495      * @return true if and only if this class was declared as an enum in the
3496      *     source code
3497      * @since 1.5
3498      */

3499     public boolean isEnum() {
3500         // An enum must both directly extend java.lang.Enum and have
3501         // the ENUM bit set; classes for specialized enum constants
3502         // don't do the former.
3503         return (this.getModifiers() & ENUM) != 0 &&
3504         this.getSuperclass() == java.lang.Enum.class;
3505     }
3506
3507     // Fetches the factory for reflective objects
3508     private static ReflectionFactory getReflectionFactory() {
3509         if (reflectionFactory == null) {
3510             reflectionFactory =
3511                 java.security.AccessController.doPrivileged
3512                     (new ReflectionFactory.GetReflectionFactoryAction());
3513         }
3514         return reflectionFactory;
3515     }
3516     private static ReflectionFactory reflectionFactory;
3517
3518     /**
3519      * Returns the elements of this enum class or null if this
3520      * Class object does not represent an enum type.
3521      *
3522      * @return an array containing the values comprising the enum class
3523      *     represented by this Class object in the order they're
3524      *     declared, or null if this Class object does not
3525      *     represent an enum type
3526      * @since 1.5
3527      */

3528     public T[] getEnumConstants() {
3529         T[] values = getEnumConstantsShared();
3530         return (values != null) ? values.clone() : null;
3531     }
3532
3533     /**
3534      * Returns the elements of this enum class or null if this
3535      * Class object does not represent an enum type;
3536      * identical to getEnumConstants except that the result is
3537      * uncloned, cached, and shared by all callers.
3538      */

3539     T[] getEnumConstantsShared() {
3540         T[] constants = enumConstants;
3541         if (constants == null) {
3542             if (!isEnum()) return null;
3543             try {
3544                 final Method values = getMethod("values");
3545                 java.security.AccessController.doPrivileged(
3546                     new java.security.PrivilegedAction<>() {
3547                         public Void run() {
3548                                 values.setAccessible(true);
3549                                 return null;
3550                             }
3551                         });
3552                 @SuppressWarnings("unchecked")
3553                 T[] temporaryConstants = (T[])values.invoke(null);
3554                 enumConstants = constants = temporaryConstants;
3555             }
3556             // These can happen when users concoct enum-like classes
3557             // that don't comply with the enum spec.
3558             catch (InvocationTargetException | NoSuchMethodException |
3559                    IllegalAccessException ex) { return null; }
3560         }
3561         return constants;
3562     }
3563     private transient volatile T[] enumConstants;
3564
3565     /**
3566      * Returns a map from simple name to enum constant.  This package-private
3567      * method is used internally by Enum to implement
3568      * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}
3569      * efficiently.  Note that the map is returned by this method is
3570      * created lazily on first use.  Typically it won't ever get created.
3571      */

3572     Map<String, T> enumConstantDirectory() {
3573         Map<String, T> directory = enumConstantDirectory;
3574         if (directory == null) {
3575             T[] universe = getEnumConstantsShared();
3576             if (universe == null)
3577                 throw new IllegalArgumentException(
3578                     getName() + " is not an enum type");
3579             directory = new HashMap<>((int)(universe.length / 0.75f) + 1);
3580             for (T constant : universe) {
3581                 directory.put(((Enum<?>)constant).name(), constant);
3582             }
3583             enumConstantDirectory = directory;
3584         }
3585         return directory;
3586     }
3587     private transient volatile Map<String, T> enumConstantDirectory;
3588
3589     /**
3590      * Casts an object to the class or interface represented
3591      * by this {@code Class} object.
3592      *
3593      * @param obj the object to be cast
3594      * @return the object after casting, or null if obj is null
3595      *
3596      * @throws ClassCastException if the object is not
3597      * null and is not assignable to the type T.
3598      *
3599      * @since 1.5
3600      */

3601     @SuppressWarnings("unchecked")
3602     @HotSpotIntrinsicCandidate
3603     public T cast(Object obj) {
3604         if (obj != null && !isInstance(obj))
3605             throw new ClassCastException(cannotCastMsg(obj));
3606         return (T) obj;
3607     }
3608
3609     private String cannotCastMsg(Object obj) {
3610         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3611     }
3612
3613     /**
3614      * Casts this {@code Class} object to represent a subclass of the class
3615      * represented by the specified class object.  Checks that the cast
3616      * is valid, and throws a {@code ClassCastException} if it is not.  If
3617      * this method succeeds, it always returns a reference to this class object.
3618      *
3619      * <p>This method is useful when a client needs to "narrow" the type of
3620      * a {@code Class} object to pass it to an API that restricts the
3621      * {@code Class} objects that it is willing to accept.  A cast would
3622      * generate a compile-time warning, as the correctness of the cast
3623      * could not be checked at runtime (because generic types are implemented
3624      * by erasure).
3625      *
3626      * @param <U> the type to cast this class object to
3627      * @param clazz the class of the type to cast this class object to
3628      * @return this {@code Class} object, cast to represent a subclass of
3629      *    the specified class object.
3630      * @throws ClassCastException if this {@code Class} object does not
3631      *    represent a subclass of the specified class (here "subclass" includes
3632      *    the class itself).
3633      * @since 1.5
3634      */

3635     @SuppressWarnings("unchecked")
3636     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
3637         if (clazz.isAssignableFrom(this))
3638             return (Class<? extends U>) this;
3639         else
3640             throw new ClassCastException(this.toString());
3641     }
3642
3643     /**
3644      * @throws NullPointerException {@inheritDoc}
3645      * @since 1.5
3646      */

3647     @SuppressWarnings("unchecked")
3648     public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
3649         Objects.requireNonNull(annotationClass);
3650
3651         return (A) annotationData().annotations.get(annotationClass);
3652     }
3653
3654     /**
3655      * {@inheritDoc}
3656      * @throws NullPointerException {@inheritDoc}
3657      * @since 1.5
3658      */

3659     @Override
3660     public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
3661         return GenericDeclaration.super.isAnnotationPresent(annotationClass);
3662     }
3663
3664     /**
3665      * @throws NullPointerException {@inheritDoc}
3666      * @since 1.8
3667      */

3668     @Override
3669     public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {
3670         Objects.requireNonNull(annotationClass);
3671
3672         AnnotationData annotationData = annotationData();
3673         return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations,
3674                                                           this,
3675                                                           annotationClass);
3676     }
3677
3678     /**
3679      * @since 1.5
3680      */

3681     public Annotation[] getAnnotations() {
3682         return AnnotationParser.toArray(annotationData().annotations);
3683     }
3684
3685     /**
3686      * @throws NullPointerException {@inheritDoc}
3687      * @since 1.8
3688      */

3689     @Override
3690     @SuppressWarnings("unchecked")
3691     public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
3692         Objects.requireNonNull(annotationClass);
3693
3694         return (A) annotationData().declaredAnnotations.get(annotationClass);
3695     }
3696
3697     /**
3698      * @throws NullPointerException {@inheritDoc}
3699      * @since 1.8
3700      */

3701     @Override
3702     public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {
3703         Objects.requireNonNull(annotationClass);
3704
3705         return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,
3706                                                                  annotationClass);
3707     }
3708
3709     /**
3710      * @since 1.5
3711      */

3712     public Annotation[] getDeclaredAnnotations()  {
3713         return AnnotationParser.toArray(annotationData().declaredAnnotations);
3714     }
3715
3716     // annotation data that might get invalidated when JVM TI RedefineClasses() is called
3717     private static class AnnotationData {
3718         final Map<Class<? extends Annotation>, Annotation> annotations;
3719         final Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
3720
3721         // Value of classRedefinedCount when we created this AnnotationData instance
3722         final int redefinedCount;
3723
3724         AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations,
3725                        Map<Class<? extends Annotation>, Annotation> declaredAnnotations,
3726                        int redefinedCount) {
3727             this.annotations = annotations;
3728             this.declaredAnnotations = declaredAnnotations;
3729             this.redefinedCount = redefinedCount;
3730         }
3731     }
3732
3733     // Annotations cache
3734     @SuppressWarnings("UnusedDeclaration")
3735     private transient volatile AnnotationData annotationData;
3736
3737     private AnnotationData annotationData() {
3738         while (true) { // retry loop
3739             AnnotationData annotationData = this.annotationData;
3740             int classRedefinedCount = this.classRedefinedCount;
3741             if (annotationData != null &&
3742                 annotationData.redefinedCount == classRedefinedCount) {
3743                 return annotationData;
3744             }
3745             // null or stale annotationData -> optimistically create new instance
3746             AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount);
3747             // try to install it
3748             if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) {
3749                 // successfully installed new AnnotationData
3750                 return newAnnotationData;
3751             }
3752         }
3753     }
3754
3755     private AnnotationData createAnnotationData(int classRedefinedCount) {
3756         Map<Class<? extends Annotation>, Annotation> declaredAnnotations =
3757             AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this);
3758         Class<?> superClass = getSuperclass();
3759         Map<Class<? extends Annotation>, Annotation> annotations = null;
3760         if (superClass != null) {
3761             Map<Class<? extends Annotation>, Annotation> superAnnotations =
3762                 superClass.annotationData().annotations;
3763             for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) {
3764                 Class<? extends Annotation> annotationClass = e.getKey();
3765                 if (AnnotationType.getInstance(annotationClass).isInherited()) {
3766                     if (annotations == null) { // lazy construction
3767                         annotations = new LinkedHashMap<>((Math.max(
3768                                 declaredAnnotations.size(),
3769                                 Math.min(12, declaredAnnotations.size() + superAnnotations.size())
3770                             ) * 4 + 2) / 3
3771                         );
3772                     }
3773                     annotations.put(annotationClass, e.getValue());
3774                 }
3775             }
3776         }
3777         if (annotations == null) {
3778             // no inherited annotations -> share the Map with declaredAnnotations
3779             annotations = declaredAnnotations;
3780         } else {
3781             // at least one inherited annotation -> declared may override inherited
3782             annotations.putAll(declaredAnnotations);
3783         }
3784         return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount);
3785     }
3786
3787     // Annotation types cache their internal (AnnotationType) form
3788
3789     @SuppressWarnings("UnusedDeclaration")
3790     private transient volatile AnnotationType annotationType;
3791
3792     boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {
3793         return Atomic.casAnnotationType(this, oldType, newType);
3794     }
3795
3796     AnnotationType getAnnotationType() {
3797         return annotationType;
3798     }
3799
3800     Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() {
3801         return annotationData().declaredAnnotations;
3802     }
3803
3804     /* Backing store of user-defined values pertaining to this class.
3805      * Maintained by the ClassValue class.
3806      */

3807     transient ClassValue.ClassValueMap classValueMap;
3808
3809     /**
3810      * Returns an {@code AnnotatedType} object that represents the use of a
3811      * type to specify the superclass of the entity represented by this {@code
3812      * Class} object. (The <em>use</em> of type Foo to specify the superclass
3813      * in '...  extends Foo' is distinct from the <em>declaration</em> of type
3814      * Foo.)
3815      *
3816      * <p> If this {@code Class} object represents a type whose declaration
3817      * does not explicitly indicate an annotated superclass, then the return
3818      * value is an {@code AnnotatedType} object representing an element with no
3819      * annotations.
3820      *
3821      * <p> If this {@code Class} represents either the {@code Object} class, an
3822      * interface type, an array type, a primitive type, or void, the return
3823      * value is {@code null}.
3824      *
3825      * @return an object representing the superclass
3826      * @since 1.8
3827      */

3828     public AnnotatedType getAnnotatedSuperclass() {
3829         if (this == Object.class ||
3830                 isInterface() ||
3831                 isArray() ||
3832                 isPrimitive() ||
3833                 this == Void.TYPE) {
3834             return null;
3835         }
3836
3837         return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
3838     }
3839
3840     /**
3841      * Returns an array of {@code AnnotatedType} objects that represent the use
3842      * of types to specify superinterfaces of the entity represented by this
3843      * {@code Class} object. (The <em>use</em> of type Foo to specify a
3844      * superinterface in '... implements Foo' is distinct from the
3845      * <em>declaration</em> of type Foo.)
3846      *
3847      * <p> If this {@code Class} object represents a class, the return value is
3848      * an array containing objects representing the uses of interface types to
3849      * specify interfaces implemented by the class. The order of the objects in
3850      * the array corresponds to the order of the interface types used in the
3851      * 'implements' clause of the declaration of this {@code Class} object.
3852      *
3853      * <p> If this {@code Class} object represents an interface, the return
3854      * value is an array containing objects representing the uses of interface
3855      * types to specify interfaces directly extended by the interface. The
3856      * order of the objects in the array corresponds to the order of the
3857      * interface types used in the 'extends' clause of the declaration of this
3858      * {@code Class} object.
3859      *
3860      * <p> If this {@code Class} object represents a class or interface whose
3861      * declaration does not explicitly indicate any annotated superinterfaces,
3862      * the return value is an array of length 0.
3863      *
3864      * <p> If this {@code Class} object represents either the {@code Object}
3865      * class, an array type, a primitive type, or void, the return value is an
3866      * array of length 0.
3867      *
3868      * @return an array representing the superinterfaces
3869      * @since 1.8
3870      */

3871     public AnnotatedType[] getAnnotatedInterfaces() {
3872          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3873     }
3874
3875     private native Class<?> getNestHost0();
3876
3877     /**
3878      * Returns the nest host of the <a href=#nest>nest</a> to which the class
3879      * or interface represented by this {@code Class} object belongs.
3880      * Every class and interface is a member of exactly one nest.
3881      * A class or interface that is not recorded as belonging to a nest
3882      * belongs to the nest consisting only of itself, and is the nest
3883      * host.
3884      *
3885      * <p>Each of the {@code Class} objects representing array types,
3886      * primitive types, and {@code void} returns {@code this} to indicate
3887      * that the represented entity belongs to the nest consisting only of
3888      * itself, and is the nest host.
3889      *
3890      * <p>If there is a {@linkplain LinkageError linkage error} accessing
3891      * the nest host, or if this class or interface is not enumerated as
3892      * a member of the nest by the nest host, then it is considered to belong
3893      * to its own nest and {@code this} is returned as the host.
3894      *
3895      * @apiNote A {@code class} file of version 55.0 or greater may record the
3896      * host of the nest to which it belongs by using the {@code NestHost}
3897      * attribute (JVMS 4.7.28). Alternatively, a {@code class} file of
3898      * version 55.0 or greater may act as a nest host by enumerating the nest's
3899      * other members with the
3900      * {@code NestMembers} attribute (JVMS 4.7.29).
3901      * A {@code class} file of version 54.0 or lower does not use these
3902      * attributes.
3903      *
3904      * @return the nest host of this class or interface
3905      *
3906      * @throws SecurityException
3907      *         If the returned class is not the current class, and
3908      *         if a security manager, <i>s</i>, is present and the caller's
3909      *         class loader is not the same as or an ancestor of the class
3910      *         loader for the returned class and invocation of {@link
3911      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
3912      *         denies access to the package of the returned class
3913      * @since 11
3914      * @jvms 4.7.28 and 4.7.29 NestHost and NestMembers attributes
3915      * @jvms 5.4.4 Access Control
3916      */

3917     @CallerSensitive
3918     public Class<?> getNestHost() {
3919         if (isPrimitive() || isArray()) {
3920             return this;
3921         }
3922         Class<?> host;
3923         try {
3924             host = getNestHost0();
3925         } catch (LinkageError e) {
3926             // if we couldn't load our nest-host then we
3927             // act as-if we have no nest-host attribute
3928             return this;
3929         }
3930         // if null then nest membership validation failed, so we
3931         // act as-if we have no nest-host attribute
3932         if (host == null || host == this) {
3933             return this;
3934         }
3935         // returning a different class requires a security check
3936         SecurityManager sm = System.getSecurityManager();
3937         if (sm != null) {
3938             checkPackageAccess(sm,
3939                                ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
3940         }
3941         return host;
3942     }
3943
3944     /**
3945      * Determines if the given {@code Class} is a nestmate of the
3946      * class or interface represented by this {@code Class} object.
3947      * Two classes or interfaces are nestmates
3948      * if they have the same {@linkplain #getNestHost() nest host}.
3949      *
3950      * @param c the class to check
3951      * @return {@code trueif this class and {@code c} are members of
3952      * the same nest; and {@code false} otherwise.
3953      *
3954      * @since 11
3955      */

3956     public boolean isNestmateOf(Class<?> c) {
3957         if (this == c) {
3958             return true;
3959         }
3960         if (isPrimitive() || isArray() ||
3961             c.isPrimitive() || c.isArray()) {
3962             return false;
3963         }
3964         try {
3965             return getNestHost0() == c.getNestHost0();
3966         } catch (LinkageError e) {
3967             return false;
3968         }
3969     }
3970
3971     private native Class<?>[] getNestMembers0();
3972
3973     /**
3974      * Returns an array containing {@code Class} objects representing all the
3975      * classes and interfaces that are members of the nest to which the class
3976      * or interface represented by this {@code Class} object belongs.
3977      * The {@linkplain #getNestHost() nest host} of that nest is the zeroth
3978      * element of the array. Subsequent elements represent any classes or
3979      * interfaces that are recorded by the nest host as being members of
3980      * the nest; the order of such elements is unspecified. Duplicates are
3981      * permitted.
3982      * If the nest host of that nest does not enumerate any members, then the
3983      * array has a single element containing {@code this}.
3984      *
3985      * <p>Each of the {@code Class} objects representing array types,
3986      * primitive types, and {@code void} returns an array containing only
3987      * {@code this}.
3988      *
3989      * <p>This method validates that, for each class or interface which is
3990      * recorded as a member of the nest by the nest host, that class or
3991      * interface records itself as a member of that same nest. Any exceptions
3992      * that occur during this validation are rethrown by this method.
3993      *
3994      * @return an array of all classes and interfaces in the same nest as
3995      * this class
3996      *
3997      * @throws LinkageError
3998      *         If there is any problem loading or validating a nest member or
3999      *         its nest host
4000      * @throws SecurityException
4001      *         If any returned class is not the current class, and
4002      *         if a security manager, <i>s</i>, is present and the caller's
4003      *         class loader is not the same as or an ancestor of the class
4004      *         loader for that returned class and invocation of {@link
4005      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
4006      *         denies access to the package of that returned class
4007      *
4008      * @since 11
4009      * @see #getNestHost()
4010      */

4011     @CallerSensitive
4012     public Class<?>[] getNestMembers() {
4013         if (isPrimitive() || isArray()) {
4014             return new Class<?>[] { this };
4015         }
4016         Class<?>[] members = getNestMembers0();
4017         // Can't actually enable this due to bootstrapping issues
4018         // assert(members.length != 1 || members[0] == this); // expected invariant from VM
4019
4020         if (members.length > 1) {
4021             // If we return anything other than the current class we need
4022             // a security check
4023             SecurityManager sm = System.getSecurityManager();
4024             if (sm != null) {
4025                 checkPackageAccess(sm,
4026                                    ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
4027             }
4028         }
4029         return members;
4030     }
4031 }
4032