Path: blob/master/src/java.base/share/classes/java/lang/Class.java
41152 views
/*1* Copyright (c) 1994, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.lang;2627import java.lang.annotation.Annotation;28import java.lang.constant.ClassDesc;29import java.lang.invoke.TypeDescriptor;30import java.lang.invoke.MethodHandles;31import java.lang.module.ModuleReader;32import java.lang.ref.SoftReference;33import java.io.IOException;34import java.io.InputStream;35import java.io.ObjectStreamField;36import java.lang.reflect.AnnotatedElement;37import java.lang.reflect.AnnotatedType;38import java.lang.reflect.Array;39import java.lang.reflect.Constructor;40import java.lang.reflect.Executable;41import java.lang.reflect.Field;42import java.lang.reflect.GenericArrayType;43import java.lang.reflect.GenericDeclaration;44import java.lang.reflect.InvocationTargetException;45import java.lang.reflect.Member;46import java.lang.reflect.Method;47import java.lang.reflect.Modifier;48import java.lang.reflect.Proxy;49import java.lang.reflect.RecordComponent;50import java.lang.reflect.Type;51import java.lang.reflect.TypeVariable;52import java.lang.constant.Constable;53import java.net.URL;54import java.security.AccessController;55import java.security.PrivilegedAction;56import java.util.ArrayList;57import java.util.Arrays;58import java.util.Collection;59import java.util.HashMap;60import java.util.HashSet;61import java.util.LinkedHashMap;62import java.util.LinkedHashSet;63import java.util.List;64import java.util.Map;65import java.util.Objects;66import java.util.Optional;67import java.util.Set;68import java.util.stream.Collectors;6970import jdk.internal.loader.BootLoader;71import jdk.internal.loader.BuiltinClassLoader;72import jdk.internal.misc.Unsafe;73import jdk.internal.module.Resources;74import jdk.internal.reflect.CallerSensitive;75import jdk.internal.reflect.ConstantPool;76import jdk.internal.reflect.Reflection;77import jdk.internal.reflect.ReflectionFactory;78import jdk.internal.vm.annotation.ForceInline;79import jdk.internal.vm.annotation.IntrinsicCandidate;80import sun.invoke.util.Wrapper;81import sun.reflect.generics.factory.CoreReflectionFactory;82import sun.reflect.generics.factory.GenericsFactory;83import sun.reflect.generics.repository.ClassRepository;84import sun.reflect.generics.repository.MethodRepository;85import sun.reflect.generics.repository.ConstructorRepository;86import sun.reflect.generics.scope.ClassScope;87import sun.security.util.SecurityConstants;88import sun.reflect.annotation.*;89import sun.reflect.misc.ReflectUtil;9091/**92* Instances of the class {@code Class} represent classes and93* interfaces in a running Java application. An enum class and a record94* class are kinds of class; an annotation interface is a kind of95* interface. Every array also belongs to a class that is reflected as96* a {@code Class} object that is shared by all arrays with the same97* element type and number of dimensions. The primitive Java types98* ({@code boolean}, {@code byte}, {@code char}, {@code short}, {@code99* int}, {@code long}, {@code float}, and {@code double}), and the100* keyword {@code void} are also represented as {@code Class} objects.101*102* <p> {@code Class} has no public constructor. Instead a {@code Class}103* object is constructed automatically by the Java Virtual Machine when104* a class is derived from the bytes of a {@code class} file through105* the invocation of one of the following methods:106* <ul>107* <li> {@link ClassLoader#defineClass(String, byte[], int, int) ClassLoader::defineClass}108* <li> {@link java.lang.invoke.MethodHandles.Lookup#defineClass(byte[])109* java.lang.invoke.MethodHandles.Lookup::defineClass}110* <li> {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)111* java.lang.invoke.MethodHandles.Lookup::defineHiddenClass}112* </ul>113*114* <p> The methods of class {@code Class} expose many characteristics of a115* class or interface. Most characteristics are derived from the {@code class}116* file that the class loader passed to the Java Virtual Machine or117* from the {@code class} file passed to {@code Lookup::defineClass}118* or {@code Lookup::defineHiddenClass}.119* A few characteristics are determined by the class loading environment120* at run time, such as the module returned by {@link #getModule() getModule()}.121*122* <p> The following example uses a {@code Class} object to print the123* class name of an object:124*125* <blockquote><pre>126* void printClassName(Object obj) {127* System.out.println("The class of " + obj +128* " is " + obj.getClass().getName());129* }130* </pre></blockquote>131*132* It is also possible to get the {@code Class} object for a named133* class or interface (or for {@code void}) using a <i>class literal</i>.134* For example:135*136* <blockquote>137* {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}138* </blockquote>139*140* <p> Some methods of class {@code Class} expose whether the declaration of141* a class or interface in Java source code was <em>enclosed</em> within142* another declaration. Other methods describe how a class or interface143* is situated in a <em>nest</em>. A <a id="nest">nest</a> is a set of144* classes and interfaces, in the same run-time package, that145* allow mutual access to their {@code private} members.146* The classes and interfaces are known as <em>nestmates</em>.147* One nestmate acts as the148* <em>nest host</em>, and enumerates the other nestmates which149* belong to the nest; each of them in turn records it as the nest host.150* The classes and interfaces which belong to a nest, including its host, are151* determined when152* {@code class} files are generated, for example, a Java compiler153* will typically record a top-level class as the host of a nest where the154* other members are the classes and interfaces whose declarations are155* enclosed within the top-level class declaration.156*157* <p> A class or interface created by the invocation of158* {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)159* Lookup::defineHiddenClass} is a {@linkplain Class#isHidden() <em>hidden</em>}160* class or interface.161* All kinds of class, including enum classes and record classes, may be162* hidden classes; all kinds of interface, including annotation interfaces,163* may be hidden interfaces.164*165* The {@linkplain #getName() name of a hidden class or interface} is166* not a <a href="ClassLoader.html#binary-name">binary name</a>,167* which means the following:168* <ul>169* <li>A hidden class or interface cannot be referenced by the constant pools170* of other classes and interfaces.171* <li>A hidden class or interface cannot be described in172* {@linkplain java.lang.constant.ConstantDesc <em>nominal form</em>} by173* {@link #describeConstable() Class::describeConstable},174* {@link ClassDesc#of(String) ClassDesc::of}, or175* {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor}.176* <li>A hidden class or interface cannot be discovered by {@link #forName Class::forName}177* or {@link ClassLoader#loadClass(String, boolean) ClassLoader::loadClass}.178* </ul>179*180* A hidden class or interface is never an array class, but may be181* the element type of an array. In all other respects, the fact that182* a class or interface is hidden has no bearing on the characteristics183* exposed by the methods of class {@code Class}.184*185* @param <T> the type of the class modeled by this {@code Class}186* object. For example, the type of {@code String.class} is {@code187* Class<String>}. Use {@code Class<?>} if the class being modeled is188* unknown.189*190* @see java.lang.ClassLoader#defineClass(byte[], int, int)191* @since 1.0192* @jls 15.8.2 Class Literals193*/194public final class Class<T> implements java.io.Serializable,195GenericDeclaration,196Type,197AnnotatedElement,198TypeDescriptor.OfField<Class<?>>,199Constable {200private static final int ANNOTATION= 0x00002000;201private static final int ENUM = 0x00004000;202private static final int SYNTHETIC = 0x00001000;203204private static native void registerNatives();205static {206registerNatives();207}208209/*210* Private constructor. Only the Java Virtual Machine creates Class objects.211* This constructor is not used and prevents the default constructor being212* generated.213*/214private Class(ClassLoader loader, Class<?> arrayComponentType) {215// Initialize final field for classLoader. The initialization value of non-null216// prevents future JIT optimizations from assuming this final field is null.217classLoader = loader;218componentType = arrayComponentType;219}220221/**222* Converts the object to a string. The string representation is the223* string "class" or "interface", followed by a space, and then by the224* name of the class in the format returned by {@code getName}.225* If this {@code Class} object represents a primitive type,226* this method returns the name of the primitive type. If227* this {@code Class} object represents void this method returns228* "void". If this {@code Class} object represents an array type,229* this method returns "class " followed by {@code getName}.230*231* @return a string representation of this {@code Class} object.232*/233public String toString() {234return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))235+ getName();236}237238/**239* Returns a string describing this {@code Class}, including240* information about modifiers and type parameters.241*242* The string is formatted as a list of type modifiers, if any,243* followed by the kind of type (empty string for primitive types244* and {@code class}, {@code enum}, {@code interface},245* {@code @interface}, or {@code record} as appropriate), followed246* by the type's name, followed by an angle-bracketed247* comma-separated list of the type's type parameters, if any,248* including informative bounds on the type parameters, if any.249*250* A space is used to separate modifiers from one another and to251* separate any modifiers from the kind of type. The modifiers252* occur in canonical order. If there are no type parameters, the253* type parameter list is elided.254*255* For an array type, the string starts with the type name,256* followed by an angle-bracketed comma-separated list of the257* type's type parameters, if any, followed by a sequence of258* {@code []} characters, one set of brackets per dimension of259* the array.260*261* <p>Note that since information about the runtime representation262* of a type is being generated, modifiers not present on the263* originating source code or illegal on the originating source264* code may be present.265*266* @return a string describing this {@code Class}, including267* information about modifiers and type parameters268*269* @since 1.8270*/271public String toGenericString() {272if (isPrimitive()) {273return toString();274} else {275StringBuilder sb = new StringBuilder();276Class<?> component = this;277int arrayDepth = 0;278279if (isArray()) {280do {281arrayDepth++;282component = component.getComponentType();283} while (component.isArray());284sb.append(component.getName());285} else {286// Class modifiers are a superset of interface modifiers287int modifiers = getModifiers() & Modifier.classModifiers();288if (modifiers != 0) {289sb.append(Modifier.toString(modifiers));290sb.append(' ');291}292293if (isAnnotation()) {294sb.append('@');295}296if (isInterface()) { // Note: all annotation interfaces are interfaces297sb.append("interface");298} else {299if (isEnum())300sb.append("enum");301else if (isRecord())302sb.append("record");303else304sb.append("class");305}306sb.append(' ');307sb.append(getName());308}309310TypeVariable<?>[] typeparms = component.getTypeParameters();311if (typeparms.length > 0) {312sb.append(Arrays.stream(typeparms)313.map(Class::typeVarBounds)314.collect(Collectors.joining(",", "<", ">")));315}316317if (arrayDepth > 0) sb.append("[]".repeat(arrayDepth));318319return sb.toString();320}321}322323static String typeVarBounds(TypeVariable<?> typeVar) {324Type[] bounds = typeVar.getBounds();325if (bounds.length == 1 && bounds[0].equals(Object.class)) {326return typeVar.getName();327} else {328return typeVar.getName() + " extends " +329Arrays.stream(bounds)330.map(Type::getTypeName)331.collect(Collectors.joining(" & "));332}333}334335/**336* Returns the {@code Class} object associated with the class or337* interface with the given string name. Invoking this method is338* equivalent to:339*340* <blockquote>341* {@code Class.forName(className, true, currentLoader)}342* </blockquote>343*344* where {@code currentLoader} denotes the defining class loader of345* the current class.346*347* <p> For example, the following code fragment returns the348* runtime {@code Class} descriptor for the class named349* {@code java.lang.Thread}:350*351* <blockquote>352* {@code Class t = Class.forName("java.lang.Thread")}353* </blockquote>354* <p>355* A call to {@code forName("X")} causes the class named356* {@code X} to be initialized.357*358* @param className the fully qualified name of the desired class.359* @return the {@code Class} object for the class with the360* specified name.361* @throws LinkageError if the linkage fails362* @throws ExceptionInInitializerError if the initialization provoked363* by this method fails364* @throws ClassNotFoundException if the class cannot be located365*366* @jls 12.2 Loading of Classes and Interfaces367* @jls 12.3 Linking of Classes and Interfaces368* @jls 12.4 Initialization of Classes and Interfaces369*/370@CallerSensitive371public static Class<?> forName(String className)372throws ClassNotFoundException {373Class<?> caller = Reflection.getCallerClass();374return forName0(className, true, ClassLoader.getClassLoader(caller), caller);375}376377378/**379* Returns the {@code Class} object associated with the class or380* interface with the given string name, using the given class loader.381* Given the fully qualified name for a class or interface (in the same382* format returned by {@code getName}) this method attempts to383* locate and load the class or interface. The specified class384* loader is used to load the class or interface. If the parameter385* {@code loader} is null, the class is loaded through the bootstrap386* class loader. The class is initialized only if the387* {@code initialize} parameter is {@code true} and if it has388* not been initialized earlier.389*390* <p> If {@code name} denotes a primitive type or void, an attempt391* will be made to locate a user-defined class in the unnamed package whose392* name is {@code name}. Therefore, this method cannot be used to393* obtain any of the {@code Class} objects representing primitive394* types or void.395*396* <p> If {@code name} denotes an array class, the component type of397* the array class is loaded but not initialized.398*399* <p> For example, in an instance method the expression:400*401* <blockquote>402* {@code Class.forName("Foo")}403* </blockquote>404*405* is equivalent to:406*407* <blockquote>408* {@code Class.forName("Foo", true, this.getClass().getClassLoader())}409* </blockquote>410*411* Note that this method throws errors related to loading, linking412* or initializing as specified in Sections {@jls 12.2}, {@jls413* 12.3}, and {@jls 12.4} of <cite>The Java Language414* Specification</cite>.415* Note that this method does not check whether the requested class416* is accessible to its caller.417*418* @param name fully qualified name of the desired class419420* @param initialize if {@code true} the class will be initialized421* (which implies linking). See Section {@jls422* 12.4} of <cite>The Java Language423* Specification</cite>.424* @param loader class loader from which the class must be loaded425* @return class object representing the desired class426*427* @throws LinkageError if the linkage fails428* @throws ExceptionInInitializerError if the initialization provoked429* by this method fails430* @throws ClassNotFoundException if the class cannot be located by431* the specified class loader432* @throws SecurityException433* if a security manager is present, and the {@code loader} is434* {@code null}, and the caller's class loader is not435* {@code null}, and the caller does not have the436* {@link RuntimePermission}{@code ("getClassLoader")}437*438* @see java.lang.Class#forName(String)439* @see java.lang.ClassLoader440*441* @jls 12.2 Loading of Classes and Interfaces442* @jls 12.3 Linking of Classes and Interfaces443* @jls 12.4 Initialization of Classes and Interfaces444* @since 1.2445*/446@CallerSensitive447public static Class<?> forName(String name, boolean initialize,448ClassLoader loader)449throws ClassNotFoundException450{451Class<?> caller = null;452@SuppressWarnings("removal")453SecurityManager sm = System.getSecurityManager();454if (sm != null) {455// Reflective call to get caller class is only needed if a security manager456// is present. Avoid the overhead of making this call otherwise.457caller = Reflection.getCallerClass();458if (loader == null) {459ClassLoader ccl = ClassLoader.getClassLoader(caller);460if (ccl != null) {461sm.checkPermission(462SecurityConstants.GET_CLASSLOADER_PERMISSION);463}464}465}466return forName0(name, initialize, loader, caller);467}468469/** Called after security check for system loader access checks have been made. */470private static native Class<?> forName0(String name, boolean initialize,471ClassLoader loader,472Class<?> caller)473throws ClassNotFoundException;474475476/**477* Returns the {@code Class} with the given <a href="ClassLoader.html#binary-name">478* binary name</a> in the given module.479*480* <p> This method attempts to locate and load the class or interface.481* It does not link the class, and does not run the class initializer.482* If the class is not found, this method returns {@code null}. </p>483*484* <p> If the class loader of the given module defines other modules and485* the given name is a class defined in a different module, this method486* returns {@code null} after the class is loaded. </p>487*488* <p> This method does not check whether the requested class is489* accessible to its caller. </p>490*491* @apiNote492* This method returns {@code null} on failure rather than493* throwing a {@link ClassNotFoundException}, as is done by494* the {@link #forName(String, boolean, ClassLoader)} method.495* The security check is a stack-based permission check if the caller496* loads a class in another module.497*498* @param module A module499* @param name The <a href="ClassLoader.html#binary-name">binary name</a>500* of the class501* @return {@code Class} object of the given name defined in the given module;502* {@code null} if not found.503*504* @throws NullPointerException if the given module or name is {@code null}505*506* @throws LinkageError if the linkage fails507*508* @throws SecurityException509* <ul>510* <li> if the caller is not the specified module and511* {@code RuntimePermission("getClassLoader")} permission is denied; or</li>512* <li> access to the module content is denied. For example,513* permission check will be performed when a class loader calls514* {@link ModuleReader#open(String)} to read the bytes of a class file515* in a module.</li>516* </ul>517*518* @jls 12.2 Loading of Classes and Interfaces519* @jls 12.3 Linking of Classes and Interfaces520* @since 9521*/522@SuppressWarnings("removal")523@CallerSensitive524public static Class<?> forName(Module module, String name) {525Objects.requireNonNull(module);526Objects.requireNonNull(name);527528ClassLoader cl;529SecurityManager sm = System.getSecurityManager();530if (sm != null) {531Class<?> caller = Reflection.getCallerClass();532if (caller != null && caller.getModule() != module) {533// if caller is null, Class.forName is the last java frame on the stack.534// java.base has all permissions535sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);536}537PrivilegedAction<ClassLoader> pa = module::getClassLoader;538cl = AccessController.doPrivileged(pa);539} else {540cl = module.getClassLoader();541}542543if (cl != null) {544return cl.loadClass(module, name);545} else {546return BootLoader.loadClass(module, name);547}548}549550/**551* Creates a new instance of the class represented by this {@code Class}552* object. The class is instantiated as if by a {@code new}553* expression with an empty argument list. The class is initialized if it554* has not already been initialized.555*556* @deprecated This method propagates any exception thrown by the557* nullary constructor, including a checked exception. Use of558* this method effectively bypasses the compile-time exception559* checking that would otherwise be performed by the compiler.560* The {@link561* java.lang.reflect.Constructor#newInstance(java.lang.Object...)562* Constructor.newInstance} method avoids this problem by wrapping563* any exception thrown by the constructor in a (checked) {@link564* java.lang.reflect.InvocationTargetException}.565*566* <p>The call567*568* <pre>{@code569* clazz.newInstance()570* }</pre>571*572* can be replaced by573*574* <pre>{@code575* clazz.getDeclaredConstructor().newInstance()576* }</pre>577*578* The latter sequence of calls is inferred to be able to throw579* the additional exception types {@link580* InvocationTargetException} and {@link581* NoSuchMethodException}. Both of these exception types are582* subclasses of {@link ReflectiveOperationException}.583*584* @return a newly allocated instance of the class represented by this585* object.586* @throws IllegalAccessException if the class or its nullary587* constructor is not accessible.588* @throws InstantiationException589* if this {@code Class} represents an abstract class,590* an interface, an array class, a primitive type, or void;591* or if the class has no nullary constructor;592* or if the instantiation fails for some other reason.593* @throws ExceptionInInitializerError if the initialization594* provoked by this method fails.595* @throws SecurityException596* If a security manager, <i>s</i>, is present and597* the caller's class loader is not the same as or an598* ancestor of the class loader for the current class and599* invocation of {@link SecurityManager#checkPackageAccess600* s.checkPackageAccess()} denies access to the package601* of this class.602*/603@SuppressWarnings("removal")604@CallerSensitive605@Deprecated(since="9")606public T newInstance()607throws InstantiationException, IllegalAccessException608{609SecurityManager sm = System.getSecurityManager();610if (sm != null) {611checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false);612}613614// Constructor lookup615Constructor<T> tmpConstructor = cachedConstructor;616if (tmpConstructor == null) {617if (this == Class.class) {618throw new IllegalAccessException(619"Can not call newInstance() on the Class for java.lang.Class"620);621}622try {623Class<?>[] empty = {};624final Constructor<T> c = getReflectionFactory().copyConstructor(625getConstructor0(empty, Member.DECLARED));626// Disable accessibility checks on the constructor627// access check is done with the true caller628java.security.AccessController.doPrivileged(629new java.security.PrivilegedAction<>() {630public Void run() {631c.setAccessible(true);632return null;633}634});635cachedConstructor = tmpConstructor = c;636} catch (NoSuchMethodException e) {637throw (InstantiationException)638new InstantiationException(getName()).initCause(e);639}640}641642try {643Class<?> caller = Reflection.getCallerClass();644return getReflectionFactory().newInstance(tmpConstructor, null, caller);645} catch (InvocationTargetException e) {646Unsafe.getUnsafe().throwException(e.getTargetException());647// Not reached648return null;649}650}651652private transient volatile Constructor<T> cachedConstructor;653654/**655* Determines if the specified {@code Object} is assignment-compatible656* with the object represented by this {@code Class}. This method is657* the dynamic equivalent of the Java language {@code instanceof}658* operator. The method returns {@code true} if the specified659* {@code Object} argument is non-null and can be cast to the660* reference type represented by this {@code Class} object without661* raising a {@code ClassCastException.} It returns {@code false}662* otherwise.663*664* <p> Specifically, if this {@code Class} object represents a665* declared class, this method returns {@code true} if the specified666* {@code Object} argument is an instance of the represented class (or667* of any of its subclasses); it returns {@code false} otherwise. If668* this {@code Class} object represents an array class, this method669* returns {@code true} if the specified {@code Object} argument670* can be converted to an object of the array class by an identity671* conversion or by a widening reference conversion; it returns672* {@code false} otherwise. If this {@code Class} object673* represents an interface, this method returns {@code true} if the674* class or any superclass of the specified {@code Object} argument675* implements this interface; it returns {@code false} otherwise. If676* this {@code Class} object represents a primitive type, this method677* returns {@code false}.678*679* @param obj the object to check680* @return true if {@code obj} is an instance of this class681*682* @since 1.1683*/684@IntrinsicCandidate685public native boolean isInstance(Object obj);686687688/**689* Determines if the class or interface represented by this690* {@code Class} object is either the same as, or is a superclass or691* superinterface of, the class or interface represented by the specified692* {@code Class} parameter. It returns {@code true} if so;693* otherwise it returns {@code false}. If this {@code Class}694* object represents a primitive type, this method returns695* {@code true} if the specified {@code Class} parameter is696* exactly this {@code Class} object; otherwise it returns697* {@code false}.698*699* <p> Specifically, this method tests whether the type represented by the700* specified {@code Class} parameter can be converted to the type701* represented by this {@code Class} object via an identity conversion702* or via a widening reference conversion. See <cite>The Java Language703* Specification</cite>, sections {@jls 5.1.1} and {@jls 5.1.4},704* for details.705*706* @param cls the {@code Class} object to be checked707* @return the {@code boolean} value indicating whether objects of the708* type {@code cls} can be assigned to objects of this class709* @throws NullPointerException if the specified Class parameter is710* null.711* @since 1.1712*/713@IntrinsicCandidate714public native boolean isAssignableFrom(Class<?> cls);715716717/**718* Determines if this {@code Class} object represents an719* interface type.720*721* @return {@code true} if this {@code Class} object represents an interface;722* {@code false} otherwise.723*/724@IntrinsicCandidate725public native boolean isInterface();726727728/**729* Determines if this {@code Class} object represents an array class.730*731* @return {@code true} if this {@code Class} object represents an array class;732* {@code false} otherwise.733* @since 1.1734*/735@IntrinsicCandidate736public native boolean isArray();737738739/**740* Determines if the specified {@code Class} object represents a741* primitive type.742*743* <p> There are nine predefined {@code Class} objects to represent744* the eight primitive types and void. These are created by the Java745* Virtual Machine, and have the same names as the primitive types that746* they represent, namely {@code boolean}, {@code byte},747* {@code char}, {@code short}, {@code int},748* {@code long}, {@code float}, and {@code double}.749*750* <p> These objects may only be accessed via the following public static751* final variables, and are the only {@code Class} objects for which752* this method returns {@code true}.753*754* @return true if and only if this class represents a primitive type755*756* @see java.lang.Boolean#TYPE757* @see java.lang.Character#TYPE758* @see java.lang.Byte#TYPE759* @see java.lang.Short#TYPE760* @see java.lang.Integer#TYPE761* @see java.lang.Long#TYPE762* @see java.lang.Float#TYPE763* @see java.lang.Double#TYPE764* @see java.lang.Void#TYPE765* @since 1.1766*/767@IntrinsicCandidate768public native boolean isPrimitive();769770/**771* Returns true if this {@code Class} object represents an annotation772* interface. Note that if this method returns true, {@link #isInterface()}773* would also return true, as all annotation interfaces are also interfaces.774*775* @return {@code true} if this {@code Class} object represents an annotation776* interface; {@code false} otherwise777* @since 1.5778*/779public boolean isAnnotation() {780return (getModifiers() & ANNOTATION) != 0;781}782783/**784*{@return {@code true} if and only if this class has the synthetic modifier785* bit set}786*787* @jls 13.1 The Form of a Binary788* @jvms 4.1 The {@code ClassFile} Structure789* @see <a790* href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java791* programming language and JVM modeling in core reflection</a>792* @since 1.5793*/794public boolean isSynthetic() {795return (getModifiers() & SYNTHETIC) != 0;796}797798/**799* Returns the name of the entity (class, interface, array class,800* primitive type, or void) represented by this {@code Class} object.801*802* <p> If this {@code Class} object represents a class or interface,803* not an array class, then:804* <ul>805* <li> If the class or interface is not {@linkplain #isHidden() hidden},806* then the <a href="ClassLoader.html#binary-name">binary name</a>807* of the class or interface is returned.808* <li> If the class or interface is hidden, then the result is a string809* of the form: {@code N + '/' + <suffix>}810* where {@code N} is the <a href="ClassLoader.html#binary-name">binary name</a>811* indicated by the {@code class} file passed to812* {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)813* Lookup::defineHiddenClass}, and {@code <suffix>} is an unqualified name.814* </ul>815*816* <p> If this {@code Class} object represents an array class, then817* the result is a string consisting of one or more '{@code [}' characters818* representing the depth of the array nesting, followed by the element819* type as encoded using the following table:820*821* <blockquote><table class="striped">822* <caption style="display:none">Element types and encodings</caption>823* <thead>824* <tr><th scope="col"> Element Type <th scope="col"> Encoding825* </thead>826* <tbody style="text-align:left">827* <tr><th scope="row"> {@code boolean} <td style="text-align:center"> {@code Z}828* <tr><th scope="row"> {@code byte} <td style="text-align:center"> {@code B}829* <tr><th scope="row"> {@code char} <td style="text-align:center"> {@code C}830* <tr><th scope="row"> class or interface with <a href="ClassLoader.html#binary-name">binary name</a> <i>N</i>831* <td style="text-align:center"> {@code L}<em>N</em>{@code ;}832* <tr><th scope="row"> {@code double} <td style="text-align:center"> {@code D}833* <tr><th scope="row"> {@code float} <td style="text-align:center"> {@code F}834* <tr><th scope="row"> {@code int} <td style="text-align:center"> {@code I}835* <tr><th scope="row"> {@code long} <td style="text-align:center"> {@code J}836* <tr><th scope="row"> {@code short} <td style="text-align:center"> {@code S}837* </tbody>838* </table></blockquote>839*840* <p> If this {@code Class} object represents a primitive type or {@code void},841* then the result is a string with the same spelling as the Java language842* keyword which corresponds to the primitive type or {@code void}.843*844* <p> Examples:845* <blockquote><pre>846* String.class.getName()847* returns "java.lang.String"848* byte.class.getName()849* returns "byte"850* (new Object[3]).getClass().getName()851* returns "[Ljava.lang.Object;"852* (new int[3][4][5][6][7][8][9]).getClass().getName()853* returns "[[[[[[[I"854* </pre></blockquote>855*856* @return the name of the class, interface, or other entity857* represented by this {@code Class} object.858* @jls 13.1 The Form of a Binary859*/860public String getName() {861String name = this.name;862return name != null ? name : initClassName();863}864865// Cache the name to reduce the number of calls into the VM.866// This field would be set by VM itself during initClassName call.867private transient String name;868private native String initClassName();869870/**871* Returns the class loader for the class. Some implementations may use872* null to represent the bootstrap class loader. This method will return873* null in such implementations if this class was loaded by the bootstrap874* class loader.875*876* <p>If this {@code Class} object877* represents a primitive type or void, null is returned.878*879* @return the class loader that loaded the class or interface880* represented by this {@code Class} object.881* @throws SecurityException882* if a security manager is present, and the caller's class loader883* is not {@code null} and is not the same as or an ancestor of the884* class loader for the class whose class loader is requested,885* and the caller does not have the886* {@link RuntimePermission}{@code ("getClassLoader")}887* @see java.lang.ClassLoader888* @see SecurityManager#checkPermission889* @see java.lang.RuntimePermission890*/891@CallerSensitive892@ForceInline // to ensure Reflection.getCallerClass optimization893public ClassLoader getClassLoader() {894ClassLoader cl = getClassLoader0();895if (cl == null)896return null;897@SuppressWarnings("removal")898SecurityManager sm = System.getSecurityManager();899if (sm != null) {900ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass());901}902return cl;903}904905// Package-private to allow ClassLoader access906ClassLoader getClassLoader0() { return classLoader; }907908/**909* Returns the module that this class or interface is a member of.910*911* If this class represents an array type then this method returns the912* {@code Module} for the element type. If this class represents a913* primitive type or void, then the {@code Module} object for the914* {@code java.base} module is returned.915*916* If this class is in an unnamed module then the {@linkplain917* ClassLoader#getUnnamedModule() unnamed} {@code Module} of the class918* loader for this class is returned.919*920* @return the module that this class or interface is a member of921*922* @since 9923*/924public Module getModule() {925return module;926}927928// set by VM929private transient Module module;930931// Initialized in JVM not by private constructor932// This field is filtered from reflection access, i.e. getDeclaredField933// will throw NoSuchFieldException934private final ClassLoader classLoader;935936// Set by VM937private transient Object classData;938939// package-private940Object getClassData() {941return classData;942}943944/**945* Returns an array of {@code TypeVariable} objects that represent the946* type variables declared by the generic declaration represented by this947* {@code GenericDeclaration} object, in declaration order. Returns an948* array of length 0 if the underlying generic declaration declares no type949* variables.950*951* @return an array of {@code TypeVariable} objects that represent952* the type variables declared by this generic declaration953* @throws java.lang.reflect.GenericSignatureFormatError if the generic954* signature of this generic declaration does not conform to955* the format specified in section {@jvms 4.7.9} of956* <cite>The Java Virtual Machine Specification</cite>957* @since 1.5958*/959@SuppressWarnings("unchecked")960public TypeVariable<Class<T>>[] getTypeParameters() {961ClassRepository info = getGenericInfo();962if (info != null)963return (TypeVariable<Class<T>>[])info.getTypeParameters();964else965return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];966}967968969/**970* Returns the {@code Class} representing the direct superclass of the971* entity (class, interface, primitive type or void) represented by972* this {@code Class}. If this {@code Class} represents either the973* {@code Object} class, an interface, a primitive type, or void, then974* null is returned. If this {@code Class} object represents an array class975* then the {@code Class} object representing the {@code Object} class is976* returned.977*978* @return the direct superclass of the class represented by this {@code Class} object979*/980@IntrinsicCandidate981public native Class<? super T> getSuperclass();982983984/**985* Returns the {@code Type} representing the direct superclass of986* the entity (class, interface, primitive type or void) represented by987* this {@code Class} object.988*989* <p>If the superclass is a parameterized type, the {@code Type}990* object returned must accurately reflect the actual type991* arguments used in the source code. The parameterized type992* representing the superclass is created if it had not been993* created before. See the declaration of {@link994* java.lang.reflect.ParameterizedType ParameterizedType} for the995* semantics of the creation process for parameterized types. If996* this {@code Class} object represents either the {@code Object}997* class, an interface, a primitive type, or void, then null is998* returned. If this {@code Class} object represents an array class999* then the {@code Class} object representing the {@code Object} class is1000* returned.1001*1002* @throws java.lang.reflect.GenericSignatureFormatError if the generic1003* class signature does not conform to the format specified in1004* section {@jvms 4.7.9} of <cite>The Java Virtual1005* Machine Specification</cite>1006* @throws TypeNotPresentException if the generic superclass1007* refers to a non-existent type declaration1008* @throws java.lang.reflect.MalformedParameterizedTypeException if the1009* generic superclass refers to a parameterized type that cannot be1010* instantiated for any reason1011* @return the direct superclass of the class represented by this {@code Class} object1012* @since 1.51013*/1014public Type getGenericSuperclass() {1015ClassRepository info = getGenericInfo();1016if (info == null) {1017return getSuperclass();1018}10191020// Historical irregularity:1021// Generic signature marks interfaces with superclass = Object1022// but this API returns null for interfaces1023if (isInterface()) {1024return null;1025}10261027return info.getSuperclass();1028}10291030/**1031* Gets the package of this class.1032*1033* <p>If this class represents an array type, a primitive type or void,1034* this method returns {@code null}.1035*1036* @return the package of this class.1037* @revised 91038*/1039public Package getPackage() {1040if (isPrimitive() || isArray()) {1041return null;1042}1043ClassLoader cl = getClassLoader0();1044return cl != null ? cl.definePackage(this)1045: BootLoader.definePackage(this);1046}10471048/**1049* Returns the fully qualified package name.1050*1051* <p> If this class is a top level class, then this method returns the fully1052* qualified name of the package that the class is a member of, or the1053* empty string if the class is in an unnamed package.1054*1055* <p> If this class is a member class, then this method is equivalent to1056* invoking {@code getPackageName()} on the {@linkplain #getEnclosingClass1057* enclosing class}.1058*1059* <p> If this class is a {@linkplain #isLocalClass local class} or an {@linkplain1060* #isAnonymousClass() anonymous class}, then this method is equivalent to1061* invoking {@code getPackageName()} on the {@linkplain #getDeclaringClass1062* declaring class} of the {@linkplain #getEnclosingMethod enclosing method} or1063* {@linkplain #getEnclosingConstructor enclosing constructor}.1064*1065* <p> If this class represents an array type then this method returns the1066* package name of the element type. If this class represents a primitive1067* type or void then the package name "{@code java.lang}" is returned.1068*1069* @return the fully qualified package name1070*1071* @since 91072* @jls 6.7 Fully Qualified Names1073*/1074public String getPackageName() {1075String pn = this.packageName;1076if (pn == null) {1077Class<?> c = isArray() ? elementType() : this;1078if (c.isPrimitive()) {1079pn = "java.lang";1080} else {1081String cn = c.getName();1082int dot = cn.lastIndexOf('.');1083pn = (dot != -1) ? cn.substring(0, dot).intern() : "";1084}1085this.packageName = pn;1086}1087return pn;1088}10891090// cached package name1091private transient String packageName;10921093/**1094* Returns the interfaces directly implemented by the class or interface1095* represented by this {@code Class} object.1096*1097* <p>If this {@code Class} object represents a class, the return value is an array1098* containing objects representing all interfaces directly implemented by1099* the class. The order of the interface objects in the array corresponds1100* to the order of the interface names in the {@code implements} clause of1101* the declaration of the class represented by this {@code Class} object. For example,1102* given the declaration:1103* <blockquote>1104* {@code class Shimmer implements FloorWax, DessertTopping { ... }}1105* </blockquote>1106* suppose the value of {@code s} is an instance of1107* {@code Shimmer}; the value of the expression:1108* <blockquote>1109* {@code s.getClass().getInterfaces()[0]}1110* </blockquote>1111* is the {@code Class} object that represents interface1112* {@code FloorWax}; and the value of:1113* <blockquote>1114* {@code s.getClass().getInterfaces()[1]}1115* </blockquote>1116* is the {@code Class} object that represents interface1117* {@code DessertTopping}.1118*1119* <p>If this {@code Class} object represents an interface, the array contains objects1120* representing all interfaces directly extended by the interface. The1121* order of the interface objects in the array corresponds to the order of1122* the interface names in the {@code extends} clause of the declaration of1123* the interface represented by this {@code Class} object.1124*1125* <p>If this {@code Class} object represents a class or interface that implements no1126* interfaces, the method returns an array of length 0.1127*1128* <p>If this {@code Class} object represents a primitive type or void, the method1129* returns an array of length 0.1130*1131* <p>If this {@code Class} object represents an array type, the1132* interfaces {@code Cloneable} and {@code java.io.Serializable} are1133* returned in that order.1134*1135* @return an array of interfaces directly implemented by this class1136*/1137public Class<?>[] getInterfaces() {1138// defensively copy before handing over to user code1139return getInterfaces(true);1140}11411142private Class<?>[] getInterfaces(boolean cloneArray) {1143ReflectionData<T> rd = reflectionData();1144if (rd == null) {1145// no cloning required1146return getInterfaces0();1147} else {1148Class<?>[] interfaces = rd.interfaces;1149if (interfaces == null) {1150interfaces = getInterfaces0();1151rd.interfaces = interfaces;1152}1153// defensively copy if requested1154return cloneArray ? interfaces.clone() : interfaces;1155}1156}11571158private native Class<?>[] getInterfaces0();11591160/**1161* Returns the {@code Type}s representing the interfaces1162* directly implemented by the class or interface represented by1163* this {@code Class} object.1164*1165* <p>If a superinterface is a parameterized type, the1166* {@code Type} object returned for it must accurately reflect1167* the actual type arguments used in the source code. The1168* parameterized type representing each superinterface is created1169* if it had not been created before. See the declaration of1170* {@link java.lang.reflect.ParameterizedType ParameterizedType}1171* for the semantics of the creation process for parameterized1172* types.1173*1174* <p>If this {@code Class} object represents a class, the return value is an array1175* containing objects representing all interfaces directly implemented by1176* the class. The order of the interface objects in the array corresponds1177* to the order of the interface names in the {@code implements} clause of1178* the declaration of the class represented by this {@code Class} object.1179*1180* <p>If this {@code Class} object represents an interface, the array contains objects1181* representing all interfaces directly extended by the interface. The1182* order of the interface objects in the array corresponds to the order of1183* the interface names in the {@code extends} clause of the declaration of1184* the interface represented by this {@code Class} object.1185*1186* <p>If this {@code Class} object represents a class or interface that implements no1187* interfaces, the method returns an array of length 0.1188*1189* <p>If this {@code Class} object represents a primitive type or void, the method1190* returns an array of length 0.1191*1192* <p>If this {@code Class} object represents an array type, the1193* interfaces {@code Cloneable} and {@code java.io.Serializable} are1194* returned in that order.1195*1196* @throws java.lang.reflect.GenericSignatureFormatError1197* if the generic class signature does not conform to the1198* format specified in section {@jvms 4.7.9} of <cite>The1199* Java Virtual Machine Specification</cite>1200* @throws TypeNotPresentException if any of the generic1201* superinterfaces refers to a non-existent type declaration1202* @throws java.lang.reflect.MalformedParameterizedTypeException1203* if any of the generic superinterfaces refer to a parameterized1204* type that cannot be instantiated for any reason1205* @return an array of interfaces directly implemented by this class1206* @since 1.51207*/1208public Type[] getGenericInterfaces() {1209ClassRepository info = getGenericInfo();1210return (info == null) ? getInterfaces() : info.getSuperInterfaces();1211}121212131214/**1215* Returns the {@code Class} representing the component type of an1216* array. If this class does not represent an array class this method1217* returns null.1218*1219* @return the {@code Class} representing the component type of this1220* class if this class is an array1221* @see java.lang.reflect.Array1222* @since 1.11223*/1224public Class<?> getComponentType() {1225// Only return for array types. Storage may be reused for Class for instance types.1226if (isArray()) {1227return componentType;1228} else {1229return null;1230}1231}12321233private final Class<?> componentType;12341235/*1236* Returns the {@code Class} representing the element type of an array class.1237* If this class does not represent an array class, then this method returns1238* {@code null}.1239*/1240private Class<?> elementType() {1241if (!isArray()) return null;12421243Class<?> c = this;1244while (c.isArray()) {1245c = c.getComponentType();1246}1247return c;1248}12491250/**1251* Returns the Java language modifiers for this class or interface, encoded1252* in an integer. The modifiers consist of the Java Virtual Machine's1253* constants for {@code public}, {@code protected},1254* {@code private}, {@code final}, {@code static},1255* {@code abstract} and {@code interface}; they should be decoded1256* using the methods of class {@code Modifier}.1257*1258* <p> If the underlying class is an array class, then its1259* {@code public}, {@code private} and {@code protected}1260* modifiers are the same as those of its component type. If this1261* {@code Class} object represents a primitive type or void, its1262* {@code public} modifier is always {@code true}, and its1263* {@code protected} and {@code private} modifiers are always1264* {@code false}. If this {@code Class} object represents an array class, a1265* primitive type or void, then its {@code final} modifier is always1266* {@code true} and its interface modifier is always1267* {@code false}. The values of its other modifiers are not determined1268* by this specification.1269*1270* <p> The modifier encodings are defined in section {@jvms 4.1}1271* of <cite>The Java Virtual Machine Specification</cite>.1272*1273* @return the {@code int} representing the modifiers for this class1274* @see java.lang.reflect.Modifier1275* @see <a1276* href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java1277* programming language and JVM modeling in core reflection</a>1278* @since 1.11279* @jls 8.1.1 Class Modifiers1280* @jls 9.1.1. Interface Modifiers1281*/1282@IntrinsicCandidate1283public native int getModifiers();128412851286/**1287* Gets the signers of this class.1288*1289* @return the signers of this class, or null if there are no signers. In1290* particular, this method returns null if this {@code Class} object represents1291* a primitive type or void.1292* @since 1.11293*/1294public native Object[] getSigners();129512961297/**1298* Set the signers of this class.1299*/1300native void setSigners(Object[] signers);130113021303/**1304* If this {@code Class} object represents a local or anonymous1305* class within a method, returns a {@link1306* java.lang.reflect.Method Method} object representing the1307* immediately enclosing method of the underlying class. Returns1308* {@code null} otherwise.1309*1310* In particular, this method returns {@code null} if the underlying1311* class is a local or anonymous class immediately enclosed by a class or1312* interface declaration, instance initializer or static initializer.1313*1314* @return the immediately enclosing method of the underlying class, if1315* that class is a local or anonymous class; otherwise {@code null}.1316*1317* @throws SecurityException1318* If a security manager, <i>s</i>, is present and any of the1319* following conditions is met:1320*1321* <ul>1322*1323* <li> the caller's class loader is not the same as the1324* class loader of the enclosing class and invocation of1325* {@link SecurityManager#checkPermission1326* s.checkPermission} method with1327* {@code RuntimePermission("accessDeclaredMembers")}1328* denies access to the methods within the enclosing class1329*1330* <li> the caller's class loader is not the same as or an1331* ancestor of the class loader for the enclosing class and1332* invocation of {@link SecurityManager#checkPackageAccess1333* s.checkPackageAccess()} denies access to the package1334* of the enclosing class1335*1336* </ul>1337* @since 1.51338*/1339@CallerSensitive1340public Method getEnclosingMethod() throws SecurityException {1341EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();13421343if (enclosingInfo == null)1344return null;1345else {1346if (!enclosingInfo.isMethod())1347return null;13481349MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),1350getFactory());1351Class<?> returnType = toClass(typeInfo.getReturnType());1352Type [] parameterTypes = typeInfo.getParameterTypes();1353Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];13541355// Convert Types to Classes; returned types *should*1356// be class objects since the methodDescriptor's used1357// don't have generics information1358for(int i = 0; i < parameterClasses.length; i++)1359parameterClasses[i] = toClass(parameterTypes[i]);13601361// Perform access check1362final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();1363@SuppressWarnings("removal")1364SecurityManager sm = System.getSecurityManager();1365if (sm != null) {1366enclosingCandidate.checkMemberAccess(sm, Member.DECLARED,1367Reflection.getCallerClass(), true);1368}1369Method[] candidates = enclosingCandidate.privateGetDeclaredMethods(false);13701371/*1372* Loop over all declared methods; match method name,1373* number of and type of parameters, *and* return1374* type. Matching return type is also necessary1375* because of covariant returns, etc.1376*/1377ReflectionFactory fact = getReflectionFactory();1378for (Method m : candidates) {1379if (m.getName().equals(enclosingInfo.getName()) &&1380arrayContentsEq(parameterClasses,1381fact.getExecutableSharedParameterTypes(m))) {1382// finally, check return type1383if (m.getReturnType().equals(returnType)) {1384return fact.copyMethod(m);1385}1386}1387}13881389throw new InternalError("Enclosing method not found");1390}1391}13921393private native Object[] getEnclosingMethod0();13941395private EnclosingMethodInfo getEnclosingMethodInfo() {1396Object[] enclosingInfo = getEnclosingMethod0();1397if (enclosingInfo == null)1398return null;1399else {1400return new EnclosingMethodInfo(enclosingInfo);1401}1402}14031404private static final class EnclosingMethodInfo {1405private final Class<?> enclosingClass;1406private final String name;1407private final String descriptor;14081409static void validate(Object[] enclosingInfo) {1410if (enclosingInfo.length != 3)1411throw new InternalError("Malformed enclosing method information");1412try {1413// The array is expected to have three elements:14141415// the immediately enclosing class1416Class<?> enclosingClass = (Class<?>)enclosingInfo[0];1417assert(enclosingClass != null);14181419// the immediately enclosing method or constructor's1420// name (can be null).1421String name = (String)enclosingInfo[1];14221423// the immediately enclosing method or constructor's1424// descriptor (null iff name is).1425String descriptor = (String)enclosingInfo[2];1426assert((name != null && descriptor != null) || name == descriptor);1427} catch (ClassCastException cce) {1428throw new InternalError("Invalid type in enclosing method information", cce);1429}1430}14311432EnclosingMethodInfo(Object[] enclosingInfo) {1433validate(enclosingInfo);1434this.enclosingClass = (Class<?>)enclosingInfo[0];1435this.name = (String)enclosingInfo[1];1436this.descriptor = (String)enclosingInfo[2];1437}14381439boolean isPartial() {1440return enclosingClass == null || name == null || descriptor == null;1441}14421443boolean isConstructor() { return !isPartial() && "<init>".equals(name); }14441445boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }14461447Class<?> getEnclosingClass() { return enclosingClass; }14481449String getName() { return name; }14501451String getDescriptor() { return descriptor; }14521453}14541455private static Class<?> toClass(Type o) {1456if (o instanceof GenericArrayType)1457return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),14580)1459.getClass();1460return (Class<?>)o;1461}14621463/**1464* If this {@code Class} object represents a local or anonymous1465* class within a constructor, returns a {@link1466* java.lang.reflect.Constructor Constructor} object representing1467* the immediately enclosing constructor of the underlying1468* class. Returns {@code null} otherwise. In particular, this1469* method returns {@code null} if the underlying class is a local1470* or anonymous class immediately enclosed by a class or1471* interface declaration, instance initializer or static initializer.1472*1473* @return the immediately enclosing constructor of the underlying class, if1474* that class is a local or anonymous class; otherwise {@code null}.1475* @throws SecurityException1476* If a security manager, <i>s</i>, is present and any of the1477* following conditions is met:1478*1479* <ul>1480*1481* <li> the caller's class loader is not the same as the1482* class loader of the enclosing class and invocation of1483* {@link SecurityManager#checkPermission1484* s.checkPermission} method with1485* {@code RuntimePermission("accessDeclaredMembers")}1486* denies access to the constructors within the enclosing class1487*1488* <li> the caller's class loader is not the same as or an1489* ancestor of the class loader for the enclosing class and1490* invocation of {@link SecurityManager#checkPackageAccess1491* s.checkPackageAccess()} denies access to the package1492* of the enclosing class1493*1494* </ul>1495* @since 1.51496*/1497@CallerSensitive1498public Constructor<?> getEnclosingConstructor() throws SecurityException {1499EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();15001501if (enclosingInfo == null)1502return null;1503else {1504if (!enclosingInfo.isConstructor())1505return null;15061507ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),1508getFactory());1509Type [] parameterTypes = typeInfo.getParameterTypes();1510Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];15111512// Convert Types to Classes; returned types *should*1513// be class objects since the methodDescriptor's used1514// don't have generics information1515for(int i = 0; i < parameterClasses.length; i++)1516parameterClasses[i] = toClass(parameterTypes[i]);15171518// Perform access check1519final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();1520@SuppressWarnings("removal")1521SecurityManager sm = System.getSecurityManager();1522if (sm != null) {1523enclosingCandidate.checkMemberAccess(sm, Member.DECLARED,1524Reflection.getCallerClass(), true);1525}15261527Constructor<?>[] candidates = enclosingCandidate1528.privateGetDeclaredConstructors(false);1529/*1530* Loop over all declared constructors; match number1531* of and type of parameters.1532*/1533ReflectionFactory fact = getReflectionFactory();1534for (Constructor<?> c : candidates) {1535if (arrayContentsEq(parameterClasses,1536fact.getExecutableSharedParameterTypes(c))) {1537return fact.copyConstructor(c);1538}1539}15401541throw new InternalError("Enclosing constructor not found");1542}1543}154415451546/**1547* If the class or interface represented by this {@code Class} object1548* is a member of another class, returns the {@code Class} object1549* representing the class in which it was declared. This method returns1550* null if this class or interface is not a member of any other class. If1551* this {@code Class} object represents an array class, a primitive1552* type, or void,then this method returns null.1553*1554* @return the declaring class for this class1555* @throws SecurityException1556* If a security manager, <i>s</i>, is present and the caller's1557* class loader is not the same as or an ancestor of the class1558* loader for the declaring class and invocation of {@link1559* SecurityManager#checkPackageAccess s.checkPackageAccess()}1560* denies access to the package of the declaring class1561* @since 1.11562*/1563@CallerSensitive1564public Class<?> getDeclaringClass() throws SecurityException {1565final Class<?> candidate = getDeclaringClass0();15661567if (candidate != null) {1568@SuppressWarnings("removal")1569SecurityManager sm = System.getSecurityManager();1570if (sm != null) {1571candidate.checkPackageAccess(sm,1572ClassLoader.getClassLoader(Reflection.getCallerClass()), true);1573}1574}1575return candidate;1576}15771578private native Class<?> getDeclaringClass0();157915801581/**1582* Returns the immediately enclosing class of the underlying1583* class. If the underlying class is a top level class this1584* method returns {@code null}.1585* @return the immediately enclosing class of the underlying class1586* @throws SecurityException1587* If a security manager, <i>s</i>, is present and the caller's1588* class loader is not the same as or an ancestor of the class1589* loader for the enclosing class and invocation of {@link1590* SecurityManager#checkPackageAccess s.checkPackageAccess()}1591* denies access to the package of the enclosing class1592* @since 1.51593*/1594@CallerSensitive1595public Class<?> getEnclosingClass() throws SecurityException {1596// There are five kinds of classes (or interfaces):1597// a) Top level classes1598// b) Nested classes (static member classes)1599// c) Inner classes (non-static member classes)1600// d) Local classes (named classes declared within a method)1601// e) Anonymous classes160216031604// JVM Spec 4.7.7: A class must have an EnclosingMethod1605// attribute if and only if it is a local class or an1606// anonymous class.1607EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();1608Class<?> enclosingCandidate;16091610if (enclosingInfo == null) {1611// This is a top level or a nested class or an inner class (a, b, or c)1612enclosingCandidate = getDeclaringClass0();1613} else {1614Class<?> enclosingClass = enclosingInfo.getEnclosingClass();1615// This is a local class or an anonymous class (d or e)1616if (enclosingClass == this || enclosingClass == null)1617throw new InternalError("Malformed enclosing method information");1618else1619enclosingCandidate = enclosingClass;1620}16211622if (enclosingCandidate != null) {1623@SuppressWarnings("removal")1624SecurityManager sm = System.getSecurityManager();1625if (sm != null) {1626enclosingCandidate.checkPackageAccess(sm,1627ClassLoader.getClassLoader(Reflection.getCallerClass()), true);1628}1629}1630return enclosingCandidate;1631}16321633/**1634* Returns the simple name of the underlying class as given in the1635* source code. An empty string is returned if the underlying class is1636* {@linkplain #isAnonymousClass() anonymous}.1637* A {@linkplain #isSynthetic() synthetic class}, one not present1638* in source code, can have a non-empty name including special1639* characters, such as "{@code $}".1640*1641* <p>The simple name of an {@linkplain #isArray() array class} is the simple name of the1642* component type with "[]" appended. In particular the simple1643* name of an array class whose component type is anonymous is "[]".1644*1645* @return the simple name of the underlying class1646* @since 1.51647*/1648public String getSimpleName() {1649ReflectionData<T> rd = reflectionData();1650String simpleName = rd.simpleName;1651if (simpleName == null) {1652rd.simpleName = simpleName = getSimpleName0();1653}1654return simpleName;1655}16561657private String getSimpleName0() {1658if (isArray()) {1659return getComponentType().getSimpleName() + "[]";1660}1661String simpleName = getSimpleBinaryName();1662if (simpleName == null) { // top level class1663simpleName = getName();1664simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name1665}1666return simpleName;1667}16681669/**1670* Return an informative string for the name of this class or interface.1671*1672* @return an informative string for the name of this class or interface1673* @since 1.81674*/1675public String getTypeName() {1676if (isArray()) {1677try {1678Class<?> cl = this;1679int dimensions = 0;1680do {1681dimensions++;1682cl = cl.getComponentType();1683} while (cl.isArray());1684return cl.getName() + "[]".repeat(dimensions);1685} catch (Throwable e) { /*FALLTHRU*/ }1686}1687return getName();1688}16891690/**1691* Returns the canonical name of the underlying class as1692* defined by <cite>The Java Language Specification</cite>.1693* Returns {@code null} if the underlying class does not have a canonical1694* name. Classes without canonical names include:1695* <ul>1696* <li>a {@linkplain #isLocalClass() local class}1697* <li>a {@linkplain #isAnonymousClass() anonymous class}1698* <li>a {@linkplain #isHidden() hidden class}1699* <li>an array whose component type does not have a canonical name</li>1700* </ul>1701*1702* @return the canonical name of the underlying class if it exists, and1703* {@code null} otherwise.1704* @since 1.51705*/1706public String getCanonicalName() {1707ReflectionData<T> rd = reflectionData();1708String canonicalName = rd.canonicalName;1709if (canonicalName == null) {1710rd.canonicalName = canonicalName = getCanonicalName0();1711}1712return canonicalName == ReflectionData.NULL_SENTINEL? null : canonicalName;1713}17141715private String getCanonicalName0() {1716if (isArray()) {1717String canonicalName = getComponentType().getCanonicalName();1718if (canonicalName != null)1719return canonicalName + "[]";1720else1721return ReflectionData.NULL_SENTINEL;1722}1723if (isHidden() || isLocalOrAnonymousClass())1724return ReflectionData.NULL_SENTINEL;1725Class<?> enclosingClass = getEnclosingClass();1726if (enclosingClass == null) { // top level class1727return getName();1728} else {1729String enclosingName = enclosingClass.getCanonicalName();1730if (enclosingName == null)1731return ReflectionData.NULL_SENTINEL;1732String simpleName = getSimpleName();1733return new StringBuilder(enclosingName.length() + simpleName.length() + 1)1734.append(enclosingName)1735.append('.')1736.append(simpleName)1737.toString();1738}1739}17401741/**1742* Returns {@code true} if and only if the underlying class1743* is an anonymous class.1744*1745* @apiNote1746* An anonymous class is not a {@linkplain #isHidden() hidden class}.1747*1748* @return {@code true} if and only if this class is an anonymous class.1749* @since 1.51750* @jls 15.9.5 Anonymous Class Declarations1751*/1752public boolean isAnonymousClass() {1753return !isArray() && isLocalOrAnonymousClass() &&1754getSimpleBinaryName0() == null;1755}17561757/**1758* Returns {@code true} if and only if the underlying class1759* is a local class.1760*1761* @return {@code true} if and only if this class is a local class.1762* @since 1.51763* @jls 14.3 Local Class Declarations1764*/1765public boolean isLocalClass() {1766return isLocalOrAnonymousClass() &&1767(isArray() || getSimpleBinaryName0() != null);1768}17691770/**1771* Returns {@code true} if and only if the underlying class1772* is a member class.1773*1774* @return {@code true} if and only if this class is a member class.1775* @since 1.51776* @jls 8.5 Member Type Declarations1777*/1778public boolean isMemberClass() {1779return !isLocalOrAnonymousClass() && getDeclaringClass0() != null;1780}17811782/**1783* Returns the "simple binary name" of the underlying class, i.e.,1784* the binary name without the leading enclosing class name.1785* Returns {@code null} if the underlying class is a top level1786* class.1787*/1788private String getSimpleBinaryName() {1789if (isTopLevelClass())1790return null;1791String name = getSimpleBinaryName0();1792if (name == null) // anonymous class1793return "";1794return name;1795}17961797private native String getSimpleBinaryName0();17981799/**1800* Returns {@code true} if this is a top level class. Returns {@code false}1801* otherwise.1802*/1803private boolean isTopLevelClass() {1804return !isLocalOrAnonymousClass() && getDeclaringClass0() == null;1805}18061807/**1808* Returns {@code true} if this is a local class or an anonymous1809* class. Returns {@code false} otherwise.1810*/1811private boolean isLocalOrAnonymousClass() {1812// JVM Spec 4.7.7: A class must have an EnclosingMethod1813// attribute if and only if it is a local class or an1814// anonymous class.1815return hasEnclosingMethodInfo();1816}18171818private boolean hasEnclosingMethodInfo() {1819Object[] enclosingInfo = getEnclosingMethod0();1820if (enclosingInfo != null) {1821EnclosingMethodInfo.validate(enclosingInfo);1822return true;1823}1824return false;1825}18261827/**1828* Returns an array containing {@code Class} objects representing all1829* the public classes and interfaces that are members of the class1830* represented by this {@code Class} object. This includes public1831* class and interface members inherited from superclasses and public class1832* and interface members declared by the class. This method returns an1833* array of length 0 if this {@code Class} object has no public member1834* classes or interfaces. This method also returns an array of length 0 if1835* this {@code Class} object represents a primitive type, an array1836* class, or void.1837*1838* @return the array of {@code Class} objects representing the public1839* members of this class1840* @throws SecurityException1841* If a security manager, <i>s</i>, is present and1842* the caller's class loader is not the same as or an1843* ancestor of the class loader for the current class and1844* invocation of {@link SecurityManager#checkPackageAccess1845* s.checkPackageAccess()} denies access to the package1846* of this class.1847*1848* @since 1.11849*/1850@SuppressWarnings("removal")1851@CallerSensitive1852public Class<?>[] getClasses() {1853SecurityManager sm = System.getSecurityManager();1854if (sm != null) {1855checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false);1856}18571858// Privileged so this implementation can look at DECLARED classes,1859// something the caller might not have privilege to do. The code here1860// is allowed to look at DECLARED classes because (1) it does not hand1861// out anything other than public members and (2) public member access1862// has already been ok'd by the SecurityManager.18631864return java.security.AccessController.doPrivileged(1865new java.security.PrivilegedAction<>() {1866public Class<?>[] run() {1867List<Class<?>> list = new ArrayList<>();1868Class<?> currentClass = Class.this;1869while (currentClass != null) {1870for (Class<?> m : currentClass.getDeclaredClasses()) {1871if (Modifier.isPublic(m.getModifiers())) {1872list.add(m);1873}1874}1875currentClass = currentClass.getSuperclass();1876}1877return list.toArray(new Class<?>[0]);1878}1879});1880}188118821883/**1884* Returns an array containing {@code Field} objects reflecting all1885* the accessible public fields of the class or interface represented by1886* this {@code Class} object.1887*1888* <p> If this {@code Class} object represents a class or interface with1889* no accessible public fields, then this method returns an array of length1890* 0.1891*1892* <p> If this {@code Class} object represents a class, then this method1893* returns the public fields of the class and of all its superclasses and1894* superinterfaces.1895*1896* <p> If this {@code Class} object represents an interface, then this1897* method returns the fields of the interface and of all its1898* superinterfaces.1899*1900* <p> If this {@code Class} object represents an array type, a primitive1901* type, or void, then this method returns an array of length 0.1902*1903* <p> The elements in the returned array are not sorted and are not in any1904* particular order.1905*1906* @return the array of {@code Field} objects representing the1907* public fields1908* @throws SecurityException1909* If a security manager, <i>s</i>, is present and1910* the caller's class loader is not the same as or an1911* ancestor of the class loader for the current class and1912* invocation of {@link SecurityManager#checkPackageAccess1913* s.checkPackageAccess()} denies access to the package1914* of this class.1915*1916* @since 1.11917* @jls 8.2 Class Members1918* @jls 8.3 Field Declarations1919*/1920@CallerSensitive1921public Field[] getFields() throws SecurityException {1922@SuppressWarnings("removal")1923SecurityManager sm = System.getSecurityManager();1924if (sm != null) {1925checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);1926}1927return copyFields(privateGetPublicFields());1928}192919301931/**1932* Returns an array containing {@code Method} objects reflecting all the1933* public methods of the class or interface represented by this {@code1934* Class} object, including those declared by the class or interface and1935* those inherited from superclasses and superinterfaces.1936*1937* <p> If this {@code Class} object represents an array type, then the1938* returned array has a {@code Method} object for each of the public1939* methods inherited by the array type from {@code Object}. It does not1940* contain a {@code Method} object for {@code clone()}.1941*1942* <p> If this {@code Class} object represents an interface then the1943* returned array does not contain any implicitly declared methods from1944* {@code Object}. Therefore, if no methods are explicitly declared in1945* this interface or any of its superinterfaces then the returned array1946* has length 0. (Note that a {@code Class} object which represents a class1947* always has public methods, inherited from {@code Object}.)1948*1949* <p> The returned array never contains methods with names "{@code <init>}"1950* or "{@code <clinit>}".1951*1952* <p> The elements in the returned array are not sorted and are not in any1953* particular order.1954*1955* <p> Generally, the result is computed as with the following 4 step algorithm.1956* Let C be the class or interface represented by this {@code Class} object:1957* <ol>1958* <li> A union of methods is composed of:1959* <ol type="a">1960* <li> C's declared public instance and static methods as returned by1961* {@link #getDeclaredMethods()} and filtered to include only public1962* methods.</li>1963* <li> If C is a class other than {@code Object}, then include the result1964* of invoking this algorithm recursively on the superclass of C.</li>1965* <li> Include the results of invoking this algorithm recursively on all1966* direct superinterfaces of C, but include only instance methods.</li>1967* </ol></li>1968* <li> Union from step 1 is partitioned into subsets of methods with same1969* signature (name, parameter types) and return type.</li>1970* <li> Within each such subset only the most specific methods are selected.1971* Let method M be a method from a set of methods with same signature1972* and return type. M is most specific if there is no such method1973* N != M from the same set, such that N is more specific than M.1974* N is more specific than M if:1975* <ol type="a">1976* <li> N is declared by a class and M is declared by an interface; or</li>1977* <li> N and M are both declared by classes or both by interfaces and1978* N's declaring type is the same as or a subtype of M's declaring type1979* (clearly, if M's and N's declaring types are the same type, then1980* M and N are the same method).</li>1981* </ol></li>1982* <li> The result of this algorithm is the union of all selected methods from1983* step 3.</li>1984* </ol>1985*1986* @apiNote There may be more than one method with a particular name1987* and parameter types in a class because while the Java language forbids a1988* class to declare multiple methods with the same signature but different1989* return types, the Java virtual machine does not. This1990* increased flexibility in the virtual machine can be used to1991* implement various language features. For example, covariant1992* returns can be implemented with {@linkplain1993* java.lang.reflect.Method#isBridge bridge methods}; the bridge1994* method and the overriding method would have the same1995* signature but different return types.1996*1997* @return the array of {@code Method} objects representing the1998* public methods of this class1999* @throws SecurityException2000* If a security manager, <i>s</i>, is present and2001* the caller's class loader is not the same as or an2002* ancestor of the class loader for the current class and2003* invocation of {@link SecurityManager#checkPackageAccess2004* s.checkPackageAccess()} denies access to the package2005* of this class.2006*2007* @jls 8.2 Class Members2008* @jls 8.4 Method Declarations2009* @since 1.12010*/2011@CallerSensitive2012public Method[] getMethods() throws SecurityException {2013@SuppressWarnings("removal")2014SecurityManager sm = System.getSecurityManager();2015if (sm != null) {2016checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);2017}2018return copyMethods(privateGetPublicMethods());2019}202020212022/**2023* Returns an array containing {@code Constructor} objects reflecting2024* all the public constructors of the class represented by this2025* {@code Class} object. An array of length 0 is returned if the2026* class has no public constructors, or if the class is an array class, or2027* if the class reflects a primitive type or void.2028*2029* @apiNote2030* While this method returns an array of {@code2031* Constructor<T>} objects (that is an array of constructors from2032* this class), the return type of this method is {@code2033* Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as2034* might be expected. This less informative return type is2035* necessary since after being returned from this method, the2036* array could be modified to hold {@code Constructor} objects for2037* different classes, which would violate the type guarantees of2038* {@code Constructor<T>[]}.2039*2040* @return the array of {@code Constructor} objects representing the2041* public constructors of this class2042* @throws SecurityException2043* If a security manager, <i>s</i>, is present and2044* the caller's class loader is not the same as or an2045* ancestor of the class loader for the current class and2046* invocation of {@link SecurityManager#checkPackageAccess2047* s.checkPackageAccess()} denies access to the package2048* of this class.2049*2050* @since 1.12051*/2052@CallerSensitive2053public Constructor<?>[] getConstructors() throws SecurityException {2054@SuppressWarnings("removal")2055SecurityManager sm = System.getSecurityManager();2056if (sm != null) {2057checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);2058}2059return copyConstructors(privateGetDeclaredConstructors(true));2060}206120622063/**2064* Returns a {@code Field} object that reflects the specified public member2065* field of the class or interface represented by this {@code Class}2066* object. The {@code name} parameter is a {@code String} specifying the2067* simple name of the desired field.2068*2069* <p> The field to be reflected is determined by the algorithm that2070* follows. Let C be the class or interface represented by this {@code Class} object:2071*2072* <OL>2073* <LI> If C declares a public field with the name specified, that is the2074* field to be reflected.</LI>2075* <LI> If no field was found in step 1 above, this algorithm is applied2076* recursively to each direct superinterface of C. The direct2077* superinterfaces are searched in the order they were declared.</LI>2078* <LI> If no field was found in steps 1 and 2 above, and C has a2079* superclass S, then this algorithm is invoked recursively upon S.2080* If C has no superclass, then a {@code NoSuchFieldException}2081* is thrown.</LI>2082* </OL>2083*2084* <p> If this {@code Class} object represents an array type, then this2085* method does not find the {@code length} field of the array type.2086*2087* @param name the field name2088* @return the {@code Field} object of this class specified by2089* {@code name}2090* @throws NoSuchFieldException if a field with the specified name is2091* not found.2092* @throws NullPointerException if {@code name} is {@code null}2093* @throws SecurityException2094* If a security manager, <i>s</i>, is present and2095* the caller's class loader is not the same as or an2096* ancestor of the class loader for the current class and2097* invocation of {@link SecurityManager#checkPackageAccess2098* s.checkPackageAccess()} denies access to the package2099* of this class.2100*2101* @since 1.12102* @jls 8.2 Class Members2103* @jls 8.3 Field Declarations2104*/2105@CallerSensitive2106public Field getField(String name)2107throws NoSuchFieldException, SecurityException {2108Objects.requireNonNull(name);2109@SuppressWarnings("removal")2110SecurityManager sm = System.getSecurityManager();2111if (sm != null) {2112checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);2113}2114Field field = getField0(name);2115if (field == null) {2116throw new NoSuchFieldException(name);2117}2118return getReflectionFactory().copyField(field);2119}212021212122/**2123* Returns a {@code Method} object that reflects the specified public2124* member method of the class or interface represented by this2125* {@code Class} object. The {@code name} parameter is a2126* {@code String} specifying the simple name of the desired method. The2127* {@code parameterTypes} parameter is an array of {@code Class}2128* objects that identify the method's formal parameter types, in declared2129* order. If {@code parameterTypes} is {@code null}, it is2130* treated as if it were an empty array.2131*2132* <p> If this {@code Class} object represents an array type, then this2133* method finds any public method inherited by the array type from2134* {@code Object} except method {@code clone()}.2135*2136* <p> If this {@code Class} object represents an interface then this2137* method does not find any implicitly declared method from2138* {@code Object}. Therefore, if no methods are explicitly declared in2139* this interface or any of its superinterfaces, then this method does not2140* find any method.2141*2142* <p> This method does not find any method with name "{@code <init>}" or2143* "{@code <clinit>}".2144*2145* <p> Generally, the method to be reflected is determined by the 4 step2146* algorithm that follows.2147* Let C be the class or interface represented by this {@code Class} object:2148* <ol>2149* <li> A union of methods is composed of:2150* <ol type="a">2151* <li> C's declared public instance and static methods as returned by2152* {@link #getDeclaredMethods()} and filtered to include only public2153* methods that match given {@code name} and {@code parameterTypes}</li>2154* <li> If C is a class other than {@code Object}, then include the result2155* of invoking this algorithm recursively on the superclass of C.</li>2156* <li> Include the results of invoking this algorithm recursively on all2157* direct superinterfaces of C, but include only instance methods.</li>2158* </ol></li>2159* <li> This union is partitioned into subsets of methods with same2160* return type (the selection of methods from step 1 also guarantees that2161* they have the same method name and parameter types).</li>2162* <li> Within each such subset only the most specific methods are selected.2163* Let method M be a method from a set of methods with same VM2164* signature (return type, name, parameter types).2165* M is most specific if there is no such method N != M from the same2166* set, such that N is more specific than M. N is more specific than M2167* if:2168* <ol type="a">2169* <li> N is declared by a class and M is declared by an interface; or</li>2170* <li> N and M are both declared by classes or both by interfaces and2171* N's declaring type is the same as or a subtype of M's declaring type2172* (clearly, if M's and N's declaring types are the same type, then2173* M and N are the same method).</li>2174* </ol></li>2175* <li> The result of this algorithm is chosen arbitrarily from the methods2176* with most specific return type among all selected methods from step 3.2177* Let R be a return type of a method M from the set of all selected methods2178* from step 3. M is a method with most specific return type if there is2179* no such method N != M from the same set, having return type S != R,2180* such that S is a subtype of R as determined by2181* R.class.{@link #isAssignableFrom}(S.class).2182* </ol>2183*2184* @apiNote There may be more than one method with matching name and2185* parameter types in a class because while the Java language forbids a2186* class to declare multiple methods with the same signature but different2187* return types, the Java virtual machine does not. This2188* increased flexibility in the virtual machine can be used to2189* implement various language features. For example, covariant2190* returns can be implemented with {@linkplain2191* java.lang.reflect.Method#isBridge bridge methods}; the bridge2192* method and the overriding method would have the same2193* signature but different return types. This method would return the2194* overriding method as it would have a more specific return type.2195*2196* @param name the name of the method2197* @param parameterTypes the list of parameters2198* @return the {@code Method} object that matches the specified2199* {@code name} and {@code parameterTypes}2200* @throws NoSuchMethodException if a matching method is not found2201* or if the name is "<init>"or "<clinit>".2202* @throws NullPointerException if {@code name} is {@code null}2203* @throws SecurityException2204* If a security manager, <i>s</i>, is present and2205* the caller's class loader is not the same as or an2206* ancestor of the class loader for the current class and2207* invocation of {@link SecurityManager#checkPackageAccess2208* s.checkPackageAccess()} denies access to the package2209* of this class.2210*2211* @jls 8.2 Class Members2212* @jls 8.4 Method Declarations2213* @since 1.12214*/2215@CallerSensitive2216public Method getMethod(String name, Class<?>... parameterTypes)2217throws NoSuchMethodException, SecurityException {2218Objects.requireNonNull(name);2219@SuppressWarnings("removal")2220SecurityManager sm = System.getSecurityManager();2221if (sm != null) {2222checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);2223}2224Method method = getMethod0(name, parameterTypes);2225if (method == null) {2226throw new NoSuchMethodException(methodToString(name, parameterTypes));2227}2228return getReflectionFactory().copyMethod(method);2229}22302231/**2232* Returns a {@code Constructor} object that reflects the specified2233* public constructor of the class represented by this {@code Class}2234* object. The {@code parameterTypes} parameter is an array of2235* {@code Class} objects that identify the constructor's formal2236* parameter types, in declared order.2237*2238* If this {@code Class} object represents an inner class2239* declared in a non-static context, the formal parameter types2240* include the explicit enclosing instance as the first parameter.2241*2242* <p> The constructor to reflect is the public constructor of the class2243* represented by this {@code Class} object whose formal parameter2244* types match those specified by {@code parameterTypes}.2245*2246* @param parameterTypes the parameter array2247* @return the {@code Constructor} object of the public constructor that2248* matches the specified {@code parameterTypes}2249* @throws NoSuchMethodException if a matching method is not found.2250* @throws SecurityException2251* If a security manager, <i>s</i>, is present and2252* the caller's class loader is not the same as or an2253* ancestor of the class loader for the current class and2254* invocation of {@link SecurityManager#checkPackageAccess2255* s.checkPackageAccess()} denies access to the package2256* of this class.2257*2258* @since 1.12259*/2260@CallerSensitive2261public Constructor<T> getConstructor(Class<?>... parameterTypes)2262throws NoSuchMethodException, SecurityException2263{2264@SuppressWarnings("removal")2265SecurityManager sm = System.getSecurityManager();2266if (sm != null) {2267checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true);2268}2269return getReflectionFactory().copyConstructor(2270getConstructor0(parameterTypes, Member.PUBLIC));2271}227222732274/**2275* Returns an array of {@code Class} objects reflecting all the2276* classes and interfaces declared as members of the class represented by2277* this {@code Class} object. This includes public, protected, default2278* (package) access, and private classes and interfaces declared by the2279* class, but excludes inherited classes and interfaces. This method2280* returns an array of length 0 if the class declares no classes or2281* interfaces as members, or if this {@code Class} object represents a2282* primitive type, an array class, or void.2283*2284* @return the array of {@code Class} objects representing all the2285* declared members of this class2286* @throws SecurityException2287* If a security manager, <i>s</i>, is present and any of the2288* following conditions is met:2289*2290* <ul>2291*2292* <li> the caller's class loader is not the same as the2293* class loader of this class and invocation of2294* {@link SecurityManager#checkPermission2295* s.checkPermission} method with2296* {@code RuntimePermission("accessDeclaredMembers")}2297* denies access to the declared classes within this class2298*2299* <li> the caller's class loader is not the same as or an2300* ancestor of the class loader for the current class and2301* invocation of {@link SecurityManager#checkPackageAccess2302* s.checkPackageAccess()} denies access to the package2303* of this class2304*2305* </ul>2306*2307* @since 1.12308* @jls 8.5 Member Type Declarations2309*/2310@CallerSensitive2311public Class<?>[] getDeclaredClasses() throws SecurityException {2312@SuppressWarnings("removal")2313SecurityManager sm = System.getSecurityManager();2314if (sm != null) {2315checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), false);2316}2317return getDeclaredClasses0();2318}231923202321/**2322* Returns an array of {@code Field} objects reflecting all the fields2323* declared by the class or interface represented by this2324* {@code Class} object. This includes public, protected, default2325* (package) access, and private fields, but excludes inherited fields.2326*2327* <p> If this {@code Class} object represents a class or interface with no2328* declared fields, then this method returns an array of length 0.2329*2330* <p> If this {@code Class} object represents an array type, a primitive2331* type, or void, then this method returns an array of length 0.2332*2333* <p> The elements in the returned array are not sorted and are not in any2334* particular order.2335*2336* @return the array of {@code Field} objects representing all the2337* declared fields of this class2338* @throws SecurityException2339* If a security manager, <i>s</i>, is present and any of the2340* following conditions is met:2341*2342* <ul>2343*2344* <li> the caller's class loader is not the same as the2345* class loader of this class and invocation of2346* {@link SecurityManager#checkPermission2347* s.checkPermission} method with2348* {@code RuntimePermission("accessDeclaredMembers")}2349* denies access to the declared fields within this class2350*2351* <li> the caller's class loader is not the same as or an2352* ancestor of the class loader for the current class and2353* invocation of {@link SecurityManager#checkPackageAccess2354* s.checkPackageAccess()} denies access to the package2355* of this class2356*2357* </ul>2358*2359* @since 1.12360* @jls 8.2 Class Members2361* @jls 8.3 Field Declarations2362*/2363@CallerSensitive2364public Field[] getDeclaredFields() throws SecurityException {2365@SuppressWarnings("removal")2366SecurityManager sm = System.getSecurityManager();2367if (sm != null) {2368checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);2369}2370return copyFields(privateGetDeclaredFields(false));2371}23722373/**2374* Returns an array of {@code RecordComponent} objects representing all the2375* record components of this record class, or {@code null} if this class is2376* not a record class.2377*2378* <p> The components are returned in the same order that they are declared2379* in the record header. The array is empty if this record class has no2380* components. If the class is not a record class, that is {@link2381* #isRecord()} returns {@code false}, then this method returns {@code null}.2382* Conversely, if {@link #isRecord()} returns {@code true}, then this method2383* returns a non-null value.2384*2385* @apiNote2386* <p> The following method can be used to find the record canonical constructor:2387*2388* <pre>{@code2389* static <T extends Record> Constructor<T> getCanonicalConstructor(Class<T> cls)2390* throws NoSuchMethodException {2391* Class<?>[] paramTypes =2392* Arrays.stream(cls.getRecordComponents())2393* .map(RecordComponent::getType)2394* .toArray(Class<?>[]::new);2395* return cls.getDeclaredConstructor(paramTypes);2396* }}</pre>2397*2398* @return An array of {@code RecordComponent} objects representing all the2399* record components of this record class, or {@code null} if this2400* class is not a record class2401* @throws SecurityException2402* If a security manager, <i>s</i>, is present and any of the2403* following conditions is met:2404*2405* <ul>2406*2407* <li> the caller's class loader is not the same as the2408* class loader of this class and invocation of2409* {@link SecurityManager#checkPermission2410* s.checkPermission} method with2411* {@code RuntimePermission("accessDeclaredMembers")}2412* denies access to the declared methods within this class2413*2414* <li> the caller's class loader is not the same as or an2415* ancestor of the class loader for the current class and2416* invocation of {@link SecurityManager#checkPackageAccess2417* s.checkPackageAccess()} denies access to the package2418* of this class2419*2420* </ul>2421*2422* @jls 8.10 Record Classes2423* @since 162424*/2425@CallerSensitive2426public RecordComponent[] getRecordComponents() {2427@SuppressWarnings("removal")2428SecurityManager sm = System.getSecurityManager();2429if (sm != null) {2430checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);2431}2432if (!isRecord()) {2433return null;2434}2435return getRecordComponents0();2436}24372438/**2439* Returns an array containing {@code Method} objects reflecting all the2440* declared methods of the class or interface represented by this {@code2441* Class} object, including public, protected, default (package)2442* access, and private methods, but excluding inherited methods.2443* The declared methods may include methods <em>not</em> in the2444* source of the class or interface, including {@linkplain2445* Method#isBridge bridge methods} and other {@linkplain2446* Executable#isSynthetic synthetic} methods added by compilers.2447*2448* <p> If this {@code Class} object represents a class or interface that2449* has multiple declared methods with the same name and parameter types,2450* but different return types, then the returned array has a {@code Method}2451* object for each such method.2452*2453* <p> If this {@code Class} object represents a class or interface that2454* has a class initialization method {@code <clinit>}, then the returned2455* array does <em>not</em> have a corresponding {@code Method} object.2456*2457* <p> If this {@code Class} object represents a class or interface with no2458* declared methods, then the returned array has length 0.2459*2460* <p> If this {@code Class} object represents an array type, a primitive2461* type, or void, then the returned array has length 0.2462*2463* <p> The elements in the returned array are not sorted and are not in any2464* particular order.2465*2466* @return the array of {@code Method} objects representing all the2467* declared methods of this class2468* @throws SecurityException2469* If a security manager, <i>s</i>, is present and any of the2470* following conditions is met:2471*2472* <ul>2473*2474* <li> the caller's class loader is not the same as the2475* class loader of this class and invocation of2476* {@link SecurityManager#checkPermission2477* s.checkPermission} method with2478* {@code RuntimePermission("accessDeclaredMembers")}2479* denies access to the declared methods within this class2480*2481* <li> the caller's class loader is not the same as or an2482* ancestor of the class loader for the current class and2483* invocation of {@link SecurityManager#checkPackageAccess2484* s.checkPackageAccess()} denies access to the package2485* of this class2486*2487* </ul>2488*2489* @jls 8.2 Class Members2490* @jls 8.4 Method Declarations2491* @see <a2492* href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java2493* programming language and JVM modeling in core reflection</a>2494* @since 1.12495*/2496@CallerSensitive2497public Method[] getDeclaredMethods() throws SecurityException {2498@SuppressWarnings("removal")2499SecurityManager sm = System.getSecurityManager();2500if (sm != null) {2501checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);2502}2503return copyMethods(privateGetDeclaredMethods(false));2504}250525062507/**2508* Returns an array of {@code Constructor} objects reflecting all the2509* constructors declared by the class represented by this2510* {@code Class} object. These are public, protected, default2511* (package) access, and private constructors. The elements in the array2512* returned are not sorted and are not in any particular order. If the2513* class has a default constructor, it is included in the returned array.2514* This method returns an array of length 0 if this {@code Class}2515* object represents an interface, a primitive type, an array class, or2516* void.2517*2518* <p> See <cite>The Java Language Specification</cite>,2519* section {@jls 8.2}.2520*2521* @return the array of {@code Constructor} objects representing all the2522* declared constructors of this class2523* @throws SecurityException2524* If a security manager, <i>s</i>, is present and any of the2525* following conditions is met:2526*2527* <ul>2528*2529* <li> the caller's class loader is not the same as the2530* class loader of this class and invocation of2531* {@link SecurityManager#checkPermission2532* s.checkPermission} method with2533* {@code RuntimePermission("accessDeclaredMembers")}2534* denies access to the declared constructors within this class2535*2536* <li> the caller's class loader is not the same as or an2537* ancestor of the class loader for the current class and2538* invocation of {@link SecurityManager#checkPackageAccess2539* s.checkPackageAccess()} denies access to the package2540* of this class2541*2542* </ul>2543*2544* @since 1.12545* @jls 8.8 Constructor Declarations2546*/2547@CallerSensitive2548public Constructor<?>[] getDeclaredConstructors() throws SecurityException {2549@SuppressWarnings("removal")2550SecurityManager sm = System.getSecurityManager();2551if (sm != null) {2552checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);2553}2554return copyConstructors(privateGetDeclaredConstructors(false));2555}255625572558/**2559* Returns a {@code Field} object that reflects the specified declared2560* field of the class or interface represented by this {@code Class}2561* object. The {@code name} parameter is a {@code String} that specifies2562* the simple name of the desired field.2563*2564* <p> If this {@code Class} object represents an array type, then this2565* method does not find the {@code length} field of the array type.2566*2567* @param name the name of the field2568* @return the {@code Field} object for the specified field in this2569* class2570* @throws NoSuchFieldException if a field with the specified name is2571* not found.2572* @throws NullPointerException if {@code name} is {@code null}2573* @throws SecurityException2574* If a security manager, <i>s</i>, is present and any of the2575* following conditions is met:2576*2577* <ul>2578*2579* <li> the caller's class loader is not the same as the2580* class loader of this class and invocation of2581* {@link SecurityManager#checkPermission2582* s.checkPermission} method with2583* {@code RuntimePermission("accessDeclaredMembers")}2584* denies access to the declared field2585*2586* <li> the caller's class loader is not the same as or an2587* ancestor of the class loader for the current class and2588* invocation of {@link SecurityManager#checkPackageAccess2589* s.checkPackageAccess()} denies access to the package2590* of this class2591*2592* </ul>2593*2594* @since 1.12595* @jls 8.2 Class Members2596* @jls 8.3 Field Declarations2597*/2598@CallerSensitive2599public Field getDeclaredField(String name)2600throws NoSuchFieldException, SecurityException {2601Objects.requireNonNull(name);2602@SuppressWarnings("removal")2603SecurityManager sm = System.getSecurityManager();2604if (sm != null) {2605checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);2606}2607Field field = searchFields(privateGetDeclaredFields(false), name);2608if (field == null) {2609throw new NoSuchFieldException(name);2610}2611return getReflectionFactory().copyField(field);2612}261326142615/**2616* Returns a {@code Method} object that reflects the specified2617* declared method of the class or interface represented by this2618* {@code Class} object. The {@code name} parameter is a2619* {@code String} that specifies the simple name of the desired2620* method, and the {@code parameterTypes} parameter is an array of2621* {@code Class} objects that identify the method's formal parameter2622* types, in declared order. If more than one method with the same2623* parameter types is declared in a class, and one of these methods has a2624* return type that is more specific than any of the others, that method is2625* returned; otherwise one of the methods is chosen arbitrarily. If the2626* name is "<init>"or "<clinit>" a {@code NoSuchMethodException}2627* is raised.2628*2629* <p> If this {@code Class} object represents an array type, then this2630* method does not find the {@code clone()} method.2631*2632* @param name the name of the method2633* @param parameterTypes the parameter array2634* @return the {@code Method} object for the method of this class2635* matching the specified name and parameters2636* @throws NoSuchMethodException if a matching method is not found.2637* @throws NullPointerException if {@code name} is {@code null}2638* @throws SecurityException2639* If a security manager, <i>s</i>, is present and any of the2640* following conditions is met:2641*2642* <ul>2643*2644* <li> the caller's class loader is not the same as the2645* class loader of this class and invocation of2646* {@link SecurityManager#checkPermission2647* s.checkPermission} method with2648* {@code RuntimePermission("accessDeclaredMembers")}2649* denies access to the declared method2650*2651* <li> the caller's class loader is not the same as or an2652* ancestor of the class loader for the current class and2653* invocation of {@link SecurityManager#checkPackageAccess2654* s.checkPackageAccess()} denies access to the package2655* of this class2656*2657* </ul>2658*2659* @jls 8.2 Class Members2660* @jls 8.4 Method Declarations2661* @since 1.12662*/2663@CallerSensitive2664public Method getDeclaredMethod(String name, Class<?>... parameterTypes)2665throws NoSuchMethodException, SecurityException {2666Objects.requireNonNull(name);2667@SuppressWarnings("removal")2668SecurityManager sm = System.getSecurityManager();2669if (sm != null) {2670checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);2671}2672Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);2673if (method == null) {2674throw new NoSuchMethodException(methodToString(name, parameterTypes));2675}2676return getReflectionFactory().copyMethod(method);2677}26782679/**2680* Returns the list of {@code Method} objects for the declared public2681* methods of this class or interface that have the specified method name2682* and parameter types.2683*2684* @param name the name of the method2685* @param parameterTypes the parameter array2686* @return the list of {@code Method} objects for the public methods of2687* this class matching the specified name and parameters2688*/2689List<Method> getDeclaredPublicMethods(String name, Class<?>... parameterTypes) {2690Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);2691ReflectionFactory factory = getReflectionFactory();2692List<Method> result = new ArrayList<>();2693for (Method method : methods) {2694if (method.getName().equals(name)2695&& Arrays.equals(2696factory.getExecutableSharedParameterTypes(method),2697parameterTypes)) {2698result.add(factory.copyMethod(method));2699}2700}2701return result;2702}27032704/**2705* Returns a {@code Constructor} object that reflects the specified2706* constructor of the class or interface represented by this2707* {@code Class} object. The {@code parameterTypes} parameter is2708* an array of {@code Class} objects that identify the constructor's2709* formal parameter types, in declared order.2710*2711* If this {@code Class} object represents an inner class2712* declared in a non-static context, the formal parameter types2713* include the explicit enclosing instance as the first parameter.2714*2715* @param parameterTypes the parameter array2716* @return The {@code Constructor} object for the constructor with the2717* specified parameter list2718* @throws NoSuchMethodException if a matching method is not found.2719* @throws SecurityException2720* If a security manager, <i>s</i>, is present and any of the2721* following conditions is met:2722*2723* <ul>2724*2725* <li> the caller's class loader is not the same as the2726* class loader of this class and invocation of2727* {@link SecurityManager#checkPermission2728* s.checkPermission} method with2729* {@code RuntimePermission("accessDeclaredMembers")}2730* denies access to the declared constructor2731*2732* <li> the caller's class loader is not the same as or an2733* ancestor of the class loader for the current class and2734* invocation of {@link SecurityManager#checkPackageAccess2735* s.checkPackageAccess()} denies access to the package2736* of this class2737*2738* </ul>2739*2740* @since 1.12741*/2742@CallerSensitive2743public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)2744throws NoSuchMethodException, SecurityException2745{2746@SuppressWarnings("removal")2747SecurityManager sm = System.getSecurityManager();2748if (sm != null) {2749checkMemberAccess(sm, Member.DECLARED, Reflection.getCallerClass(), true);2750}27512752return getReflectionFactory().copyConstructor(2753getConstructor0(parameterTypes, Member.DECLARED));2754}27552756/**2757* Finds a resource with a given name.2758*2759* <p> If this class is in a named {@link Module Module} then this method2760* will attempt to find the resource in the module. This is done by2761* delegating to the module's class loader {@link2762* ClassLoader#findResource(String,String) findResource(String,String)}2763* method, invoking it with the module name and the absolute name of the2764* resource. Resources in named modules are subject to the rules for2765* encapsulation specified in the {@code Module} {@link2766* Module#getResourceAsStream getResourceAsStream} method and so this2767* method returns {@code null} when the resource is a2768* non-"{@code .class}" resource in a package that is not open to the2769* caller's module.2770*2771* <p> Otherwise, if this class is not in a named module then the rules for2772* searching resources associated with a given class are implemented by the2773* defining {@linkplain ClassLoader class loader} of the class. This method2774* delegates to this {@code Class} object's class loader.2775* If this {@code Class} object was loaded by the bootstrap class loader,2776* the method delegates to {@link ClassLoader#getSystemResourceAsStream}.2777*2778* <p> Before delegation, an absolute resource name is constructed from the2779* given resource name using this algorithm:2780*2781* <ul>2782*2783* <li> If the {@code name} begins with a {@code '/'}2784* (<code>'\u002f'</code>), then the absolute name of the resource is the2785* portion of the {@code name} following the {@code '/'}.2786*2787* <li> Otherwise, the absolute name is of the following form:2788*2789* <blockquote>2790* {@code modified_package_name/name}2791* </blockquote>2792*2793* <p> Where the {@code modified_package_name} is the package name of this2794* object with {@code '/'} substituted for {@code '.'}2795* (<code>'\u002e'</code>).2796*2797* </ul>2798*2799* @param name name of the desired resource2800* @return A {@link java.io.InputStream} object; {@code null} if no2801* resource with this name is found, the resource is in a package2802* that is not {@linkplain Module#isOpen(String, Module) open} to at2803* least the caller module, or access to the resource is denied2804* by the security manager.2805* @throws NullPointerException If {@code name} is {@code null}2806*2807* @see Module#getResourceAsStream(String)2808* @since 1.12809* @revised 92810*/2811@CallerSensitive2812public InputStream getResourceAsStream(String name) {2813name = resolveName(name);28142815Module thisModule = getModule();2816if (thisModule.isNamed()) {2817// check if resource can be located by caller2818if (Resources.canEncapsulate(name)2819&& !isOpenToCaller(name, Reflection.getCallerClass())) {2820return null;2821}28222823// resource not encapsulated or in package open to caller2824String mn = thisModule.getName();2825ClassLoader cl = getClassLoader0();2826try {28272828// special-case built-in class loaders to avoid the2829// need for a URL connection2830if (cl == null) {2831return BootLoader.findResourceAsStream(mn, name);2832} else if (cl instanceof BuiltinClassLoader) {2833return ((BuiltinClassLoader) cl).findResourceAsStream(mn, name);2834} else {2835URL url = cl.findResource(mn, name);2836return (url != null) ? url.openStream() : null;2837}28382839} catch (IOException | SecurityException e) {2840return null;2841}2842}28432844// unnamed module2845ClassLoader cl = getClassLoader0();2846if (cl == null) {2847return ClassLoader.getSystemResourceAsStream(name);2848} else {2849return cl.getResourceAsStream(name);2850}2851}28522853/**2854* Finds a resource with a given name.2855*2856* <p> If this class is in a named {@link Module Module} then this method2857* will attempt to find the resource in the module. This is done by2858* delegating to the module's class loader {@link2859* ClassLoader#findResource(String,String) findResource(String,String)}2860* method, invoking it with the module name and the absolute name of the2861* resource. Resources in named modules are subject to the rules for2862* encapsulation specified in the {@code Module} {@link2863* Module#getResourceAsStream getResourceAsStream} method and so this2864* method returns {@code null} when the resource is a2865* non-"{@code .class}" resource in a package that is not open to the2866* caller's module.2867*2868* <p> Otherwise, if this class is not in a named module then the rules for2869* searching resources associated with a given class are implemented by the2870* defining {@linkplain ClassLoader class loader} of the class. This method2871* delegates to this {@code Class} object's class loader.2872* If this {@code Class} object was loaded by the bootstrap class loader,2873* the method delegates to {@link ClassLoader#getSystemResource}.2874*2875* <p> Before delegation, an absolute resource name is constructed from the2876* given resource name using this algorithm:2877*2878* <ul>2879*2880* <li> If the {@code name} begins with a {@code '/'}2881* (<code>'\u002f'</code>), then the absolute name of the resource is the2882* portion of the {@code name} following the {@code '/'}.2883*2884* <li> Otherwise, the absolute name is of the following form:2885*2886* <blockquote>2887* {@code modified_package_name/name}2888* </blockquote>2889*2890* <p> Where the {@code modified_package_name} is the package name of this2891* object with {@code '/'} substituted for {@code '.'}2892* (<code>'\u002e'</code>).2893*2894* </ul>2895*2896* @param name name of the desired resource2897* @return A {@link java.net.URL} object; {@code null} if no resource with2898* this name is found, the resource cannot be located by a URL, the2899* resource is in a package that is not2900* {@linkplain Module#isOpen(String, Module) open} to at least the caller2901* module, or access to the resource is denied by the security2902* manager.2903* @throws NullPointerException If {@code name} is {@code null}2904* @since 1.12905* @revised 92906*/2907@CallerSensitive2908public URL getResource(String name) {2909name = resolveName(name);29102911Module thisModule = getModule();2912if (thisModule.isNamed()) {2913// check if resource can be located by caller2914if (Resources.canEncapsulate(name)2915&& !isOpenToCaller(name, Reflection.getCallerClass())) {2916return null;2917}29182919// resource not encapsulated or in package open to caller2920String mn = thisModule.getName();2921ClassLoader cl = getClassLoader0();2922try {2923if (cl == null) {2924return BootLoader.findResource(mn, name);2925} else {2926return cl.findResource(mn, name);2927}2928} catch (IOException ioe) {2929return null;2930}2931}29322933// unnamed module2934ClassLoader cl = getClassLoader0();2935if (cl == null) {2936return ClassLoader.getSystemResource(name);2937} else {2938return cl.getResource(name);2939}2940}29412942/**2943* Returns true if a resource with the given name can be located by the2944* given caller. All resources in a module can be located by code in2945* the module. For other callers, then the package needs to be open to2946* the caller.2947*/2948private boolean isOpenToCaller(String name, Class<?> caller) {2949// assert getModule().isNamed();2950Module thisModule = getModule();2951Module callerModule = (caller != null) ? caller.getModule() : null;2952if (callerModule != thisModule) {2953String pn = Resources.toPackageName(name);2954if (thisModule.getDescriptor().packages().contains(pn)) {2955if (callerModule == null && !thisModule.isOpen(pn)) {2956// no caller, package not open2957return false;2958}2959if (!thisModule.isOpen(pn, callerModule)) {2960// package not open to caller2961return false;2962}2963}2964}2965return true;2966}296729682969/** protection domain returned when the internal domain is null */2970private static java.security.ProtectionDomain allPermDomain;29712972/**2973* Returns the {@code ProtectionDomain} of this class. If there is a2974* security manager installed, this method first calls the security2975* manager's {@code checkPermission} method with a2976* {@code RuntimePermission("getProtectionDomain")} permission to2977* ensure it's ok to get the2978* {@code ProtectionDomain}.2979*2980* @return the ProtectionDomain of this class2981*2982* @throws SecurityException2983* if a security manager exists and its2984* {@code checkPermission} method doesn't allow2985* getting the ProtectionDomain.2986*2987* @see java.security.ProtectionDomain2988* @see SecurityManager#checkPermission2989* @see java.lang.RuntimePermission2990* @since 1.22991*/2992public java.security.ProtectionDomain getProtectionDomain() {2993@SuppressWarnings("removal")2994SecurityManager sm = System.getSecurityManager();2995if (sm != null) {2996sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);2997}2998return protectionDomain();2999}30003001// package-private3002java.security.ProtectionDomain protectionDomain() {3003java.security.ProtectionDomain pd = getProtectionDomain0();3004if (pd == null) {3005if (allPermDomain == null) {3006java.security.Permissions perms =3007new java.security.Permissions();3008perms.add(SecurityConstants.ALL_PERMISSION);3009allPermDomain =3010new java.security.ProtectionDomain(null, perms);3011}3012pd = allPermDomain;3013}3014return pd;3015}30163017/**3018* Returns the ProtectionDomain of this class.3019*/3020private native java.security.ProtectionDomain getProtectionDomain0();30213022/*3023* Return the Virtual Machine's Class object for the named3024* primitive type.3025*/3026static native Class<?> getPrimitiveClass(String name);30273028/*3029* Check if client is allowed to access members. If access is denied,3030* throw a SecurityException.3031*3032* This method also enforces package access.3033*3034* <p> Default policy: allow all clients access with normal Java access3035* control.3036*3037* <p> NOTE: should only be called if a SecurityManager is installed3038*/3039private void checkMemberAccess(@SuppressWarnings("removal") SecurityManager sm, int which,3040Class<?> caller, boolean checkProxyInterfaces) {3041/* Default policy allows access to all {@link Member#PUBLIC} members,3042* as well as access to classes that have the same class loader as the caller.3043* In all other cases, it requires RuntimePermission("accessDeclaredMembers")3044* permission.3045*/3046final ClassLoader ccl = ClassLoader.getClassLoader(caller);3047if (which != Member.PUBLIC) {3048final ClassLoader cl = getClassLoader0();3049if (ccl != cl) {3050sm.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);3051}3052}3053this.checkPackageAccess(sm, ccl, checkProxyInterfaces);3054}30553056/*3057* Checks if a client loaded in ClassLoader ccl is allowed to access this3058* class under the current package access policy. If access is denied,3059* throw a SecurityException.3060*3061* NOTE: this method should only be called if a SecurityManager is active3062*/3063private void checkPackageAccess(@SuppressWarnings("removal") SecurityManager sm, final ClassLoader ccl,3064boolean checkProxyInterfaces) {3065final ClassLoader cl = getClassLoader0();30663067if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {3068String pkg = this.getPackageName();3069if (!pkg.isEmpty()) {3070// skip the package access check on a proxy class in default proxy package3071if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {3072sm.checkPackageAccess(pkg);3073}3074}3075}3076// check package access on the proxy interfaces3077if (checkProxyInterfaces && Proxy.isProxyClass(this)) {3078ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());3079}3080}30813082/*3083* Checks if a client loaded in ClassLoader ccl is allowed to access the provided3084* classes under the current package access policy. If access is denied,3085* throw a SecurityException.3086*3087* NOTE: this method should only be called if a SecurityManager is active3088* classes must be non-empty3089* all classes provided must be loaded by the same ClassLoader3090* NOTE: this method does not support Proxy classes3091*/3092private static void checkPackageAccessForPermittedSubclasses(@SuppressWarnings("removal") SecurityManager sm,3093final ClassLoader ccl, Class<?>[] subClasses) {3094final ClassLoader cl = subClasses[0].getClassLoader0();30953096if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {3097Set<String> packages = new HashSet<>();30983099for (Class<?> c : subClasses) {3100if (Proxy.isProxyClass(c))3101throw new InternalError("a permitted subclass should not be a proxy class: " + c);3102String pkg = c.getPackageName();3103if (!pkg.isEmpty()) {3104packages.add(pkg);3105}3106}3107for (String pkg : packages) {3108sm.checkPackageAccess(pkg);3109}3110}3111}31123113/**3114* Add a package name prefix if the name is not absolute. Remove leading "/"3115* if name is absolute3116*/3117private String resolveName(String name) {3118if (!name.startsWith("/")) {3119String baseName = getPackageName();3120if (!baseName.isEmpty()) {3121int len = baseName.length() + 1 + name.length();3122StringBuilder sb = new StringBuilder(len);3123name = sb.append(baseName.replace('.', '/'))3124.append('/')3125.append(name)3126.toString();3127}3128} else {3129name = name.substring(1);3130}3131return name;3132}31333134/**3135* Atomic operations support.3136*/3137private static class Atomic {3138// initialize Unsafe machinery here, since we need to call Class.class instance method3139// and have to avoid calling it in the static initializer of the Class class...3140private static final Unsafe unsafe = Unsafe.getUnsafe();3141// offset of Class.reflectionData instance field3142private static final long reflectionDataOffset3143= unsafe.objectFieldOffset(Class.class, "reflectionData");3144// offset of Class.annotationType instance field3145private static final long annotationTypeOffset3146= unsafe.objectFieldOffset(Class.class, "annotationType");3147// offset of Class.annotationData instance field3148private static final long annotationDataOffset3149= unsafe.objectFieldOffset(Class.class, "annotationData");31503151static <T> boolean casReflectionData(Class<?> clazz,3152SoftReference<ReflectionData<T>> oldData,3153SoftReference<ReflectionData<T>> newData) {3154return unsafe.compareAndSetReference(clazz, reflectionDataOffset, oldData, newData);3155}31563157static boolean casAnnotationType(Class<?> clazz,3158AnnotationType oldType,3159AnnotationType newType) {3160return unsafe.compareAndSetReference(clazz, annotationTypeOffset, oldType, newType);3161}31623163static boolean casAnnotationData(Class<?> clazz,3164AnnotationData oldData,3165AnnotationData newData) {3166return unsafe.compareAndSetReference(clazz, annotationDataOffset, oldData, newData);3167}3168}31693170/**3171* Reflection support.3172*/31733174// Reflection data caches various derived names and reflective members. Cached3175// values may be invalidated when JVM TI RedefineClasses() is called3176private static class ReflectionData<T> {3177volatile Field[] declaredFields;3178volatile Field[] publicFields;3179volatile Method[] declaredMethods;3180volatile Method[] publicMethods;3181volatile Constructor<T>[] declaredConstructors;3182volatile Constructor<T>[] publicConstructors;3183// Intermediate results for getFields and getMethods3184volatile Field[] declaredPublicFields;3185volatile Method[] declaredPublicMethods;3186volatile Class<?>[] interfaces;31873188// Cached names3189String simpleName;3190String canonicalName;3191static final String NULL_SENTINEL = new String();31923193// Value of classRedefinedCount when we created this ReflectionData instance3194final int redefinedCount;31953196ReflectionData(int redefinedCount) {3197this.redefinedCount = redefinedCount;3198}3199}32003201private transient volatile SoftReference<ReflectionData<T>> reflectionData;32023203// Incremented by the VM on each call to JVM TI RedefineClasses()3204// that redefines this class or a superclass.3205private transient volatile int classRedefinedCount;32063207// Lazily create and cache ReflectionData3208private ReflectionData<T> reflectionData() {3209SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;3210int classRedefinedCount = this.classRedefinedCount;3211ReflectionData<T> rd;3212if (reflectionData != null &&3213(rd = reflectionData.get()) != null &&3214rd.redefinedCount == classRedefinedCount) {3215return rd;3216}3217// else no SoftReference or cleared SoftReference or stale ReflectionData3218// -> create and replace new instance3219return newReflectionData(reflectionData, classRedefinedCount);3220}32213222private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,3223int classRedefinedCount) {3224while (true) {3225ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);3226// try to CAS it...3227if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {3228return rd;3229}3230// else retry3231oldReflectionData = this.reflectionData;3232classRedefinedCount = this.classRedefinedCount;3233if (oldReflectionData != null &&3234(rd = oldReflectionData.get()) != null &&3235rd.redefinedCount == classRedefinedCount) {3236return rd;3237}3238}3239}32403241// Generic signature handling3242private native String getGenericSignature0();32433244// Generic info repository; lazily initialized3245private transient volatile ClassRepository genericInfo;32463247// accessor for factory3248private GenericsFactory getFactory() {3249// create scope and factory3250return CoreReflectionFactory.make(this, ClassScope.make(this));3251}32523253// accessor for generic info repository;3254// generic info is lazily initialized3255private ClassRepository getGenericInfo() {3256ClassRepository genericInfo = this.genericInfo;3257if (genericInfo == null) {3258String signature = getGenericSignature0();3259if (signature == null) {3260genericInfo = ClassRepository.NONE;3261} else {3262genericInfo = ClassRepository.make(signature, getFactory());3263}3264this.genericInfo = genericInfo;3265}3266return (genericInfo != ClassRepository.NONE) ? genericInfo : null;3267}32683269// Annotations handling3270native byte[] getRawAnnotations();3271// Since 1.83272native byte[] getRawTypeAnnotations();3273static byte[] getExecutableTypeAnnotationBytes(Executable ex) {3274return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);3275}32763277native ConstantPool getConstantPool();32783279//3280//3281// java.lang.reflect.Field handling3282//3283//32843285// Returns an array of "root" fields. These Field objects must NOT3286// be propagated to the outside world, but must instead be copied3287// via ReflectionFactory.copyField.3288private Field[] privateGetDeclaredFields(boolean publicOnly) {3289Field[] res;3290ReflectionData<T> rd = reflectionData();3291if (rd != null) {3292res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;3293if (res != null) return res;3294}3295// No cached value available; request value from VM3296res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));3297if (rd != null) {3298if (publicOnly) {3299rd.declaredPublicFields = res;3300} else {3301rd.declaredFields = res;3302}3303}3304return res;3305}33063307// Returns an array of "root" fields. These Field objects must NOT3308// be propagated to the outside world, but must instead be copied3309// via ReflectionFactory.copyField.3310private Field[] privateGetPublicFields() {3311Field[] res;3312ReflectionData<T> rd = reflectionData();3313if (rd != null) {3314res = rd.publicFields;3315if (res != null) return res;3316}33173318// Use a linked hash set to ensure order is preserved and3319// fields from common super interfaces are not duplicated3320LinkedHashSet<Field> fields = new LinkedHashSet<>();33213322// Local fields3323addAll(fields, privateGetDeclaredFields(true));33243325// Direct superinterfaces, recursively3326for (Class<?> si : getInterfaces()) {3327addAll(fields, si.privateGetPublicFields());3328}33293330// Direct superclass, recursively3331Class<?> sc = getSuperclass();3332if (sc != null) {3333addAll(fields, sc.privateGetPublicFields());3334}33353336res = fields.toArray(new Field[0]);3337if (rd != null) {3338rd.publicFields = res;3339}3340return res;3341}33423343private static void addAll(Collection<Field> c, Field[] o) {3344for (Field f : o) {3345c.add(f);3346}3347}334833493350//3351//3352// java.lang.reflect.Constructor handling3353//3354//33553356// Returns an array of "root" constructors. These Constructor3357// objects must NOT be propagated to the outside world, but must3358// instead be copied via ReflectionFactory.copyConstructor.3359private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {3360Constructor<T>[] res;3361ReflectionData<T> rd = reflectionData();3362if (rd != null) {3363res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;3364if (res != null) return res;3365}3366// No cached value available; request value from VM3367if (isInterface()) {3368@SuppressWarnings("unchecked")3369Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];3370res = temporaryRes;3371} else {3372res = getDeclaredConstructors0(publicOnly);3373}3374if (rd != null) {3375if (publicOnly) {3376rd.publicConstructors = res;3377} else {3378rd.declaredConstructors = res;3379}3380}3381return res;3382}33833384//3385//3386// java.lang.reflect.Method handling3387//3388//33893390// Returns an array of "root" methods. These Method objects must NOT3391// be propagated to the outside world, but must instead be copied3392// via ReflectionFactory.copyMethod.3393private Method[] privateGetDeclaredMethods(boolean publicOnly) {3394Method[] res;3395ReflectionData<T> rd = reflectionData();3396if (rd != null) {3397res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;3398if (res != null) return res;3399}3400// No cached value available; request value from VM3401res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));3402if (rd != null) {3403if (publicOnly) {3404rd.declaredPublicMethods = res;3405} else {3406rd.declaredMethods = res;3407}3408}3409return res;3410}34113412// Returns an array of "root" methods. These Method objects must NOT3413// be propagated to the outside world, but must instead be copied3414// via ReflectionFactory.copyMethod.3415private Method[] privateGetPublicMethods() {3416Method[] res;3417ReflectionData<T> rd = reflectionData();3418if (rd != null) {3419res = rd.publicMethods;3420if (res != null) return res;3421}34223423// No cached value available; compute value recursively.3424// Start by fetching public declared methods...3425PublicMethods pms = new PublicMethods();3426for (Method m : privateGetDeclaredMethods(/* publicOnly */ true)) {3427pms.merge(m);3428}3429// ...then recur over superclass methods...3430Class<?> sc = getSuperclass();3431if (sc != null) {3432for (Method m : sc.privateGetPublicMethods()) {3433pms.merge(m);3434}3435}3436// ...and finally over direct superinterfaces.3437for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {3438for (Method m : intf.privateGetPublicMethods()) {3439// static interface methods are not inherited3440if (!Modifier.isStatic(m.getModifiers())) {3441pms.merge(m);3442}3443}3444}34453446res = pms.toArray();3447if (rd != null) {3448rd.publicMethods = res;3449}3450return res;3451}345234533454//3455// Helpers for fetchers of one field, method, or constructor3456//34573458// This method does not copy the returned Field object!3459private static Field searchFields(Field[] fields, String name) {3460for (Field field : fields) {3461if (field.getName().equals(name)) {3462return field;3463}3464}3465return null;3466}34673468// Returns a "root" Field object. This Field object must NOT3469// be propagated to the outside world, but must instead be copied3470// via ReflectionFactory.copyField.3471private Field getField0(String name) {3472// Note: the intent is that the search algorithm this routine3473// uses be equivalent to the ordering imposed by3474// privateGetPublicFields(). It fetches only the declared3475// public fields for each class, however, to reduce the number3476// of Field objects which have to be created for the common3477// case where the field being requested is declared in the3478// class which is being queried.3479Field res;3480// Search declared public fields3481if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {3482return res;3483}3484// Direct superinterfaces, recursively3485Class<?>[] interfaces = getInterfaces(/* cloneArray */ false);3486for (Class<?> c : interfaces) {3487if ((res = c.getField0(name)) != null) {3488return res;3489}3490}3491// Direct superclass, recursively3492if (!isInterface()) {3493Class<?> c = getSuperclass();3494if (c != null) {3495if ((res = c.getField0(name)) != null) {3496return res;3497}3498}3499}3500return null;3501}35023503// This method does not copy the returned Method object!3504private static Method searchMethods(Method[] methods,3505String name,3506Class<?>[] parameterTypes)3507{3508ReflectionFactory fact = getReflectionFactory();3509Method res = null;3510for (Method m : methods) {3511if (m.getName().equals(name)3512&& arrayContentsEq(parameterTypes,3513fact.getExecutableSharedParameterTypes(m))3514&& (res == null3515|| (res.getReturnType() != m.getReturnType()3516&& res.getReturnType().isAssignableFrom(m.getReturnType()))))3517res = m;3518}3519return res;3520}35213522private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];35233524// Returns a "root" Method object. This Method object must NOT3525// be propagated to the outside world, but must instead be copied3526// via ReflectionFactory.copyMethod.3527private Method getMethod0(String name, Class<?>[] parameterTypes) {3528PublicMethods.MethodList res = getMethodsRecursive(3529name,3530parameterTypes == null ? EMPTY_CLASS_ARRAY : parameterTypes,3531/* includeStatic */ true);3532return res == null ? null : res.getMostSpecific();3533}35343535// Returns a list of "root" Method objects. These Method objects must NOT3536// be propagated to the outside world, but must instead be copied3537// via ReflectionFactory.copyMethod.3538private PublicMethods.MethodList getMethodsRecursive(String name,3539Class<?>[] parameterTypes,3540boolean includeStatic) {3541// 1st check declared public methods3542Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);3543PublicMethods.MethodList res = PublicMethods.MethodList3544.filter(methods, name, parameterTypes, includeStatic);3545// if there is at least one match among declared methods, we need not3546// search any further as such match surely overrides matching methods3547// declared in superclass(es) or interface(s).3548if (res != null) {3549return res;3550}35513552// if there was no match among declared methods,3553// we must consult the superclass (if any) recursively...3554Class<?> sc = getSuperclass();3555if (sc != null) {3556res = sc.getMethodsRecursive(name, parameterTypes, includeStatic);3557}35583559// ...and coalesce the superclass methods with methods obtained3560// from directly implemented interfaces excluding static methods...3561for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {3562res = PublicMethods.MethodList.merge(3563res, intf.getMethodsRecursive(name, parameterTypes,3564/* includeStatic */ false));3565}35663567return res;3568}35693570// Returns a "root" Constructor object. This Constructor object must NOT3571// be propagated to the outside world, but must instead be copied3572// via ReflectionFactory.copyConstructor.3573private Constructor<T> getConstructor0(Class<?>[] parameterTypes,3574int which) throws NoSuchMethodException3575{3576ReflectionFactory fact = getReflectionFactory();3577Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));3578for (Constructor<T> constructor : constructors) {3579if (arrayContentsEq(parameterTypes,3580fact.getExecutableSharedParameterTypes(constructor))) {3581return constructor;3582}3583}3584throw new NoSuchMethodException(methodToString("<init>", parameterTypes));3585}35863587//3588// Other helpers and base implementation3589//35903591private static boolean arrayContentsEq(Object[] a1, Object[] a2) {3592if (a1 == null) {3593return a2 == null || a2.length == 0;3594}35953596if (a2 == null) {3597return a1.length == 0;3598}35993600if (a1.length != a2.length) {3601return false;3602}36033604for (int i = 0; i < a1.length; i++) {3605if (a1[i] != a2[i]) {3606return false;3607}3608}36093610return true;3611}36123613private static Field[] copyFields(Field[] arg) {3614Field[] out = new Field[arg.length];3615ReflectionFactory fact = getReflectionFactory();3616for (int i = 0; i < arg.length; i++) {3617out[i] = fact.copyField(arg[i]);3618}3619return out;3620}36213622private static Method[] copyMethods(Method[] arg) {3623Method[] out = new Method[arg.length];3624ReflectionFactory fact = getReflectionFactory();3625for (int i = 0; i < arg.length; i++) {3626out[i] = fact.copyMethod(arg[i]);3627}3628return out;3629}36303631private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {3632Constructor<U>[] out = arg.clone();3633ReflectionFactory fact = getReflectionFactory();3634for (int i = 0; i < out.length; i++) {3635out[i] = fact.copyConstructor(out[i]);3636}3637return out;3638}36393640private native Field[] getDeclaredFields0(boolean publicOnly);3641private native Method[] getDeclaredMethods0(boolean publicOnly);3642private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);3643private native Class<?>[] getDeclaredClasses0();36443645/*3646* Returns an array containing the components of the Record attribute,3647* or null if the attribute is not present.3648*3649* Note that this method returns non-null array on a class with3650* the Record attribute even if this class is not a record.3651*/3652private native RecordComponent[] getRecordComponents0();3653private native boolean isRecord0();36543655/**3656* Helper method to get the method name from arguments.3657*/3658private String methodToString(String name, Class<?>[] argTypes) {3659return getName() + '.' + name +3660((argTypes == null || argTypes.length == 0) ?3661"()" :3662Arrays.stream(argTypes)3663.map(c -> c == null ? "null" : c.getName())3664.collect(Collectors.joining(",", "(", ")")));3665}36663667/** use serialVersionUID from JDK 1.1 for interoperability */3668@java.io.Serial3669private static final long serialVersionUID = 3206093459760846163L;367036713672/**3673* Class Class is special cased within the Serialization Stream Protocol.3674*3675* A Class instance is written initially into an ObjectOutputStream in the3676* following format:3677* <pre>3678* {@code TC_CLASS} ClassDescriptor3679* A ClassDescriptor is a special cased serialization of3680* a {@code java.io.ObjectStreamClass} instance.3681* </pre>3682* A new handle is generated for the initial time the class descriptor3683* is written into the stream. Future references to the class descriptor3684* are written as references to the initial class descriptor instance.3685*3686* @see java.io.ObjectStreamClass3687*/3688@java.io.Serial3689private static final ObjectStreamField[] serialPersistentFields =3690new ObjectStreamField[0];369136923693/**3694* Returns the assertion status that would be assigned to this3695* class if it were to be initialized at the time this method is invoked.3696* If this class has had its assertion status set, the most recent3697* setting will be returned; otherwise, if any package default assertion3698* status pertains to this class, the most recent setting for the most3699* specific pertinent package default assertion status is returned;3700* otherwise, if this class is not a system class (i.e., it has a3701* class loader) its class loader's default assertion status is returned;3702* otherwise, the system class default assertion status is returned.3703*3704* @apiNote3705* Few programmers will have any need for this method; it is provided3706* for the benefit of the JDK itself. (It allows a class to determine at3707* the time that it is initialized whether assertions should be enabled.)3708* Note that this method is not guaranteed to return the actual3709* assertion status that was (or will be) associated with the specified3710* class when it was (or will be) initialized.3711*3712* @return the desired assertion status of the specified class.3713* @see java.lang.ClassLoader#setClassAssertionStatus3714* @see java.lang.ClassLoader#setPackageAssertionStatus3715* @see java.lang.ClassLoader#setDefaultAssertionStatus3716* @since 1.43717*/3718public boolean desiredAssertionStatus() {3719ClassLoader loader = getClassLoader0();3720// If the loader is null this is a system class, so ask the VM3721if (loader == null)3722return desiredAssertionStatus0(this);37233724// If the classloader has been initialized with the assertion3725// directives, ask it. Otherwise, ask the VM.3726synchronized(loader.assertionLock) {3727if (loader.classAssertionStatus != null) {3728return loader.desiredAssertionStatus(getName());3729}3730}3731return desiredAssertionStatus0(this);3732}37333734// Retrieves the desired assertion status of this class from the VM3735private static native boolean desiredAssertionStatus0(Class<?> clazz);37363737/**3738* Returns true if and only if this class was declared as an enum in the3739* source code.3740*3741* Note that {@link java.lang.Enum} is not itself an enum class.3742*3743* Also note that if an enum constant is declared with a class body,3744* the class of that enum constant object is an anonymous class3745* and <em>not</em> the class of the declaring enum class. The3746* {@link Enum#getDeclaringClass} method of an enum constant can3747* be used to get the class of the enum class declaring the3748* constant.3749*3750* @return true if and only if this class was declared as an enum in the3751* source code3752* @since 1.53753* @jls 8.9.1 Enum Constants3754*/3755public boolean isEnum() {3756// An enum must both directly extend java.lang.Enum and have3757// the ENUM bit set; classes for specialized enum constants3758// don't do the former.3759return (this.getModifiers() & ENUM) != 0 &&3760this.getSuperclass() == java.lang.Enum.class;3761}37623763/**3764* Returns {@code true} if and only if this class is a record class.3765*3766* <p> The {@linkplain #getSuperclass() direct superclass} of a record3767* class is {@code java.lang.Record}. A record class is {@linkplain3768* Modifier#FINAL final}. A record class has (possibly zero) record3769* components; {@link #getRecordComponents()} returns a non-null but3770* possibly empty value for a record.3771*3772* <p> Note that class {@link Record} is not a record class and thus3773* invoking this method on class {@code Record} returns {@code false}.3774*3775* @return true if and only if this class is a record class, otherwise false3776* @jls 8.10 Record Classes3777* @since 163778*/3779public boolean isRecord() {3780// this superclass and final modifier check is not strictly necessary3781// they are intrinsified and serve as a fast-path check3782return getSuperclass() == java.lang.Record.class &&3783(this.getModifiers() & Modifier.FINAL) != 0 &&3784isRecord0();3785}37863787// Fetches the factory for reflective objects3788@SuppressWarnings("removal")3789private static ReflectionFactory getReflectionFactory() {3790if (reflectionFactory == null) {3791reflectionFactory =3792java.security.AccessController.doPrivileged3793(new ReflectionFactory.GetReflectionFactoryAction());3794}3795return reflectionFactory;3796}3797private static ReflectionFactory reflectionFactory;37983799/**3800* Returns the elements of this enum class or null if this3801* Class object does not represent an enum class.3802*3803* @return an array containing the values comprising the enum class3804* represented by this {@code Class} object in the order they're3805* declared, or null if this {@code Class} object does not3806* represent an enum class3807* @since 1.53808* @jls 8.9.1 Enum Constants3809*/3810public T[] getEnumConstants() {3811T[] values = getEnumConstantsShared();3812return (values != null) ? values.clone() : null;3813}38143815/**3816* Returns the elements of this enum class or null if this3817* Class object does not represent an enum class;3818* identical to getEnumConstants except that the result is3819* uncloned, cached, and shared by all callers.3820*/3821@SuppressWarnings("removal")3822T[] getEnumConstantsShared() {3823T[] constants = enumConstants;3824if (constants == null) {3825if (!isEnum()) return null;3826try {3827final Method values = getMethod("values");3828java.security.AccessController.doPrivileged(3829new java.security.PrivilegedAction<>() {3830public Void run() {3831values.setAccessible(true);3832return null;3833}3834});3835@SuppressWarnings("unchecked")3836T[] temporaryConstants = (T[])values.invoke(null);3837enumConstants = constants = temporaryConstants;3838}3839// These can happen when users concoct enum-like classes3840// that don't comply with the enum spec.3841catch (InvocationTargetException | NoSuchMethodException |3842IllegalAccessException ex) { return null; }3843}3844return constants;3845}3846private transient volatile T[] enumConstants;38473848/**3849* Returns a map from simple name to enum constant. This package-private3850* method is used internally by Enum to implement3851* {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}3852* efficiently. Note that the map is returned by this method is3853* created lazily on first use. Typically it won't ever get created.3854*/3855Map<String, T> enumConstantDirectory() {3856Map<String, T> directory = enumConstantDirectory;3857if (directory == null) {3858T[] universe = getEnumConstantsShared();3859if (universe == null)3860throw new IllegalArgumentException(3861getName() + " is not an enum class");3862directory = new HashMap<>((int)(universe.length / 0.75f) + 1);3863for (T constant : universe) {3864directory.put(((Enum<?>)constant).name(), constant);3865}3866enumConstantDirectory = directory;3867}3868return directory;3869}3870private transient volatile Map<String, T> enumConstantDirectory;38713872/**3873* Casts an object to the class or interface represented3874* by this {@code Class} object.3875*3876* @param obj the object to be cast3877* @return the object after casting, or null if obj is null3878*3879* @throws ClassCastException if the object is not3880* null and is not assignable to the type T.3881*3882* @since 1.53883*/3884@SuppressWarnings("unchecked")3885@IntrinsicCandidate3886public T cast(Object obj) {3887if (obj != null && !isInstance(obj))3888throw new ClassCastException(cannotCastMsg(obj));3889return (T) obj;3890}38913892private String cannotCastMsg(Object obj) {3893return "Cannot cast " + obj.getClass().getName() + " to " + getName();3894}38953896/**3897* Casts this {@code Class} object to represent a subclass of the class3898* represented by the specified class object. Checks that the cast3899* is valid, and throws a {@code ClassCastException} if it is not. If3900* this method succeeds, it always returns a reference to this {@code Class} object.3901*3902* <p>This method is useful when a client needs to "narrow" the type of3903* a {@code Class} object to pass it to an API that restricts the3904* {@code Class} objects that it is willing to accept. A cast would3905* generate a compile-time warning, as the correctness of the cast3906* could not be checked at runtime (because generic types are implemented3907* by erasure).3908*3909* @param <U> the type to cast this {@code Class} object to3910* @param clazz the class of the type to cast this {@code Class} object to3911* @return this {@code Class} object, cast to represent a subclass of3912* the specified class object.3913* @throws ClassCastException if this {@code Class} object does not3914* represent a subclass of the specified class (here "subclass" includes3915* the class itself).3916* @since 1.53917*/3918@SuppressWarnings("unchecked")3919public <U> Class<? extends U> asSubclass(Class<U> clazz) {3920if (clazz.isAssignableFrom(this))3921return (Class<? extends U>) this;3922else3923throw new ClassCastException(this.toString());3924}39253926/**3927* {@inheritDoc}3928* <p>Note that any annotation returned by this method is a3929* declaration annotation.3930*3931* @throws NullPointerException {@inheritDoc}3932* @since 1.53933*/3934@Override3935@SuppressWarnings("unchecked")3936public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {3937Objects.requireNonNull(annotationClass);39383939return (A) annotationData().annotations.get(annotationClass);3940}39413942/**3943* {@inheritDoc}3944* @throws NullPointerException {@inheritDoc}3945* @since 1.53946*/3947@Override3948public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {3949return GenericDeclaration.super.isAnnotationPresent(annotationClass);3950}39513952/**3953* {@inheritDoc}3954* <p>Note that any annotations returned by this method are3955* declaration annotations.3956*3957* @throws NullPointerException {@inheritDoc}3958* @since 1.83959*/3960@Override3961public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {3962Objects.requireNonNull(annotationClass);39633964AnnotationData annotationData = annotationData();3965return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations,3966this,3967annotationClass);3968}39693970/**3971* {@inheritDoc}3972* <p>Note that any annotations returned by this method are3973* declaration annotations.3974*3975* @since 1.53976*/3977@Override3978public Annotation[] getAnnotations() {3979return AnnotationParser.toArray(annotationData().annotations);3980}39813982/**3983* {@inheritDoc}3984* <p>Note that any annotation returned by this method is a3985* declaration annotation.3986*3987* @throws NullPointerException {@inheritDoc}3988* @since 1.83989*/3990@Override3991@SuppressWarnings("unchecked")3992public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {3993Objects.requireNonNull(annotationClass);39943995return (A) annotationData().declaredAnnotations.get(annotationClass);3996}39973998/**3999* {@inheritDoc}4000* <p>Note that any annotations returned by this method are4001* declaration annotations.4002*4003* @throws NullPointerException {@inheritDoc}4004* @since 1.84005*/4006@Override4007public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {4008Objects.requireNonNull(annotationClass);40094010return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,4011annotationClass);4012}40134014/**4015* {@inheritDoc}4016* <p>Note that any annotations returned by this method are4017* declaration annotations.4018*4019* @since 1.54020*/4021@Override4022public Annotation[] getDeclaredAnnotations() {4023return AnnotationParser.toArray(annotationData().declaredAnnotations);4024}40254026// annotation data that might get invalidated when JVM TI RedefineClasses() is called4027private static class AnnotationData {4028final Map<Class<? extends Annotation>, Annotation> annotations;4029final Map<Class<? extends Annotation>, Annotation> declaredAnnotations;40304031// Value of classRedefinedCount when we created this AnnotationData instance4032final int redefinedCount;40334034AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations,4035Map<Class<? extends Annotation>, Annotation> declaredAnnotations,4036int redefinedCount) {4037this.annotations = annotations;4038this.declaredAnnotations = declaredAnnotations;4039this.redefinedCount = redefinedCount;4040}4041}40424043// Annotations cache4044@SuppressWarnings("UnusedDeclaration")4045private transient volatile AnnotationData annotationData;40464047private AnnotationData annotationData() {4048while (true) { // retry loop4049AnnotationData annotationData = this.annotationData;4050int classRedefinedCount = this.classRedefinedCount;4051if (annotationData != null &&4052annotationData.redefinedCount == classRedefinedCount) {4053return annotationData;4054}4055// null or stale annotationData -> optimistically create new instance4056AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount);4057// try to install it4058if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) {4059// successfully installed new AnnotationData4060return newAnnotationData;4061}4062}4063}40644065private AnnotationData createAnnotationData(int classRedefinedCount) {4066Map<Class<? extends Annotation>, Annotation> declaredAnnotations =4067AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this);4068Class<?> superClass = getSuperclass();4069Map<Class<? extends Annotation>, Annotation> annotations = null;4070if (superClass != null) {4071Map<Class<? extends Annotation>, Annotation> superAnnotations =4072superClass.annotationData().annotations;4073for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) {4074Class<? extends Annotation> annotationClass = e.getKey();4075if (AnnotationType.getInstance(annotationClass).isInherited()) {4076if (annotations == null) { // lazy construction4077annotations = new LinkedHashMap<>((Math.max(4078declaredAnnotations.size(),4079Math.min(12, declaredAnnotations.size() + superAnnotations.size())4080) * 4 + 2) / 34081);4082}4083annotations.put(annotationClass, e.getValue());4084}4085}4086}4087if (annotations == null) {4088// no inherited annotations -> share the Map with declaredAnnotations4089annotations = declaredAnnotations;4090} else {4091// at least one inherited annotation -> declared may override inherited4092annotations.putAll(declaredAnnotations);4093}4094return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount);4095}40964097// Annotation interfaces cache their internal (AnnotationType) form40984099@SuppressWarnings("UnusedDeclaration")4100private transient volatile AnnotationType annotationType;41014102boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {4103return Atomic.casAnnotationType(this, oldType, newType);4104}41054106AnnotationType getAnnotationType() {4107return annotationType;4108}41094110Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() {4111return annotationData().declaredAnnotations;4112}41134114/* Backing store of user-defined values pertaining to this class.4115* Maintained by the ClassValue class.4116*/4117transient ClassValue.ClassValueMap classValueMap;41184119/**4120* Returns an {@code AnnotatedType} object that represents the use of a4121* type to specify the superclass of the entity represented by this {@code4122* Class} object. (The <em>use</em> of type Foo to specify the superclass4123* in '... extends Foo' is distinct from the <em>declaration</em> of class4124* Foo.)4125*4126* <p> If this {@code Class} object represents a class whose declaration4127* does not explicitly indicate an annotated superclass, then the return4128* value is an {@code AnnotatedType} object representing an element with no4129* annotations.4130*4131* <p> If this {@code Class} represents either the {@code Object} class, an4132* interface type, an array type, a primitive type, or void, the return4133* value is {@code null}.4134*4135* @return an object representing the superclass4136* @since 1.84137*/4138public AnnotatedType getAnnotatedSuperclass() {4139if (this == Object.class ||4140isInterface() ||4141isArray() ||4142isPrimitive() ||4143this == Void.TYPE) {4144return null;4145}41464147return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);4148}41494150/**4151* Returns an array of {@code AnnotatedType} objects that represent the use4152* of types to specify superinterfaces of the entity represented by this4153* {@code Class} object. (The <em>use</em> of type Foo to specify a4154* superinterface in '... implements Foo' is distinct from the4155* <em>declaration</em> of interface Foo.)4156*4157* <p> If this {@code Class} object represents a class, the return value is4158* an array containing objects representing the uses of interface types to4159* specify interfaces implemented by the class. The order of the objects in4160* the array corresponds to the order of the interface types used in the4161* 'implements' clause of the declaration of this {@code Class} object.4162*4163* <p> If this {@code Class} object represents an interface, the return4164* value is an array containing objects representing the uses of interface4165* types to specify interfaces directly extended by the interface. The4166* order of the objects in the array corresponds to the order of the4167* interface types used in the 'extends' clause of the declaration of this4168* {@code Class} object.4169*4170* <p> If this {@code Class} object represents a class or interface whose4171* declaration does not explicitly indicate any annotated superinterfaces,4172* the return value is an array of length 0.4173*4174* <p> If this {@code Class} object represents either the {@code Object}4175* class, an array type, a primitive type, or void, the return value is an4176* array of length 0.4177*4178* @return an array representing the superinterfaces4179* @since 1.84180*/4181public AnnotatedType[] getAnnotatedInterfaces() {4182return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);4183}41844185private native Class<?> getNestHost0();41864187/**4188* Returns the nest host of the <a href=#nest>nest</a> to which the class4189* or interface represented by this {@code Class} object belongs.4190* Every class and interface belongs to exactly one nest.4191*4192* If the nest host of this class or interface has previously4193* been determined, then this method returns the nest host.4194* If the nest host of this class or interface has4195* not previously been determined, then this method determines the nest4196* host using the algorithm of JVMS 5.4.4, and returns it.4197*4198* Often, a class or interface belongs to a nest consisting only of itself,4199* in which case this method returns {@code this} to indicate that the class4200* or interface is the nest host.4201*4202* <p>If this {@code Class} object represents a primitive type, an array type,4203* or {@code void}, then this method returns {@code this},4204* indicating that the represented entity belongs to the nest consisting only of4205* itself, and is the nest host.4206*4207* @return the nest host of this class or interface4208*4209* @throws SecurityException4210* If the returned class is not the current class, and4211* if a security manager, <i>s</i>, is present and the caller's4212* class loader is not the same as or an ancestor of the class4213* loader for the returned class and invocation of {@link4214* SecurityManager#checkPackageAccess s.checkPackageAccess()}4215* denies access to the package of the returned class4216* @since 114217* @jvms 4.7.28 The {@code NestHost} Attribute4218* @jvms 4.7.29 The {@code NestMembers} Attribute4219* @jvms 5.4.4 Access Control4220*/4221@CallerSensitive4222public Class<?> getNestHost() {4223if (isPrimitive() || isArray()) {4224return this;4225}42264227Class<?> host = getNestHost0();4228if (host == this) {4229return this;4230}4231// returning a different class requires a security check4232@SuppressWarnings("removal")4233SecurityManager sm = System.getSecurityManager();4234if (sm != null) {4235checkPackageAccess(sm,4236ClassLoader.getClassLoader(Reflection.getCallerClass()), true);4237}4238return host;4239}42404241/**4242* Determines if the given {@code Class} is a nestmate of the4243* class or interface represented by this {@code Class} object.4244* Two classes or interfaces are nestmates4245* if they have the same {@linkplain #getNestHost() nest host}.4246*4247* @param c the class to check4248* @return {@code true} if this class and {@code c} are members of4249* the same nest; and {@code false} otherwise.4250*4251* @since 114252*/4253public boolean isNestmateOf(Class<?> c) {4254if (this == c) {4255return true;4256}4257if (isPrimitive() || isArray() ||4258c.isPrimitive() || c.isArray()) {4259return false;4260}42614262return getNestHost() == c.getNestHost();4263}42644265private native Class<?>[] getNestMembers0();42664267/**4268* Returns an array containing {@code Class} objects representing all the4269* classes and interfaces that are members of the nest to which the class4270* or interface represented by this {@code Class} object belongs.4271*4272* First, this method obtains the {@linkplain #getNestHost() nest host},4273* {@code H}, of the nest to which the class or interface represented by4274* this {@code Class} object belongs. The zeroth element of the returned4275* array is {@code H}.4276*4277* Then, for each class or interface {@code C} which is recorded by {@code H}4278* as being a member of its nest, this method attempts to obtain the {@code Class}4279* object for {@code C} (using {@linkplain #getClassLoader() the defining class4280* loader} of the current {@code Class} object), and then obtains the4281* {@linkplain #getNestHost() nest host} of the nest to which {@code C} belongs.4282* The classes and interfaces which are recorded by {@code H} as being members4283* of its nest, and for which {@code H} can be determined as their nest host,4284* are indicated by subsequent elements of the returned array. The order of4285* such elements is unspecified. Duplicates are permitted.4286*4287* <p>If this {@code Class} object represents a primitive type, an array type,4288* or {@code void}, then this method returns a single-element array containing4289* {@code this}.4290*4291* @apiNote4292* The returned array includes only the nest members recorded in the {@code NestMembers}4293* attribute, and not any hidden classes that were added to the nest via4294* {@link MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)4295* Lookup::defineHiddenClass}.4296*4297* @return an array of all classes and interfaces in the same nest as4298* this class or interface4299*4300* @throws SecurityException4301* If any returned class is not the current class, and4302* if a security manager, <i>s</i>, is present and the caller's4303* class loader is not the same as or an ancestor of the class4304* loader for that returned class and invocation of {@link4305* SecurityManager#checkPackageAccess s.checkPackageAccess()}4306* denies access to the package of that returned class4307*4308* @since 114309* @see #getNestHost()4310* @jvms 4.7.28 The {@code NestHost} Attribute4311* @jvms 4.7.29 The {@code NestMembers} Attribute4312*/4313@CallerSensitive4314public Class<?>[] getNestMembers() {4315if (isPrimitive() || isArray()) {4316return new Class<?>[] { this };4317}4318Class<?>[] members = getNestMembers0();4319// Can't actually enable this due to bootstrapping issues4320// assert(members.length != 1 || members[0] == this); // expected invariant from VM43214322if (members.length > 1) {4323// If we return anything other than the current class we need4324// a security check4325@SuppressWarnings("removal")4326SecurityManager sm = System.getSecurityManager();4327if (sm != null) {4328checkPackageAccess(sm,4329ClassLoader.getClassLoader(Reflection.getCallerClass()), true);4330}4331}4332return members;4333}43344335/**4336* Returns the descriptor string of the entity (class, interface, array class,4337* primitive type, or {@code void}) represented by this {@code Class} object.4338*4339* <p> If this {@code Class} object represents a class or interface,4340* not an array class, then:4341* <ul>4342* <li> If the class or interface is not {@linkplain Class#isHidden() hidden},4343* then the result is a field descriptor (JVMS {@jvms 4.3.2})4344* for the class or interface. Calling4345* {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor}4346* with the result descriptor string produces a {@link ClassDesc ClassDesc}4347* describing this class or interface.4348* <li> If the class or interface is {@linkplain Class#isHidden() hidden},4349* then the result is a string of the form:4350* <blockquote>4351* {@code "L" +} <em>N</em> {@code + "." + <suffix> + ";"}4352* </blockquote>4353* where <em>N</em> is the <a href="ClassLoader.html#binary-name">binary name</a>4354* encoded in internal form indicated by the {@code class} file passed to4355* {@link MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)4356* Lookup::defineHiddenClass}, and {@code <suffix>} is an unqualified name.4357* A hidden class or interface has no {@linkplain ClassDesc nominal descriptor}.4358* The result string is not a type descriptor.4359* </ul>4360*4361* <p> If this {@code Class} object represents an array class, then4362* the result is a string consisting of one or more '{@code [}' characters4363* representing the depth of the array nesting, followed by the4364* descriptor string of the element type.4365* <ul>4366* <li> If the element type is not a {@linkplain Class#isHidden() hidden} class4367* or interface, then this array class can be described nominally.4368* Calling {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor}4369* with the result descriptor string produces a {@link ClassDesc ClassDesc}4370* describing this array class.4371* <li> If the element type is a {@linkplain Class#isHidden() hidden} class or4372* interface, then this array class cannot be described nominally.4373* The result string is not a type descriptor.4374* </ul>4375*4376* <p> If this {@code Class} object represents a primitive type or4377* {@code void}, then the result is a field descriptor string which4378* is a one-letter code corresponding to a primitive type or {@code void}4379* ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}).4380*4381* @apiNote4382* This is not a strict inverse of {@link #forName};4383* distinct classes which share a common name but have different class loaders4384* will have identical descriptor strings.4385*4386* @return the descriptor string for this {@code Class} object4387* @jvms 4.3.2 Field Descriptors4388* @since 124389*/4390@Override4391public String descriptorString() {4392if (isPrimitive())4393return Wrapper.forPrimitiveType(this).basicTypeString();43944395if (isArray()) {4396return "[" + componentType.descriptorString();4397} else if (isHidden()) {4398String name = getName();4399int index = name.indexOf('/');4400return new StringBuilder(name.length() + 2)4401.append('L')4402.append(name.substring(0, index).replace('.', '/'))4403.append('.')4404.append(name, index + 1, name.length())4405.append(';')4406.toString();4407} else {4408String name = getName().replace('.', '/');4409return new StringBuilder(name.length() + 2)4410.append('L')4411.append(name)4412.append(';')4413.toString();4414}4415}44164417/**4418* Returns the component type of this {@code Class}, if it describes4419* an array type, or {@code null} otherwise.4420*4421* @implSpec4422* Equivalent to {@link Class#getComponentType()}.4423*4424* @return a {@code Class} describing the component type, or {@code null}4425* if this {@code Class} does not describe an array type4426* @since 124427*/4428@Override4429public Class<?> componentType() {4430return isArray() ? componentType : null;4431}44324433/**4434* Returns a {@code Class} for an array type whose component type4435* is described by this {@linkplain Class}.4436*4437* @return a {@code Class} describing the array type4438* @since 124439*/4440@Override4441public Class<?> arrayType() {4442return Array.newInstance(this, 0).getClass();4443}44444445/**4446* Returns a nominal descriptor for this instance, if one can be4447* constructed, or an empty {@link Optional} if one cannot be.4448*4449* @return An {@link Optional} containing the resulting nominal descriptor,4450* or an empty {@link Optional} if one cannot be constructed.4451* @since 124452*/4453@Override4454public Optional<ClassDesc> describeConstable() {4455Class<?> c = isArray() ? elementType() : this;4456return c.isHidden() ? Optional.empty()4457: Optional.of(ClassDesc.ofDescriptor(descriptorString()));4458}44594460/**4461* Returns {@code true} if and only if the underlying class is a hidden class.4462*4463* @return {@code true} if and only if this class is a hidden class.4464*4465* @since 154466* @see MethodHandles.Lookup#defineHiddenClass4467*/4468@IntrinsicCandidate4469public native boolean isHidden();44704471/**4472* Returns an array containing {@code Class} objects representing the4473* direct subinterfaces or subclasses permitted to extend or4474* implement this class or interface if it is sealed. The order of such elements4475* is unspecified. The array is empty if this sealed class or interface has no4476* permitted subclass. If this {@code Class} object represents a primitive type,4477* {@code void}, an array type, or a class or interface that is not sealed,4478* that is {@link #isSealed()} returns {@code false}, then this method returns {@code null}.4479* Conversely, if {@link #isSealed()} returns {@code true}, then this method4480* returns a non-null value.4481*4482* For each class or interface {@code C} which is recorded as a permitted4483* direct subinterface or subclass of this class or interface,4484* this method attempts to obtain the {@code Class}4485* object for {@code C} (using {@linkplain #getClassLoader() the defining class4486* loader} of the current {@code Class} object).4487* The {@code Class} objects which can be obtained and which are direct4488* subinterfaces or subclasses of this class or interface,4489* are indicated by elements of the returned array. If a {@code Class} object4490* cannot be obtained, it is silently ignored, and not included in the result4491* array.4492*4493* @return an array of {@code Class} objects of the permitted subclasses of this class or interface,4494* or {@code null} if this class or interface is not sealed.4495*4496* @throws SecurityException4497* If a security manager, <i>s</i>, is present and the caller's4498* class loader is not the same as or an ancestor of the class4499* loader for that returned class and invocation of {@link4500* SecurityManager#checkPackageAccess s.checkPackageAccess()}4501* denies access to the package of any class in the returned array.4502*4503* @jls 8.1 Class Declarations4504* @jls 9.1 Interface Declarations4505* @since 174506*/4507@CallerSensitive4508public Class<?>[] getPermittedSubclasses() {4509Class<?>[] subClasses;4510if (isArray() || isPrimitive() || (subClasses = getPermittedSubclasses0()) == null) {4511return null;4512}4513if (subClasses.length > 0) {4514if (Arrays.stream(subClasses).anyMatch(c -> !isDirectSubType(c))) {4515subClasses = Arrays.stream(subClasses)4516.filter(this::isDirectSubType)4517.toArray(s -> new Class<?>[s]);4518}4519}4520if (subClasses.length > 0) {4521// If we return some classes we need a security check:4522@SuppressWarnings("removal")4523SecurityManager sm = System.getSecurityManager();4524if (sm != null) {4525checkPackageAccessForPermittedSubclasses(sm,4526ClassLoader.getClassLoader(Reflection.getCallerClass()),4527subClasses);4528}4529}4530return subClasses;4531}45324533private boolean isDirectSubType(Class<?> c) {4534if (isInterface()) {4535for (Class<?> i : c.getInterfaces(/* cloneArray */ false)) {4536if (i == this) {4537return true;4538}4539}4540} else {4541return c.getSuperclass() == this;4542}4543return false;4544}45454546/**4547* Returns {@code true} if and only if this {@code Class} object represents4548* a sealed class or interface. If this {@code Class} object represents a4549* primitive type, {@code void}, or an array type, this method returns4550* {@code false}. A sealed class or interface has (possibly zero) permitted4551* subclasses; {@link #getPermittedSubclasses()} returns a non-null but4552* possibly empty value for a sealed class or interface.4553*4554* @return {@code true} if and only if this {@code Class} object represents4555* a sealed class or interface.4556*4557* @jls 8.1 Class Declarations4558* @jls 9.1 Interface Declarations4559* @since 174560*/4561public boolean isSealed() {4562if (isArray() || isPrimitive()) {4563return false;4564}4565return getPermittedSubclasses() != null;4566}45674568private native Class<?>[] getPermittedSubclasses0();4569}457045714572