Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/lang/Class.java
38829 views
/*1* Copyright (c) 1994, 2014, 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.reflect.AnnotatedElement;28import java.lang.reflect.Array;29import java.lang.reflect.GenericArrayType;30import java.lang.reflect.GenericDeclaration;31import java.lang.reflect.Member;32import java.lang.reflect.Field;33import java.lang.reflect.Executable;34import java.lang.reflect.Method;35import java.lang.reflect.Constructor;36import java.lang.reflect.Modifier;37import java.lang.reflect.Type;38import java.lang.reflect.TypeVariable;39import java.lang.reflect.InvocationTargetException;40import java.lang.reflect.AnnotatedType;41import java.lang.ref.SoftReference;42import java.io.InputStream;43import java.io.ObjectStreamField;44import java.security.AccessController;45import java.security.PrivilegedAction;46import java.util.ArrayList;47import java.util.Arrays;48import java.util.Collection;49import java.util.HashSet;50import java.util.LinkedHashMap;51import java.util.List;52import java.util.Set;53import java.util.Map;54import java.util.HashMap;55import java.util.Objects;56import sun.misc.Unsafe;57import sun.reflect.CallerSensitive;58import sun.reflect.ConstantPool;59import sun.reflect.Reflection;60import sun.reflect.ReflectionFactory;61import sun.reflect.generics.factory.CoreReflectionFactory;62import sun.reflect.generics.factory.GenericsFactory;63import sun.reflect.generics.repository.ClassRepository;64import sun.reflect.generics.repository.MethodRepository;65import sun.reflect.generics.repository.ConstructorRepository;66import sun.reflect.generics.scope.ClassScope;67import sun.security.util.SecurityConstants;68import java.lang.annotation.Annotation;69import java.lang.reflect.Proxy;70import sun.reflect.annotation.*;71import sun.reflect.misc.ReflectUtil;7273/**74* Instances of the class {@code Class} represent classes and75* interfaces in a running Java application. An enum is a kind of76* class and an annotation is a kind of interface. Every array also77* belongs to a class that is reflected as a {@code Class} object78* that is shared by all arrays with the same element type and number79* of dimensions. The primitive Java types ({@code boolean},80* {@code byte}, {@code char}, {@code short},81* {@code int}, {@code long}, {@code float}, and82* {@code double}), and the keyword {@code void} are also83* represented as {@code Class} objects.84*85* <p> {@code Class} has no public constructor. Instead {@code Class}86* objects are constructed automatically by the Java Virtual Machine as classes87* are loaded and by calls to the {@code defineClass} method in the class88* loader.89*90* <p> The following example uses a {@code Class} object to print the91* class name of an object:92*93* <blockquote><pre>94* void printClassName(Object obj) {95* System.out.println("The class of " + obj +96* " is " + obj.getClass().getName());97* }98* </pre></blockquote>99*100* <p> It is also possible to get the {@code Class} object for a named101* type (or for void) using a class literal. See Section 15.8.2 of102* <cite>The Java™ Language Specification</cite>.103* For example:104*105* <blockquote>106* {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}107* </blockquote>108*109* @param <T> the type of the class modeled by this {@code Class}110* object. For example, the type of {@code String.class} is {@code111* Class<String>}. Use {@code Class<?>} if the class being modeled is112* unknown.113*114* @author unascribed115* @see java.lang.ClassLoader#defineClass(byte[], int, int)116* @since JDK1.0117*/118public final class Class<T> implements java.io.Serializable,119GenericDeclaration,120Type,121AnnotatedElement {122private static final int ANNOTATION= 0x00002000;123private static final int ENUM = 0x00004000;124private static final int SYNTHETIC = 0x00001000;125126private static native void registerNatives();127static {128registerNatives();129}130131/*132* Private constructor. Only the Java Virtual Machine creates Class objects.133* This constructor is not used and prevents the default constructor being134* generated.135*/136private Class(ClassLoader loader) {137// Initialize final field for classLoader. The initialization value of non-null138// prevents future JIT optimizations from assuming this final field is null.139classLoader = loader;140}141142/**143* Converts the object to a string. The string representation is the144* string "class" or "interface", followed by a space, and then by the145* fully qualified name of the class in the format returned by146* {@code getName}. If this {@code Class} object represents a147* primitive type, this method returns the name of the primitive type. If148* this {@code Class} object represents void this method returns149* "void".150*151* @return a string representation of this class object.152*/153public String toString() {154return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))155+ getName();156}157158/**159* Returns a string describing this {@code Class}, including160* information about modifiers and type parameters.161*162* The string is formatted as a list of type modifiers, if any,163* followed by the kind of type (empty string for primitive types164* and {@code class}, {@code enum}, {@code interface}, or165* <code>@</code>{@code interface}, as appropriate), followed166* by the type's name, followed by an angle-bracketed167* comma-separated list of the type's type parameters, if any.168*169* A space is used to separate modifiers from one another and to170* separate any modifiers from the kind of type. The modifiers171* occur in canonical order. If there are no type parameters, the172* type parameter list is elided.173*174* <p>Note that since information about the runtime representation175* of a type is being generated, modifiers not present on the176* originating source code or illegal on the originating source177* code may be present.178*179* @return a string describing this {@code Class}, including180* information about modifiers and type parameters181*182* @since 1.8183*/184public String toGenericString() {185if (isPrimitive()) {186return toString();187} else {188StringBuilder sb = new StringBuilder();189190// Class modifiers are a superset of interface modifiers191int modifiers = getModifiers() & Modifier.classModifiers();192if (modifiers != 0) {193sb.append(Modifier.toString(modifiers));194sb.append(' ');195}196197if (isAnnotation()) {198sb.append('@');199}200if (isInterface()) { // Note: all annotation types are interfaces201sb.append("interface");202} else {203if (isEnum())204sb.append("enum");205else206sb.append("class");207}208sb.append(' ');209sb.append(getName());210211TypeVariable<?>[] typeparms = getTypeParameters();212if (typeparms.length > 0) {213boolean first = true;214sb.append('<');215for(TypeVariable<?> typeparm: typeparms) {216if (!first)217sb.append(',');218sb.append(typeparm.getTypeName());219first = false;220}221sb.append('>');222}223224return sb.toString();225}226}227228/**229* Returns the {@code Class} object associated with the class or230* interface with the given string name. Invoking this method is231* equivalent to:232*233* <blockquote>234* {@code Class.forName(className, true, currentLoader)}235* </blockquote>236*237* where {@code currentLoader} denotes the defining class loader of238* the current class.239*240* <p> For example, the following code fragment returns the241* runtime {@code Class} descriptor for the class named242* {@code java.lang.Thread}:243*244* <blockquote>245* {@code Class t = Class.forName("java.lang.Thread")}246* </blockquote>247* <p>248* A call to {@code forName("X")} causes the class named249* {@code X} to be initialized.250*251* @param className the fully qualified name of the desired class.252* @return the {@code Class} object for the class with the253* specified name.254* @exception LinkageError if the linkage fails255* @exception ExceptionInInitializerError if the initialization provoked256* by this method fails257* @exception ClassNotFoundException if the class cannot be located258*/259@CallerSensitive260public static Class<?> forName(String className)261throws ClassNotFoundException {262Class<?> caller = Reflection.getCallerClass();263return forName0(className, true, ClassLoader.getClassLoader(caller), caller);264}265266267/**268* Returns the {@code Class} object associated with the class or269* interface with the given string name, using the given class loader.270* Given the fully qualified name for a class or interface (in the same271* format returned by {@code getName}) this method attempts to272* locate, load, and link the class or interface. The specified class273* loader is used to load the class or interface. If the parameter274* {@code loader} is null, the class is loaded through the bootstrap275* class loader. The class is initialized only if the276* {@code initialize} parameter is {@code true} and if it has277* not been initialized earlier.278*279* <p> If {@code name} denotes a primitive type or void, an attempt280* will be made to locate a user-defined class in the unnamed package whose281* name is {@code name}. Therefore, this method cannot be used to282* obtain any of the {@code Class} objects representing primitive283* types or void.284*285* <p> If {@code name} denotes an array class, the component type of286* the array class is loaded but not initialized.287*288* <p> For example, in an instance method the expression:289*290* <blockquote>291* {@code Class.forName("Foo")}292* </blockquote>293*294* is equivalent to:295*296* <blockquote>297* {@code Class.forName("Foo", true, this.getClass().getClassLoader())}298* </blockquote>299*300* Note that this method throws errors related to loading, linking or301* initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The302* Java Language Specification</em>.303* Note that this method does not check whether the requested class304* is accessible to its caller.305*306* <p> If the {@code loader} is {@code null}, and a security307* manager is present, and the caller's class loader is not null, then this308* method calls the security manager's {@code checkPermission} method309* with a {@code RuntimePermission("getClassLoader")} permission to310* ensure it's ok to access the bootstrap class loader.311*312* @param name fully qualified name of the desired class313* @param initialize if {@code true} the class will be initialized.314* See Section 12.4 of <em>The Java Language Specification</em>.315* @param loader class loader from which the class must be loaded316* @return class object representing the desired class317*318* @exception LinkageError if the linkage fails319* @exception ExceptionInInitializerError if the initialization provoked320* by this method fails321* @exception ClassNotFoundException if the class cannot be located by322* the specified class loader323*324* @see java.lang.Class#forName(String)325* @see java.lang.ClassLoader326* @since 1.2327*/328@CallerSensitive329public static Class<?> forName(String name, boolean initialize,330ClassLoader loader)331throws ClassNotFoundException332{333Class<?> caller = null;334SecurityManager sm = System.getSecurityManager();335if (sm != null) {336// Reflective call to get caller class is only needed if a security manager337// is present. Avoid the overhead of making this call otherwise.338caller = Reflection.getCallerClass();339if (sun.misc.VM.isSystemDomainLoader(loader)) {340ClassLoader ccl = ClassLoader.getClassLoader(caller);341if (!sun.misc.VM.isSystemDomainLoader(ccl)) {342sm.checkPermission(343SecurityConstants.GET_CLASSLOADER_PERMISSION);344}345}346}347return forName0(name, initialize, loader, caller);348}349350/** Called after security check for system loader access checks have been made. */351private static native Class<?> forName0(String name, boolean initialize,352ClassLoader loader,353Class<?> caller)354throws ClassNotFoundException;355356/**357* Creates a new instance of the class represented by this {@code Class}358* object. The class is instantiated as if by a {@code new}359* expression with an empty argument list. The class is initialized if it360* has not already been initialized.361*362* <p>Note that this method propagates any exception thrown by the363* nullary constructor, including a checked exception. Use of364* this method effectively bypasses the compile-time exception365* checking that would otherwise be performed by the compiler.366* The {@link367* java.lang.reflect.Constructor#newInstance(java.lang.Object...)368* Constructor.newInstance} method avoids this problem by wrapping369* any exception thrown by the constructor in a (checked) {@link370* java.lang.reflect.InvocationTargetException}.371*372* @return a newly allocated instance of the class represented by this373* object.374* @throws IllegalAccessException if the class or its nullary375* constructor is not accessible.376* @throws InstantiationException377* if this {@code Class} represents an abstract class,378* an interface, an array class, a primitive type, or void;379* or if the class has no nullary constructor;380* or if the instantiation fails for some other reason.381* @throws ExceptionInInitializerError if the initialization382* provoked by this method fails.383* @throws SecurityException384* If a security manager, <i>s</i>, is present and385* the caller's class loader is not the same as or an386* ancestor of the class loader for the current class and387* invocation of {@link SecurityManager#checkPackageAccess388* s.checkPackageAccess()} denies access to the package389* of this class.390*/391@CallerSensitive392public T newInstance()393throws InstantiationException, IllegalAccessException394{395if (System.getSecurityManager() != null) {396checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);397}398399// NOTE: the following code may not be strictly correct under400// the current Java memory model.401402// Constructor lookup403if (cachedConstructor == null) {404if (this == Class.class) {405throw new IllegalAccessException(406"Can not call newInstance() on the Class for java.lang.Class"407);408}409try {410Class<?>[] empty = {};411final Constructor<T> c = getConstructor0(empty, Member.DECLARED);412// Disable accessibility checks on the constructor413// since we have to do the security check here anyway414// (the stack depth is wrong for the Constructor's415// security check to work)416java.security.AccessController.doPrivileged(417new java.security.PrivilegedAction<Void>() {418public Void run() {419c.setAccessible(true);420return null;421}422});423cachedConstructor = c;424} catch (NoSuchMethodException e) {425throw (InstantiationException)426new InstantiationException(getName()).initCause(e);427}428}429Constructor<T> tmpConstructor = cachedConstructor;430// Security check (same as in java.lang.reflect.Constructor)431int modifiers = tmpConstructor.getModifiers();432if (!Reflection.quickCheckMemberAccess(this, modifiers)) {433Class<?> caller = Reflection.getCallerClass();434if (newInstanceCallerCache != caller) {435Reflection.ensureMemberAccess(caller, this, null, modifiers);436newInstanceCallerCache = caller;437}438}439// Run constructor440try {441return tmpConstructor.newInstance((Object[])null);442} catch (InvocationTargetException e) {443Unsafe.getUnsafe().throwException(e.getTargetException());444// Not reached445return null;446}447}448private volatile transient Constructor<T> cachedConstructor;449private volatile transient Class<?> newInstanceCallerCache;450451452/**453* Determines if the specified {@code Object} is assignment-compatible454* with the object represented by this {@code Class}. This method is455* the dynamic equivalent of the Java language {@code instanceof}456* operator. The method returns {@code true} if the specified457* {@code Object} argument is non-null and can be cast to the458* reference type represented by this {@code Class} object without459* raising a {@code ClassCastException.} It returns {@code false}460* otherwise.461*462* <p> Specifically, if this {@code Class} object represents a463* declared class, this method returns {@code true} if the specified464* {@code Object} argument is an instance of the represented class (or465* of any of its subclasses); it returns {@code false} otherwise. If466* this {@code Class} object represents an array class, this method467* returns {@code true} if the specified {@code Object} argument468* can be converted to an object of the array class by an identity469* conversion or by a widening reference conversion; it returns470* {@code false} otherwise. If this {@code Class} object471* represents an interface, this method returns {@code true} if the472* class or any superclass of the specified {@code Object} argument473* implements this interface; it returns {@code false} otherwise. If474* this {@code Class} object represents a primitive type, this method475* returns {@code false}.476*477* @param obj the object to check478* @return true if {@code obj} is an instance of this class479*480* @since JDK1.1481*/482public native boolean isInstance(Object obj);483484485/**486* Determines if the class or interface represented by this487* {@code Class} object is either the same as, or is a superclass or488* superinterface of, the class or interface represented by the specified489* {@code Class} parameter. It returns {@code true} if so;490* otherwise it returns {@code false}. If this {@code Class}491* object represents a primitive type, this method returns492* {@code true} if the specified {@code Class} parameter is493* exactly this {@code Class} object; otherwise it returns494* {@code false}.495*496* <p> Specifically, this method tests whether the type represented by the497* specified {@code Class} parameter can be converted to the type498* represented by this {@code Class} object via an identity conversion499* or via a widening reference conversion. See <em>The Java Language500* Specification</em>, sections 5.1.1 and 5.1.4 , for details.501*502* @param cls the {@code Class} object to be checked503* @return the {@code boolean} value indicating whether objects of the504* type {@code cls} can be assigned to objects of this class505* @exception NullPointerException if the specified Class parameter is506* null.507* @since JDK1.1508*/509public native boolean isAssignableFrom(Class<?> cls);510511512/**513* Determines if the specified {@code Class} object represents an514* interface type.515*516* @return {@code true} if this object represents an interface;517* {@code false} otherwise.518*/519public native boolean isInterface();520521522/**523* Determines if this {@code Class} object represents an array class.524*525* @return {@code true} if this object represents an array class;526* {@code false} otherwise.527* @since JDK1.1528*/529public native boolean isArray();530531532/**533* Determines if the specified {@code Class} object represents a534* primitive type.535*536* <p> There are nine predefined {@code Class} objects to represent537* the eight primitive types and void. These are created by the Java538* Virtual Machine, and have the same names as the primitive types that539* they represent, namely {@code boolean}, {@code byte},540* {@code char}, {@code short}, {@code int},541* {@code long}, {@code float}, and {@code double}.542*543* <p> These objects may only be accessed via the following public static544* final variables, and are the only {@code Class} objects for which545* this method returns {@code true}.546*547* @return true if and only if this class represents a primitive type548*549* @see java.lang.Boolean#TYPE550* @see java.lang.Character#TYPE551* @see java.lang.Byte#TYPE552* @see java.lang.Short#TYPE553* @see java.lang.Integer#TYPE554* @see java.lang.Long#TYPE555* @see java.lang.Float#TYPE556* @see java.lang.Double#TYPE557* @see java.lang.Void#TYPE558* @since JDK1.1559*/560public native boolean isPrimitive();561562/**563* Returns true if this {@code Class} object represents an annotation564* type. Note that if this method returns true, {@link #isInterface()}565* would also return true, as all annotation types are also interfaces.566*567* @return {@code true} if this class object represents an annotation568* type; {@code false} otherwise569* @since 1.5570*/571public boolean isAnnotation() {572return (getModifiers() & ANNOTATION) != 0;573}574575/**576* Returns {@code true} if this class is a synthetic class;577* returns {@code false} otherwise.578* @return {@code true} if and only if this class is a synthetic class as579* defined by the Java Language Specification.580* @jls 13.1 The Form of a Binary581* @since 1.5582*/583public boolean isSynthetic() {584return (getModifiers() & SYNTHETIC) != 0;585}586587/**588* Returns the name of the entity (class, interface, array class,589* primitive type, or void) represented by this {@code Class} object,590* as a {@code String}.591*592* <p> If this class object represents a reference type that is not an593* array type then the binary name of the class is returned, as specified594* by595* <cite>The Java™ Language Specification</cite>.596*597* <p> If this class object represents a primitive type or void, then the598* name returned is a {@code String} equal to the Java language599* keyword corresponding to the primitive type or void.600*601* <p> If this class object represents a class of arrays, then the internal602* form of the name consists of the name of the element type preceded by603* one or more '{@code [}' characters representing the depth of the array604* nesting. The encoding of element type names is as follows:605*606* <blockquote><table summary="Element types and encodings">607* <tr><th> Element Type <th> <th> Encoding608* <tr><td> boolean <td> <td align=center> Z609* <tr><td> byte <td> <td align=center> B610* <tr><td> char <td> <td align=center> C611* <tr><td> class or interface612* <td> <td align=center> L<i>classname</i>;613* <tr><td> double <td> <td align=center> D614* <tr><td> float <td> <td align=center> F615* <tr><td> int <td> <td align=center> I616* <tr><td> long <td> <td align=center> J617* <tr><td> short <td> <td align=center> S618* </table></blockquote>619*620* <p> The class or interface name <i>classname</i> is the binary name of621* the class specified above.622*623* <p> Examples:624* <blockquote><pre>625* String.class.getName()626* returns "java.lang.String"627* byte.class.getName()628* returns "byte"629* (new Object[3]).getClass().getName()630* returns "[Ljava.lang.Object;"631* (new int[3][4][5][6][7][8][9]).getClass().getName()632* returns "[[[[[[[I"633* </pre></blockquote>634*635* @return the name of the class or interface636* represented by this object.637*/638public String getName() {639String name = this.name;640if (name == null)641this.name = name = getName0();642return name;643}644645// cache the name to reduce the number of calls into the VM646private transient String name;647private native String getName0();648649/**650* Returns the class loader for the class. Some implementations may use651* null to represent the bootstrap class loader. This method will return652* null in such implementations if this class was loaded by the bootstrap653* class loader.654*655* <p> If a security manager is present, and the caller's class loader is656* not null and the caller's class loader is not the same as or an ancestor of657* the class loader for the class whose class loader is requested, then658* this method calls the security manager's {@code checkPermission}659* method with a {@code RuntimePermission("getClassLoader")}660* permission to ensure it's ok to access the class loader for the class.661*662* <p>If this object663* represents a primitive type or void, null is returned.664*665* @return the class loader that loaded the class or interface666* represented by this object.667* @throws SecurityException668* if a security manager exists and its669* {@code checkPermission} method denies670* access to the class loader for the class.671* @see java.lang.ClassLoader672* @see SecurityManager#checkPermission673* @see java.lang.RuntimePermission674*/675@CallerSensitive676public ClassLoader getClassLoader() {677ClassLoader cl = getClassLoader0();678if (cl == null)679return null;680SecurityManager sm = System.getSecurityManager();681if (sm != null) {682ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass());683}684return cl;685}686687// Package-private to allow ClassLoader access688ClassLoader getClassLoader0() { return classLoader; }689690// Initialized in JVM not by private constructor691// This field is filtered from reflection access, i.e. getDeclaredField692// will throw NoSuchFieldException693private final ClassLoader classLoader;694695/**696* Returns an array of {@code TypeVariable} objects that represent the697* type variables declared by the generic declaration represented by this698* {@code GenericDeclaration} object, in declaration order. Returns an699* array of length 0 if the underlying generic declaration declares no type700* variables.701*702* @return an array of {@code TypeVariable} objects that represent703* the type variables declared by this generic declaration704* @throws java.lang.reflect.GenericSignatureFormatError if the generic705* signature of this generic declaration does not conform to706* the format specified in707* <cite>The Java™ Virtual Machine Specification</cite>708* @since 1.5709*/710@SuppressWarnings("unchecked")711public TypeVariable<Class<T>>[] getTypeParameters() {712ClassRepository info = getGenericInfo();713if (info != null)714return (TypeVariable<Class<T>>[])info.getTypeParameters();715else716return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];717}718719720/**721* Returns the {@code Class} representing the superclass of the entity722* (class, interface, primitive type or void) represented by this723* {@code Class}. If this {@code Class} represents either the724* {@code Object} class, an interface, a primitive type, or void, then725* null is returned. If this object represents an array class then the726* {@code Class} object representing the {@code Object} class is727* returned.728*729* @return the superclass of the class represented by this object.730*/731public native Class<? super T> getSuperclass();732733734/**735* Returns the {@code Type} representing the direct superclass of736* the entity (class, interface, primitive type or void) represented by737* this {@code Class}.738*739* <p>If the superclass is a parameterized type, the {@code Type}740* object returned must accurately reflect the actual type741* parameters used in the source code. The parameterized type742* representing the superclass is created if it had not been743* created before. See the declaration of {@link744* java.lang.reflect.ParameterizedType ParameterizedType} for the745* semantics of the creation process for parameterized types. If746* this {@code Class} represents either the {@code Object}747* class, an interface, a primitive type, or void, then null is748* returned. If this object represents an array class then the749* {@code Class} object representing the {@code Object} class is750* returned.751*752* @throws java.lang.reflect.GenericSignatureFormatError if the generic753* class signature does not conform to the format specified in754* <cite>The Java™ Virtual Machine Specification</cite>755* @throws TypeNotPresentException if the generic superclass756* refers to a non-existent type declaration757* @throws java.lang.reflect.MalformedParameterizedTypeException if the758* generic superclass refers to a parameterized type that cannot be759* instantiated for any reason760* @return the superclass of the class represented by this object761* @since 1.5762*/763public Type getGenericSuperclass() {764ClassRepository info = getGenericInfo();765if (info == null) {766return getSuperclass();767}768769// Historical irregularity:770// Generic signature marks interfaces with superclass = Object771// but this API returns null for interfaces772if (isInterface()) {773return null;774}775776return info.getSuperclass();777}778779/**780* Gets the package for this class. The class loader of this class is used781* to find the package. If the class was loaded by the bootstrap class782* loader the set of packages loaded from CLASSPATH is searched to find the783* package of the class. Null is returned if no package object was created784* by the class loader of this class.785*786* <p> Packages have attributes for versions and specifications only if the787* information was defined in the manifests that accompany the classes, and788* if the class loader created the package instance with the attributes789* from the manifest.790*791* @return the package of the class, or null if no package792* information is available from the archive or codebase.793*/794public Package getPackage() {795return Package.getPackage(this);796}797798799/**800* Determines the interfaces implemented by the class or interface801* represented by this object.802*803* <p> If this object represents a class, the return value is an array804* containing objects representing all interfaces implemented by the805* class. The order of the interface objects in the array corresponds to806* the order of the interface names in the {@code implements} clause807* of the declaration of the class represented by this object. For808* example, given the declaration:809* <blockquote>810* {@code class Shimmer implements FloorWax, DessertTopping { ... }}811* </blockquote>812* suppose the value of {@code s} is an instance of813* {@code Shimmer}; the value of the expression:814* <blockquote>815* {@code s.getClass().getInterfaces()[0]}816* </blockquote>817* is the {@code Class} object that represents interface818* {@code FloorWax}; and the value of:819* <blockquote>820* {@code s.getClass().getInterfaces()[1]}821* </blockquote>822* is the {@code Class} object that represents interface823* {@code DessertTopping}.824*825* <p> If this object represents an interface, the array contains objects826* representing all interfaces extended by the interface. The order of the827* interface objects in the array corresponds to the order of the interface828* names in the {@code extends} clause of the declaration of the829* interface represented by this object.830*831* <p> If this object represents a class or interface that implements no832* interfaces, the method returns an array of length 0.833*834* <p> If this object represents a primitive type or void, the method835* returns an array of length 0.836*837* <p> If this {@code Class} object represents an array type, the838* interfaces {@code Cloneable} and {@code java.io.Serializable} are839* returned in that order.840*841* @return an array of interfaces implemented by this class.842*/843public Class<?>[] getInterfaces() {844ReflectionData<T> rd = reflectionData();845if (rd == null) {846// no cloning required847return getInterfaces0();848} else {849Class<?>[] interfaces = rd.interfaces;850if (interfaces == null) {851interfaces = getInterfaces0();852rd.interfaces = interfaces;853}854// defensively copy before handing over to user code855return interfaces.clone();856}857}858859private native Class<?>[] getInterfaces0();860861/**862* Returns the {@code Type}s representing the interfaces863* directly implemented by the class or interface represented by864* this object.865*866* <p>If a superinterface is a parameterized type, the867* {@code Type} object returned for it must accurately reflect868* the actual type parameters used in the source code. The869* parameterized type representing each superinterface is created870* if it had not been created before. See the declaration of871* {@link java.lang.reflect.ParameterizedType ParameterizedType}872* for the semantics of the creation process for parameterized873* types.874*875* <p> If this object represents a class, the return value is an876* array containing objects representing all interfaces877* implemented by the class. The order of the interface objects in878* the array corresponds to the order of the interface names in879* the {@code implements} clause of the declaration of the class880* represented by this object. In the case of an array class, the881* interfaces {@code Cloneable} and {@code Serializable} are882* returned in that order.883*884* <p>If this object represents an interface, the array contains885* objects representing all interfaces directly extended by the886* interface. The order of the interface objects in the array887* corresponds to the order of the interface names in the888* {@code extends} clause of the declaration of the interface889* represented by this object.890*891* <p>If this object represents a class or interface that892* implements no interfaces, the method returns an array of length893* 0.894*895* <p>If this object represents a primitive type or void, the896* method returns an array of length 0.897*898* @throws java.lang.reflect.GenericSignatureFormatError899* if the generic class signature does not conform to the format900* specified in901* <cite>The Java™ Virtual Machine Specification</cite>902* @throws TypeNotPresentException if any of the generic903* superinterfaces refers to a non-existent type declaration904* @throws java.lang.reflect.MalformedParameterizedTypeException905* if any of the generic superinterfaces refer to a parameterized906* type that cannot be instantiated for any reason907* @return an array of interfaces implemented by this class908* @since 1.5909*/910public Type[] getGenericInterfaces() {911ClassRepository info = getGenericInfo();912return (info == null) ? getInterfaces() : info.getSuperInterfaces();913}914915916/**917* Returns the {@code Class} representing the component type of an918* array. If this class does not represent an array class this method919* returns null.920*921* @return the {@code Class} representing the component type of this922* class if this class is an array923* @see java.lang.reflect.Array924* @since JDK1.1925*/926public native Class<?> getComponentType();927928929/**930* Returns the Java language modifiers for this class or interface, encoded931* in an integer. The modifiers consist of the Java Virtual Machine's932* constants for {@code public}, {@code protected},933* {@code private}, {@code final}, {@code static},934* {@code abstract} and {@code interface}; they should be decoded935* using the methods of class {@code Modifier}.936*937* <p> If the underlying class is an array class, then its938* {@code public}, {@code private} and {@code protected}939* modifiers are the same as those of its component type. If this940* {@code Class} represents a primitive type or void, its941* {@code public} modifier is always {@code true}, and its942* {@code protected} and {@code private} modifiers are always943* {@code false}. If this object represents an array class, a944* primitive type or void, then its {@code final} modifier is always945* {@code true} and its interface modifier is always946* {@code false}. The values of its other modifiers are not determined947* by this specification.948*949* <p> The modifier encodings are defined in <em>The Java Virtual Machine950* Specification</em>, table 4.1.951*952* @return the {@code int} representing the modifiers for this class953* @see java.lang.reflect.Modifier954* @since JDK1.1955*/956public native int getModifiers();957958959/**960* Gets the signers of this class.961*962* @return the signers of this class, or null if there are no signers. In963* particular, this method returns null if this object represents964* a primitive type or void.965* @since JDK1.1966*/967public native Object[] getSigners();968969970/**971* Set the signers of this class.972*/973native void setSigners(Object[] signers);974975976/**977* If this {@code Class} object represents a local or anonymous978* class within a method, returns a {@link979* java.lang.reflect.Method Method} object representing the980* immediately enclosing method of the underlying class. Returns981* {@code null} otherwise.982*983* In particular, this method returns {@code null} if the underlying984* class is a local or anonymous class immediately enclosed by a type985* declaration, instance initializer or static initializer.986*987* @return the immediately enclosing method of the underlying class, if988* that class is a local or anonymous class; otherwise {@code null}.989*990* @throws SecurityException991* If a security manager, <i>s</i>, is present and any of the992* following conditions is met:993*994* <ul>995*996* <li> the caller's class loader is not the same as the997* class loader of the enclosing class and invocation of998* {@link SecurityManager#checkPermission999* s.checkPermission} method with1000* {@code RuntimePermission("accessDeclaredMembers")}1001* denies access to the methods within the enclosing class1002*1003* <li> the caller's class loader is not the same as or an1004* ancestor of the class loader for the enclosing class and1005* invocation of {@link SecurityManager#checkPackageAccess1006* s.checkPackageAccess()} denies access to the package1007* of the enclosing class1008*1009* </ul>1010* @since 1.51011*/1012@CallerSensitive1013public Method getEnclosingMethod() throws SecurityException {1014EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();10151016if (enclosingInfo == null)1017return null;1018else {1019if (!enclosingInfo.isMethod())1020return null;10211022MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),1023getFactory());1024Class<?> returnType = toClass(typeInfo.getReturnType());1025Type [] parameterTypes = typeInfo.getParameterTypes();1026Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];10271028// Convert Types to Classes; returned types *should*1029// be class objects since the methodDescriptor's used1030// don't have generics information1031for(int i = 0; i < parameterClasses.length; i++)1032parameterClasses[i] = toClass(parameterTypes[i]);10331034// Perform access check1035Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();1036enclosingCandidate.checkMemberAccess(Member.DECLARED,1037Reflection.getCallerClass(), true);1038/*1039* Loop over all declared methods; match method name,1040* number of and type of parameters, *and* return1041* type. Matching return type is also necessary1042* because of covariant returns, etc.1043*/1044for(Method m: enclosingCandidate.getDeclaredMethods()) {1045if (m.getName().equals(enclosingInfo.getName()) ) {1046Class<?>[] candidateParamClasses = m.getParameterTypes();1047if (candidateParamClasses.length == parameterClasses.length) {1048boolean matches = true;1049for(int i = 0; i < candidateParamClasses.length; i++) {1050if (!candidateParamClasses[i].equals(parameterClasses[i])) {1051matches = false;1052break;1053}1054}10551056if (matches) { // finally, check return type1057if (m.getReturnType().equals(returnType) )1058return m;1059}1060}1061}1062}10631064throw new InternalError("Enclosing method not found");1065}1066}10671068private native Object[] getEnclosingMethod0();10691070private EnclosingMethodInfo getEnclosingMethodInfo() {1071Object[] enclosingInfo = getEnclosingMethod0();1072if (enclosingInfo == null)1073return null;1074else {1075return new EnclosingMethodInfo(enclosingInfo);1076}1077}10781079private final static class EnclosingMethodInfo {1080private Class<?> enclosingClass;1081private String name;1082private String descriptor;10831084private EnclosingMethodInfo(Object[] enclosingInfo) {1085if (enclosingInfo.length != 3)1086throw new InternalError("Malformed enclosing method information");1087try {1088// The array is expected to have three elements:10891090// the immediately enclosing class1091enclosingClass = (Class<?>) enclosingInfo[0];1092assert(enclosingClass != null);10931094// the immediately enclosing method or constructor's1095// name (can be null).1096name = (String) enclosingInfo[1];10971098// the immediately enclosing method or constructor's1099// descriptor (null iff name is).1100descriptor = (String) enclosingInfo[2];1101assert((name != null && descriptor != null) || name == descriptor);1102} catch (ClassCastException cce) {1103throw new InternalError("Invalid type in enclosing method information", cce);1104}1105}11061107boolean isPartial() {1108return enclosingClass == null || name == null || descriptor == null;1109}11101111boolean isConstructor() { return !isPartial() && "<init>".equals(name); }11121113boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }11141115Class<?> getEnclosingClass() { return enclosingClass; }11161117String getName() { return name; }11181119String getDescriptor() { return descriptor; }11201121}11221123private static Class<?> toClass(Type o) {1124if (o instanceof GenericArrayType)1125return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),11260)1127.getClass();1128return (Class<?>)o;1129}11301131/**1132* If this {@code Class} object represents a local or anonymous1133* class within a constructor, returns a {@link1134* java.lang.reflect.Constructor Constructor} object representing1135* the immediately enclosing constructor of the underlying1136* class. Returns {@code null} otherwise. In particular, this1137* method returns {@code null} if the underlying class is a local1138* or anonymous class immediately enclosed by a type declaration,1139* instance initializer or static initializer.1140*1141* @return the immediately enclosing constructor of the underlying class, if1142* that class is a local or anonymous class; otherwise {@code null}.1143* @throws SecurityException1144* If a security manager, <i>s</i>, is present and any of the1145* following conditions is met:1146*1147* <ul>1148*1149* <li> the caller's class loader is not the same as the1150* class loader of the enclosing class and invocation of1151* {@link SecurityManager#checkPermission1152* s.checkPermission} method with1153* {@code RuntimePermission("accessDeclaredMembers")}1154* denies access to the constructors within the enclosing class1155*1156* <li> the caller's class loader is not the same as or an1157* ancestor of the class loader for the enclosing class and1158* invocation of {@link SecurityManager#checkPackageAccess1159* s.checkPackageAccess()} denies access to the package1160* of the enclosing class1161*1162* </ul>1163* @since 1.51164*/1165@CallerSensitive1166public Constructor<?> getEnclosingConstructor() throws SecurityException {1167EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();11681169if (enclosingInfo == null)1170return null;1171else {1172if (!enclosingInfo.isConstructor())1173return null;11741175ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),1176getFactory());1177Type [] parameterTypes = typeInfo.getParameterTypes();1178Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];11791180// Convert Types to Classes; returned types *should*1181// be class objects since the methodDescriptor's used1182// don't have generics information1183for(int i = 0; i < parameterClasses.length; i++)1184parameterClasses[i] = toClass(parameterTypes[i]);11851186// Perform access check1187Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();1188enclosingCandidate.checkMemberAccess(Member.DECLARED,1189Reflection.getCallerClass(), true);1190/*1191* Loop over all declared constructors; match number1192* of and type of parameters.1193*/1194for(Constructor<?> c: enclosingCandidate.getDeclaredConstructors()) {1195Class<?>[] candidateParamClasses = c.getParameterTypes();1196if (candidateParamClasses.length == parameterClasses.length) {1197boolean matches = true;1198for(int i = 0; i < candidateParamClasses.length; i++) {1199if (!candidateParamClasses[i].equals(parameterClasses[i])) {1200matches = false;1201break;1202}1203}12041205if (matches)1206return c;1207}1208}12091210throw new InternalError("Enclosing constructor not found");1211}1212}121312141215/**1216* If the class or interface represented by this {@code Class} object1217* is a member of another class, returns the {@code Class} object1218* representing the class in which it was declared. This method returns1219* null if this class or interface is not a member of any other class. If1220* this {@code Class} object represents an array class, a primitive1221* type, or void,then this method returns null.1222*1223* @return the declaring class for this class1224* @throws SecurityException1225* If a security manager, <i>s</i>, is present and the caller's1226* class loader is not the same as or an ancestor of the class1227* loader for the declaring class and invocation of {@link1228* SecurityManager#checkPackageAccess s.checkPackageAccess()}1229* denies access to the package of the declaring class1230* @since JDK1.11231*/1232@CallerSensitive1233public Class<?> getDeclaringClass() throws SecurityException {1234final Class<?> candidate = getDeclaringClass0();12351236if (candidate != null)1237candidate.checkPackageAccess(1238ClassLoader.getClassLoader(Reflection.getCallerClass()), true);1239return candidate;1240}12411242private native Class<?> getDeclaringClass0();124312441245/**1246* Returns the immediately enclosing class of the underlying1247* class. If the underlying class is a top level class this1248* method returns {@code null}.1249* @return the immediately enclosing class of the underlying class1250* @exception SecurityException1251* If a security manager, <i>s</i>, is present and the caller's1252* class loader is not the same as or an ancestor of the class1253* loader for the enclosing class and invocation of {@link1254* SecurityManager#checkPackageAccess s.checkPackageAccess()}1255* denies access to the package of the enclosing class1256* @since 1.51257*/1258@CallerSensitive1259public Class<?> getEnclosingClass() throws SecurityException {1260// There are five kinds of classes (or interfaces):1261// a) Top level classes1262// b) Nested classes (static member classes)1263// c) Inner classes (non-static member classes)1264// d) Local classes (named classes declared within a method)1265// e) Anonymous classes126612671268// JVM Spec 4.8.6: A class must have an EnclosingMethod1269// attribute if and only if it is a local class or an1270// anonymous class.1271EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();1272Class<?> enclosingCandidate;12731274if (enclosingInfo == null) {1275// This is a top level or a nested class or an inner class (a, b, or c)1276enclosingCandidate = getDeclaringClass();1277} else {1278Class<?> enclosingClass = enclosingInfo.getEnclosingClass();1279// This is a local class or an anonymous class (d or e)1280if (enclosingClass == this || enclosingClass == null)1281throw new InternalError("Malformed enclosing method information");1282else1283enclosingCandidate = enclosingClass;1284}12851286if (enclosingCandidate != null)1287enclosingCandidate.checkPackageAccess(1288ClassLoader.getClassLoader(Reflection.getCallerClass()), true);1289return enclosingCandidate;1290}12911292/**1293* Returns the simple name of the underlying class as given in the1294* source code. Returns an empty string if the underlying class is1295* anonymous.1296*1297* <p>The simple name of an array is the simple name of the1298* component type with "[]" appended. In particular the simple1299* name of an array whose component type is anonymous is "[]".1300*1301* @return the simple name of the underlying class1302* @since 1.51303*/1304public String getSimpleName() {1305if (isArray())1306return getComponentType().getSimpleName()+"[]";13071308String simpleName = getSimpleBinaryName();1309if (simpleName == null) { // top level class1310simpleName = getName();1311return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name1312}1313// According to JLS3 "Binary Compatibility" (13.1) the binary1314// name of non-package classes (not top level) is the binary1315// name of the immediately enclosing class followed by a '$' followed by:1316// (for nested and inner classes): the simple name.1317// (for local classes): 1 or more digits followed by the simple name.1318// (for anonymous classes): 1 or more digits.13191320// Since getSimpleBinaryName() will strip the binary name of1321// the immediatly enclosing class, we are now looking at a1322// string that matches the regular expression "\$[0-9]*"1323// followed by a simple name (considering the simple of an1324// anonymous class to be the empty string).13251326// Remove leading "\$[0-9]*" from the name1327int length = simpleName.length();1328if (length < 1 || simpleName.charAt(0) != '$')1329throw new InternalError("Malformed class name");1330int index = 1;1331while (index < length && isAsciiDigit(simpleName.charAt(index)))1332index++;1333// Eventually, this is the empty string iff this is an anonymous class1334return simpleName.substring(index);1335}13361337/**1338* Return an informative string for the name of this type.1339*1340* @return an informative string for the name of this type1341* @since 1.81342*/1343public String getTypeName() {1344if (isArray()) {1345try {1346Class<?> cl = this;1347int dimensions = 0;1348while (cl.isArray()) {1349dimensions++;1350cl = cl.getComponentType();1351}1352StringBuilder sb = new StringBuilder();1353sb.append(cl.getName());1354for (int i = 0; i < dimensions; i++) {1355sb.append("[]");1356}1357return sb.toString();1358} catch (Throwable e) { /*FALLTHRU*/ }1359}1360return getName();1361}13621363/**1364* Character.isDigit answers {@code true} to some non-ascii1365* digits. This one does not.1366*/1367private static boolean isAsciiDigit(char c) {1368return '0' <= c && c <= '9';1369}13701371/**1372* Returns the canonical name of the underlying class as1373* defined by the Java Language Specification. Returns null if1374* the underlying class does not have a canonical name (i.e., if1375* it is a local or anonymous class or an array whose component1376* type does not have a canonical name).1377* @return the canonical name of the underlying class if it exists, and1378* {@code null} otherwise.1379* @since 1.51380*/1381public String getCanonicalName() {1382if (isArray()) {1383String canonicalName = getComponentType().getCanonicalName();1384if (canonicalName != null)1385return canonicalName + "[]";1386else1387return null;1388}1389if (isLocalOrAnonymousClass())1390return null;1391Class<?> enclosingClass = getEnclosingClass();1392if (enclosingClass == null) { // top level class1393return getName();1394} else {1395String enclosingName = enclosingClass.getCanonicalName();1396if (enclosingName == null)1397return null;1398return enclosingName + "." + getSimpleName();1399}1400}14011402/**1403* Returns {@code true} if and only if the underlying class1404* is an anonymous class.1405*1406* @return {@code true} if and only if this class is an anonymous class.1407* @since 1.51408*/1409public boolean isAnonymousClass() {1410return "".equals(getSimpleName());1411}14121413/**1414* Returns {@code true} if and only if the underlying class1415* is a local class.1416*1417* @return {@code true} if and only if this class is a local class.1418* @since 1.51419*/1420public boolean isLocalClass() {1421return isLocalOrAnonymousClass() && !isAnonymousClass();1422}14231424/**1425* Returns {@code true} if and only if the underlying class1426* is a member class.1427*1428* @return {@code true} if and only if this class is a member class.1429* @since 1.51430*/1431public boolean isMemberClass() {1432return getSimpleBinaryName() != null && !isLocalOrAnonymousClass();1433}14341435/**1436* Returns the "simple binary name" of the underlying class, i.e.,1437* the binary name without the leading enclosing class name.1438* Returns {@code null} if the underlying class is a top level1439* class.1440*/1441private String getSimpleBinaryName() {1442Class<?> enclosingClass = getEnclosingClass();1443if (enclosingClass == null) // top level class1444return null;1445// Otherwise, strip the enclosing class' name1446try {1447return getName().substring(enclosingClass.getName().length());1448} catch (IndexOutOfBoundsException ex) {1449throw new InternalError("Malformed class name", ex);1450}1451}14521453/**1454* Returns {@code true} if this is a local class or an anonymous1455* class. Returns {@code false} otherwise.1456*/1457private boolean isLocalOrAnonymousClass() {1458// JVM Spec 4.8.6: A class must have an EnclosingMethod1459// attribute if and only if it is a local class or an1460// anonymous class.1461return getEnclosingMethodInfo() != null;1462}14631464/**1465* Returns an array containing {@code Class} objects representing all1466* the public classes and interfaces that are members of the class1467* represented by this {@code Class} object. This includes public1468* class and interface members inherited from superclasses and public class1469* and interface members declared by the class. This method returns an1470* array of length 0 if this {@code Class} object has no public member1471* classes or interfaces. This method also returns an array of length 0 if1472* this {@code Class} object represents a primitive type, an array1473* class, or void.1474*1475* @return the array of {@code Class} objects representing the public1476* members of this class1477* @throws SecurityException1478* If a security manager, <i>s</i>, is present and1479* the caller's class loader is not the same as or an1480* ancestor of the class loader for the current class and1481* invocation of {@link SecurityManager#checkPackageAccess1482* s.checkPackageAccess()} denies access to the package1483* of this class.1484*1485* @since JDK1.11486*/1487@CallerSensitive1488public Class<?>[] getClasses() {1489checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);14901491// Privileged so this implementation can look at DECLARED classes,1492// something the caller might not have privilege to do. The code here1493// is allowed to look at DECLARED classes because (1) it does not hand1494// out anything other than public members and (2) public member access1495// has already been ok'd by the SecurityManager.14961497return java.security.AccessController.doPrivileged(1498new java.security.PrivilegedAction<Class<?>[]>() {1499public Class<?>[] run() {1500List<Class<?>> list = new ArrayList<>();1501Class<?> currentClass = Class.this;1502while (currentClass != null) {1503Class<?>[] members = currentClass.getDeclaredClasses();1504for (int i = 0; i < members.length; i++) {1505if (Modifier.isPublic(members[i].getModifiers())) {1506list.add(members[i]);1507}1508}1509currentClass = currentClass.getSuperclass();1510}1511return list.toArray(new Class<?>[0]);1512}1513});1514}151515161517/**1518* Returns an array containing {@code Field} objects reflecting all1519* the accessible public fields of the class or interface represented by1520* this {@code Class} object.1521*1522* <p> If this {@code Class} object represents a class or interface with no1523* no accessible public fields, then this method returns an array of length1524* 0.1525*1526* <p> If this {@code Class} object represents a class, then this method1527* returns the public fields of the class and of all its superclasses.1528*1529* <p> If this {@code Class} object represents an interface, then this1530* method returns the fields of the interface and of all its1531* superinterfaces.1532*1533* <p> If this {@code Class} object represents an array type, a primitive1534* type, or void, then this method returns an array of length 0.1535*1536* <p> The elements in the returned array are not sorted and are not in any1537* particular order.1538*1539* @return the array of {@code Field} objects representing the1540* public fields1541* @throws SecurityException1542* If a security manager, <i>s</i>, is present and1543* the caller's class loader is not the same as or an1544* ancestor of the class loader for the current class and1545* invocation of {@link SecurityManager#checkPackageAccess1546* s.checkPackageAccess()} denies access to the package1547* of this class.1548*1549* @since JDK1.11550* @jls 8.2 Class Members1551* @jls 8.3 Field Declarations1552*/1553@CallerSensitive1554public Field[] getFields() throws SecurityException {1555checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);1556return copyFields(privateGetPublicFields(null));1557}155815591560/**1561* Returns an array containing {@code Method} objects reflecting all the1562* public methods of the class or interface represented by this {@code1563* Class} object, including those declared by the class or interface and1564* those inherited from superclasses and superinterfaces.1565*1566* <p> If this {@code Class} object represents a type that has multiple1567* public methods with the same name and parameter types, but different1568* return types, then the returned array has a {@code Method} object for1569* each such method.1570*1571* <p> If this {@code Class} object represents a type with a class1572* initialization method {@code <clinit>}, then the returned array does1573* <em>not</em> have a corresponding {@code Method} object.1574*1575* <p> If this {@code Class} object represents an array type, then the1576* returned array has a {@code Method} object for each of the public1577* methods inherited by the array type from {@code Object}. It does not1578* contain a {@code Method} object for {@code clone()}.1579*1580* <p> If this {@code Class} object represents an interface then the1581* returned array does not contain any implicitly declared methods from1582* {@code Object}. Therefore, if no methods are explicitly declared in1583* this interface or any of its superinterfaces then the returned array1584* has length 0. (Note that a {@code Class} object which represents a class1585* always has public methods, inherited from {@code Object}.)1586*1587* <p> If this {@code Class} object represents a primitive type or void,1588* then the returned array has length 0.1589*1590* <p> Static methods declared in superinterfaces of the class or interface1591* represented by this {@code Class} object are not considered members of1592* the class or interface.1593*1594* <p> The elements in the returned array are not sorted and are not in any1595* particular order.1596*1597* @return the array of {@code Method} objects representing the1598* public methods of this class1599* @throws SecurityException1600* If a security manager, <i>s</i>, is present and1601* the caller's class loader is not the same as or an1602* ancestor of the class loader for the current class and1603* invocation of {@link SecurityManager#checkPackageAccess1604* s.checkPackageAccess()} denies access to the package1605* of this class.1606*1607* @jls 8.2 Class Members1608* @jls 8.4 Method Declarations1609* @since JDK1.11610*/1611@CallerSensitive1612public Method[] getMethods() throws SecurityException {1613checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);1614return copyMethods(privateGetPublicMethods());1615}161616171618/**1619* Returns an array containing {@code Constructor} objects reflecting1620* all the public constructors of the class represented by this1621* {@code Class} object. An array of length 0 is returned if the1622* class has no public constructors, or if the class is an array class, or1623* if the class reflects a primitive type or void.1624*1625* Note that while this method returns an array of {@code1626* Constructor<T>} objects (that is an array of constructors from1627* this class), the return type of this method is {@code1628* Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as1629* might be expected. This less informative return type is1630* necessary since after being returned from this method, the1631* array could be modified to hold {@code Constructor} objects for1632* different classes, which would violate the type guarantees of1633* {@code Constructor<T>[]}.1634*1635* @return the array of {@code Constructor} objects representing the1636* public constructors of this class1637* @throws SecurityException1638* If a security manager, <i>s</i>, is present and1639* the caller's class loader is not the same as or an1640* ancestor of the class loader for the current class and1641* invocation of {@link SecurityManager#checkPackageAccess1642* s.checkPackageAccess()} denies access to the package1643* of this class.1644*1645* @since JDK1.11646*/1647@CallerSensitive1648public Constructor<?>[] getConstructors() throws SecurityException {1649checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);1650return copyConstructors(privateGetDeclaredConstructors(true));1651}165216531654/**1655* Returns a {@code Field} object that reflects the specified public member1656* field of the class or interface represented by this {@code Class}1657* object. The {@code name} parameter is a {@code String} specifying the1658* simple name of the desired field.1659*1660* <p> The field to be reflected is determined by the algorithm that1661* follows. Let C be the class or interface represented by this object:1662*1663* <OL>1664* <LI> If C declares a public field with the name specified, that is the1665* field to be reflected.</LI>1666* <LI> If no field was found in step 1 above, this algorithm is applied1667* recursively to each direct superinterface of C. The direct1668* superinterfaces are searched in the order they were declared.</LI>1669* <LI> If no field was found in steps 1 and 2 above, and C has a1670* superclass S, then this algorithm is invoked recursively upon S.1671* If C has no superclass, then a {@code NoSuchFieldException}1672* is thrown.</LI>1673* </OL>1674*1675* <p> If this {@code Class} object represents an array type, then this1676* method does not find the {@code length} field of the array type.1677*1678* @param name the field name1679* @return the {@code Field} object of this class specified by1680* {@code name}1681* @throws NoSuchFieldException if a field with the specified name is1682* not found.1683* @throws NullPointerException if {@code name} is {@code null}1684* @throws SecurityException1685* If a security manager, <i>s</i>, is present and1686* the caller's class loader is not the same as or an1687* ancestor of the class loader for the current class and1688* invocation of {@link SecurityManager#checkPackageAccess1689* s.checkPackageAccess()} denies access to the package1690* of this class.1691*1692* @since JDK1.11693* @jls 8.2 Class Members1694* @jls 8.3 Field Declarations1695*/1696@CallerSensitive1697public Field getField(String name)1698throws NoSuchFieldException, SecurityException {1699checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);1700Field field = getField0(name);1701if (field == null) {1702throw new NoSuchFieldException(name);1703}1704return field;1705}170617071708/**1709* Returns a {@code Method} object that reflects the specified public1710* member method of the class or interface represented by this1711* {@code Class} object. The {@code name} parameter is a1712* {@code String} specifying the simple name of the desired method. The1713* {@code parameterTypes} parameter is an array of {@code Class}1714* objects that identify the method's formal parameter types, in declared1715* order. If {@code parameterTypes} is {@code null}, it is1716* treated as if it were an empty array.1717*1718* <p> If the {@code name} is "{@code <init>}" or "{@code <clinit>}" a1719* {@code NoSuchMethodException} is raised. Otherwise, the method to1720* be reflected is determined by the algorithm that follows. Let C be the1721* class or interface represented by this object:1722* <OL>1723* <LI> C is searched for a <I>matching method</I>, as defined below. If a1724* matching method is found, it is reflected.</LI>1725* <LI> If no matching method is found by step 1 then:1726* <OL TYPE="a">1727* <LI> If C is a class other than {@code Object}, then this algorithm is1728* invoked recursively on the superclass of C.</LI>1729* <LI> If C is the class {@code Object}, or if C is an interface, then1730* the superinterfaces of C (if any) are searched for a matching1731* method. If any such method is found, it is reflected.</LI>1732* </OL></LI>1733* </OL>1734*1735* <p> To find a matching method in a class or interface C: If C1736* declares exactly one public method with the specified name and exactly1737* the same formal parameter types, that is the method reflected. If more1738* than one such method is found in C, and one of these methods has a1739* return type that is more specific than any of the others, that method is1740* reflected; otherwise one of the methods is chosen arbitrarily.1741*1742* <p>Note that there may be more than one matching method in a1743* class because while the Java language forbids a class to1744* declare multiple methods with the same signature but different1745* return types, the Java virtual machine does not. This1746* increased flexibility in the virtual machine can be used to1747* implement various language features. For example, covariant1748* returns can be implemented with {@linkplain1749* java.lang.reflect.Method#isBridge bridge methods}; the bridge1750* method and the method being overridden would have the same1751* signature but different return types.1752*1753* <p> If this {@code Class} object represents an array type, then this1754* method does not find the {@code clone()} method.1755*1756* <p> Static methods declared in superinterfaces of the class or interface1757* represented by this {@code Class} object are not considered members of1758* the class or interface.1759*1760* @param name the name of the method1761* @param parameterTypes the list of parameters1762* @return the {@code Method} object that matches the specified1763* {@code name} and {@code parameterTypes}1764* @throws NoSuchMethodException if a matching method is not found1765* or if the name is "<init>"or "<clinit>".1766* @throws NullPointerException if {@code name} is {@code null}1767* @throws SecurityException1768* If a security manager, <i>s</i>, is present and1769* the caller's class loader is not the same as or an1770* ancestor of the class loader for the current class and1771* invocation of {@link SecurityManager#checkPackageAccess1772* s.checkPackageAccess()} denies access to the package1773* of this class.1774*1775* @jls 8.2 Class Members1776* @jls 8.4 Method Declarations1777* @since JDK1.11778*/1779@CallerSensitive1780public Method getMethod(String name, Class<?>... parameterTypes)1781throws NoSuchMethodException, SecurityException {1782checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);1783Method method = getMethod0(name, parameterTypes, true);1784if (method == null) {1785throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));1786}1787return method;1788}178917901791/**1792* Returns a {@code Constructor} object that reflects the specified1793* public constructor of the class represented by this {@code Class}1794* object. The {@code parameterTypes} parameter is an array of1795* {@code Class} objects that identify the constructor's formal1796* parameter types, in declared order.1797*1798* If this {@code Class} object represents an inner class1799* declared in a non-static context, the formal parameter types1800* include the explicit enclosing instance as the first parameter.1801*1802* <p> The constructor to reflect is the public constructor of the class1803* represented by this {@code Class} object whose formal parameter1804* types match those specified by {@code parameterTypes}.1805*1806* @param parameterTypes the parameter array1807* @return the {@code Constructor} object of the public constructor that1808* matches the specified {@code parameterTypes}1809* @throws NoSuchMethodException if a matching method is not found.1810* @throws SecurityException1811* If a security manager, <i>s</i>, is present and1812* the caller's class loader is not the same as or an1813* ancestor of the class loader for the current class and1814* invocation of {@link SecurityManager#checkPackageAccess1815* s.checkPackageAccess()} denies access to the package1816* of this class.1817*1818* @since JDK1.11819*/1820@CallerSensitive1821public Constructor<T> getConstructor(Class<?>... parameterTypes)1822throws NoSuchMethodException, SecurityException {1823checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);1824return getConstructor0(parameterTypes, Member.PUBLIC);1825}182618271828/**1829* Returns an array of {@code Class} objects reflecting all the1830* classes and interfaces declared as members of the class represented by1831* this {@code Class} object. This includes public, protected, default1832* (package) access, and private classes and interfaces declared by the1833* class, but excludes inherited classes and interfaces. This method1834* returns an array of length 0 if the class declares no classes or1835* interfaces as members, or if this {@code Class} object represents a1836* primitive type, an array class, or void.1837*1838* @return the array of {@code Class} objects representing all the1839* declared members of this class1840* @throws SecurityException1841* If a security manager, <i>s</i>, is present and any of the1842* following conditions is met:1843*1844* <ul>1845*1846* <li> the caller's class loader is not the same as the1847* class loader of this class and invocation of1848* {@link SecurityManager#checkPermission1849* s.checkPermission} method with1850* {@code RuntimePermission("accessDeclaredMembers")}1851* denies access to the declared classes within this class1852*1853* <li> the caller's class loader is not the same as or an1854* ancestor of the class loader for the current class and1855* invocation of {@link SecurityManager#checkPackageAccess1856* s.checkPackageAccess()} denies access to the package1857* of this class1858*1859* </ul>1860*1861* @since JDK1.11862*/1863@CallerSensitive1864public Class<?>[] getDeclaredClasses() throws SecurityException {1865checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), false);1866return getDeclaredClasses0();1867}186818691870/**1871* Returns an array of {@code Field} objects reflecting all the fields1872* declared by the class or interface represented by this1873* {@code Class} object. This includes public, protected, default1874* (package) access, and private fields, but excludes inherited fields.1875*1876* <p> If this {@code Class} object represents a class or interface with no1877* declared fields, then this method returns an array of length 0.1878*1879* <p> If this {@code Class} object represents an array type, a primitive1880* type, or void, then this method returns an array of length 0.1881*1882* <p> The elements in the returned array are not sorted and are not in any1883* particular order.1884*1885* @return the array of {@code Field} objects representing all the1886* declared fields of this class1887* @throws SecurityException1888* If a security manager, <i>s</i>, is present and any of the1889* following conditions is met:1890*1891* <ul>1892*1893* <li> the caller's class loader is not the same as the1894* class loader of this class and invocation of1895* {@link SecurityManager#checkPermission1896* s.checkPermission} method with1897* {@code RuntimePermission("accessDeclaredMembers")}1898* denies access to the declared fields within this class1899*1900* <li> the caller's class loader is not the same as or an1901* ancestor of the class loader for the current class and1902* invocation of {@link SecurityManager#checkPackageAccess1903* s.checkPackageAccess()} denies access to the package1904* of this class1905*1906* </ul>1907*1908* @since JDK1.11909* @jls 8.2 Class Members1910* @jls 8.3 Field Declarations1911*/1912@CallerSensitive1913public Field[] getDeclaredFields() throws SecurityException {1914checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);1915return copyFields(privateGetDeclaredFields(false));1916}191719181919/**1920*1921* Returns an array containing {@code Method} objects reflecting all the1922* declared methods of the class or interface represented by this {@code1923* Class} object, including public, protected, default (package)1924* access, and private methods, but excluding inherited methods.1925*1926* <p> If this {@code Class} object represents a type that has multiple1927* declared methods with the same name and parameter types, but different1928* return types, then the returned array has a {@code Method} object for1929* each such method.1930*1931* <p> If this {@code Class} object represents a type that has a class1932* initialization method {@code <clinit>}, then the returned array does1933* <em>not</em> have a corresponding {@code Method} object.1934*1935* <p> If this {@code Class} object represents a class or interface with no1936* declared methods, then the returned array has length 0.1937*1938* <p> If this {@code Class} object represents an array type, a primitive1939* type, or void, then the returned array has length 0.1940*1941* <p> The elements in the returned array are not sorted and are not in any1942* particular order.1943*1944* @return the array of {@code Method} objects representing all the1945* declared methods of this class1946* @throws SecurityException1947* If a security manager, <i>s</i>, is present and any of the1948* following conditions is met:1949*1950* <ul>1951*1952* <li> the caller's class loader is not the same as the1953* class loader of this class and invocation of1954* {@link SecurityManager#checkPermission1955* s.checkPermission} method with1956* {@code RuntimePermission("accessDeclaredMembers")}1957* denies access to the declared methods within this class1958*1959* <li> the caller's class loader is not the same as or an1960* ancestor of the class loader for the current class and1961* invocation of {@link SecurityManager#checkPackageAccess1962* s.checkPackageAccess()} denies access to the package1963* of this class1964*1965* </ul>1966*1967* @jls 8.2 Class Members1968* @jls 8.4 Method Declarations1969* @since JDK1.11970*/1971@CallerSensitive1972public Method[] getDeclaredMethods() throws SecurityException {1973checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);1974return copyMethods(privateGetDeclaredMethods(false));1975}197619771978/**1979* Returns an array of {@code Constructor} objects reflecting all the1980* constructors declared by the class represented by this1981* {@code Class} object. These are public, protected, default1982* (package) access, and private constructors. The elements in the array1983* returned are not sorted and are not in any particular order. If the1984* class has a default constructor, it is included in the returned array.1985* This method returns an array of length 0 if this {@code Class}1986* object represents an interface, a primitive type, an array class, or1987* void.1988*1989* <p> See <em>The Java Language Specification</em>, section 8.2.1990*1991* @return the array of {@code Constructor} objects representing all the1992* declared constructors of this class1993* @throws SecurityException1994* If a security manager, <i>s</i>, is present and any of the1995* following conditions is met:1996*1997* <ul>1998*1999* <li> the caller's class loader is not the same as the2000* class loader of this class and invocation of2001* {@link SecurityManager#checkPermission2002* s.checkPermission} method with2003* {@code RuntimePermission("accessDeclaredMembers")}2004* denies access to the declared constructors within this class2005*2006* <li> the caller's class loader is not the same as or an2007* ancestor of the class loader for the current class and2008* invocation of {@link SecurityManager#checkPackageAccess2009* s.checkPackageAccess()} denies access to the package2010* of this class2011*2012* </ul>2013*2014* @since JDK1.12015*/2016@CallerSensitive2017public Constructor<?>[] getDeclaredConstructors() throws SecurityException {2018checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);2019return copyConstructors(privateGetDeclaredConstructors(false));2020}202120222023/**2024* Returns a {@code Field} object that reflects the specified declared2025* field of the class or interface represented by this {@code Class}2026* object. The {@code name} parameter is a {@code String} that specifies2027* the simple name of the desired field.2028*2029* <p> If this {@code Class} object represents an array type, then this2030* method does not find the {@code length} field of the array type.2031*2032* @param name the name of the field2033* @return the {@code Field} object for the specified field in this2034* class2035* @throws NoSuchFieldException if a field with the specified name is2036* not found.2037* @throws NullPointerException if {@code name} is {@code null}2038* @throws SecurityException2039* If a security manager, <i>s</i>, is present and any of the2040* following conditions is met:2041*2042* <ul>2043*2044* <li> the caller's class loader is not the same as the2045* class loader of this class and invocation of2046* {@link SecurityManager#checkPermission2047* s.checkPermission} method with2048* {@code RuntimePermission("accessDeclaredMembers")}2049* denies access to the declared field2050*2051* <li> the caller's class loader is not the same as or an2052* ancestor of the class loader for the current class and2053* invocation of {@link SecurityManager#checkPackageAccess2054* s.checkPackageAccess()} denies access to the package2055* of this class2056*2057* </ul>2058*2059* @since JDK1.12060* @jls 8.2 Class Members2061* @jls 8.3 Field Declarations2062*/2063@CallerSensitive2064public Field getDeclaredField(String name)2065throws NoSuchFieldException, SecurityException {2066checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);2067Field field = searchFields(privateGetDeclaredFields(false), name);2068if (field == null) {2069throw new NoSuchFieldException(name);2070}2071return field;2072}207320742075/**2076* Returns a {@code Method} object that reflects the specified2077* declared method of the class or interface represented by this2078* {@code Class} object. The {@code name} parameter is a2079* {@code String} that specifies the simple name of the desired2080* method, and the {@code parameterTypes} parameter is an array of2081* {@code Class} objects that identify the method's formal parameter2082* types, in declared order. If more than one method with the same2083* parameter types is declared in a class, and one of these methods has a2084* return type that is more specific than any of the others, that method is2085* returned; otherwise one of the methods is chosen arbitrarily. If the2086* name is "<init>"or "<clinit>" a {@code NoSuchMethodException}2087* is raised.2088*2089* <p> If this {@code Class} object represents an array type, then this2090* method does not find the {@code clone()} method.2091*2092* @param name the name of the method2093* @param parameterTypes the parameter array2094* @return the {@code Method} object for the method of this class2095* matching the specified name and parameters2096* @throws NoSuchMethodException if a matching method is not found.2097* @throws NullPointerException if {@code name} is {@code null}2098* @throws SecurityException2099* If a security manager, <i>s</i>, is present and any of the2100* following conditions is met:2101*2102* <ul>2103*2104* <li> the caller's class loader is not the same as the2105* class loader of this class and invocation of2106* {@link SecurityManager#checkPermission2107* s.checkPermission} method with2108* {@code RuntimePermission("accessDeclaredMembers")}2109* denies access to the declared method2110*2111* <li> the caller's class loader is not the same as or an2112* ancestor of the class loader for the current class and2113* invocation of {@link SecurityManager#checkPackageAccess2114* s.checkPackageAccess()} denies access to the package2115* of this class2116*2117* </ul>2118*2119* @jls 8.2 Class Members2120* @jls 8.4 Method Declarations2121* @since JDK1.12122*/2123@CallerSensitive2124public Method getDeclaredMethod(String name, Class<?>... parameterTypes)2125throws NoSuchMethodException, SecurityException {2126checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);2127Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);2128if (method == null) {2129throw new NoSuchMethodException(getName() + "." + name + argumentTypesToString(parameterTypes));2130}2131return method;2132}213321342135/**2136* Returns a {@code Constructor} object that reflects the specified2137* constructor of the class or interface represented by this2138* {@code Class} object. The {@code parameterTypes} parameter is2139* an array of {@code Class} objects that identify the constructor's2140* formal parameter types, in declared order.2141*2142* If this {@code Class} object represents an inner class2143* declared in a non-static context, the formal parameter types2144* include the explicit enclosing instance as the first parameter.2145*2146* @param parameterTypes the parameter array2147* @return The {@code Constructor} object for the constructor with the2148* specified parameter list2149* @throws NoSuchMethodException if a matching method is not found.2150* @throws SecurityException2151* If a security manager, <i>s</i>, is present and any of the2152* following conditions is met:2153*2154* <ul>2155*2156* <li> the caller's class loader is not the same as the2157* class loader of this class and invocation of2158* {@link SecurityManager#checkPermission2159* s.checkPermission} method with2160* {@code RuntimePermission("accessDeclaredMembers")}2161* denies access to the declared constructor2162*2163* <li> the caller's class loader is not the same as or an2164* ancestor of the class loader for the current class and2165* invocation of {@link SecurityManager#checkPackageAccess2166* s.checkPackageAccess()} denies access to the package2167* of this class2168*2169* </ul>2170*2171* @since JDK1.12172*/2173@CallerSensitive2174public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)2175throws NoSuchMethodException, SecurityException {2176checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);2177return getConstructor0(parameterTypes, Member.DECLARED);2178}21792180/**2181* Finds a resource with a given name. The rules for searching resources2182* associated with a given class are implemented by the defining2183* {@linkplain ClassLoader class loader} of the class. This method2184* delegates to this object's class loader. If this object was loaded by2185* the bootstrap class loader, the method delegates to {@link2186* ClassLoader#getSystemResourceAsStream}.2187*2188* <p> Before delegation, an absolute resource name is constructed from the2189* given resource name using this algorithm:2190*2191* <ul>2192*2193* <li> If the {@code name} begins with a {@code '/'}2194* (<tt>'\u002f'</tt>), then the absolute name of the resource is the2195* portion of the {@code name} following the {@code '/'}.2196*2197* <li> Otherwise, the absolute name is of the following form:2198*2199* <blockquote>2200* {@code modified_package_name/name}2201* </blockquote>2202*2203* <p> Where the {@code modified_package_name} is the package name of this2204* object with {@code '/'} substituted for {@code '.'}2205* (<tt>'\u002e'</tt>).2206*2207* </ul>2208*2209* @param name name of the desired resource2210* @return A {@link java.io.InputStream} object or {@code null} if2211* no resource with this name is found2212* @throws NullPointerException If {@code name} is {@code null}2213* @since JDK1.12214*/2215public InputStream getResourceAsStream(String name) {2216name = resolveName(name);2217ClassLoader cl = getClassLoader0();2218if (cl==null) {2219// A system class.2220return ClassLoader.getSystemResourceAsStream(name);2221}2222return cl.getResourceAsStream(name);2223}22242225/**2226* Finds a resource with a given name. The rules for searching resources2227* associated with a given class are implemented by the defining2228* {@linkplain ClassLoader class loader} of the class. This method2229* delegates to this object's class loader. If this object was loaded by2230* the bootstrap class loader, the method delegates to {@link2231* ClassLoader#getSystemResource}.2232*2233* <p> Before delegation, an absolute resource name is constructed from the2234* given resource name using this algorithm:2235*2236* <ul>2237*2238* <li> If the {@code name} begins with a {@code '/'}2239* (<tt>'\u002f'</tt>), then the absolute name of the resource is the2240* portion of the {@code name} following the {@code '/'}.2241*2242* <li> Otherwise, the absolute name is of the following form:2243*2244* <blockquote>2245* {@code modified_package_name/name}2246* </blockquote>2247*2248* <p> Where the {@code modified_package_name} is the package name of this2249* object with {@code '/'} substituted for {@code '.'}2250* (<tt>'\u002e'</tt>).2251*2252* </ul>2253*2254* @param name name of the desired resource2255* @return A {@link java.net.URL} object or {@code null} if no2256* resource with this name is found2257* @since JDK1.12258*/2259public java.net.URL getResource(String name) {2260name = resolveName(name);2261ClassLoader cl = getClassLoader0();2262if (cl==null) {2263// A system class.2264return ClassLoader.getSystemResource(name);2265}2266return cl.getResource(name);2267}2268226922702271/** protection domain returned when the internal domain is null */2272private static java.security.ProtectionDomain allPermDomain;227322742275/**2276* Returns the {@code ProtectionDomain} of this class. If there is a2277* security manager installed, this method first calls the security2278* manager's {@code checkPermission} method with a2279* {@code RuntimePermission("getProtectionDomain")} permission to2280* ensure it's ok to get the2281* {@code ProtectionDomain}.2282*2283* @return the ProtectionDomain of this class2284*2285* @throws SecurityException2286* if a security manager exists and its2287* {@code checkPermission} method doesn't allow2288* getting the ProtectionDomain.2289*2290* @see java.security.ProtectionDomain2291* @see SecurityManager#checkPermission2292* @see java.lang.RuntimePermission2293* @since 1.22294*/2295public java.security.ProtectionDomain getProtectionDomain() {2296SecurityManager sm = System.getSecurityManager();2297if (sm != null) {2298sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);2299}2300java.security.ProtectionDomain pd = getProtectionDomain0();2301if (pd == null) {2302if (allPermDomain == null) {2303java.security.Permissions perms =2304new java.security.Permissions();2305perms.add(SecurityConstants.ALL_PERMISSION);2306allPermDomain =2307new java.security.ProtectionDomain(null, perms);2308}2309pd = allPermDomain;2310}2311return pd;2312}231323142315/**2316* Returns the ProtectionDomain of this class.2317*/2318private native java.security.ProtectionDomain getProtectionDomain0();23192320/*2321* Return the Virtual Machine's Class object for the named2322* primitive type.2323*/2324static native Class<?> getPrimitiveClass(String name);23252326/*2327* Check if client is allowed to access members. If access is denied,2328* throw a SecurityException.2329*2330* This method also enforces package access.2331*2332* <p> Default policy: allow all clients access with normal Java access2333* control.2334*/2335private void checkMemberAccess(int which, Class<?> caller, boolean checkProxyInterfaces) {2336final SecurityManager s = System.getSecurityManager();2337if (s != null) {2338/* Default policy allows access to all {@link Member#PUBLIC} members,2339* as well as access to classes that have the same class loader as the caller.2340* In all other cases, it requires RuntimePermission("accessDeclaredMembers")2341* permission.2342*/2343final ClassLoader ccl = ClassLoader.getClassLoader(caller);2344final ClassLoader cl = getClassLoader0();2345if (which != Member.PUBLIC) {2346if (ccl != cl) {2347s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);2348}2349}2350this.checkPackageAccess(ccl, checkProxyInterfaces);2351}2352}23532354/*2355* Checks if a client loaded in ClassLoader ccl is allowed to access this2356* class under the current package access policy. If access is denied,2357* throw a SecurityException.2358*/2359private void checkPackageAccess(final ClassLoader ccl, boolean checkProxyInterfaces) {2360final SecurityManager s = System.getSecurityManager();2361if (s != null) {2362final ClassLoader cl = getClassLoader0();23632364if (ReflectUtil.needsPackageAccessCheck(ccl, cl)) {2365String name = this.getName();2366int i = name.lastIndexOf('.');2367if (i != -1) {2368// skip the package access check on a proxy class in default proxy package2369String pkg = name.substring(0, i);2370if (!Proxy.isProxyClass(this) || ReflectUtil.isNonPublicProxyClass(this)) {2371s.checkPackageAccess(pkg);2372}2373}2374}2375// check package access on the proxy interfaces2376if (checkProxyInterfaces && Proxy.isProxyClass(this)) {2377ReflectUtil.checkProxyPackageAccess(ccl, this.getInterfaces());2378}2379}2380}23812382/**2383* Add a package name prefix if the name is not absolute Remove leading "/"2384* if name is absolute2385*/2386private String resolveName(String name) {2387if (name == null) {2388return name;2389}2390if (!name.startsWith("/")) {2391Class<?> c = this;2392while (c.isArray()) {2393c = c.getComponentType();2394}2395String baseName = c.getName();2396int index = baseName.lastIndexOf('.');2397if (index != -1) {2398name = baseName.substring(0, index).replace('.', '/')2399+"/"+name;2400}2401} else {2402name = name.substring(1);2403}2404return name;2405}24062407/**2408* Atomic operations support.2409*/2410private static class Atomic {2411// initialize Unsafe machinery here, since we need to call Class.class instance method2412// and have to avoid calling it in the static initializer of the Class class...2413private static final Unsafe unsafe = Unsafe.getUnsafe();2414// offset of Class.reflectionData instance field2415private static final long reflectionDataOffset;2416// offset of Class.annotationType instance field2417private static final long annotationTypeOffset;2418// offset of Class.annotationData instance field2419private static final long annotationDataOffset;24202421static {2422Field[] fields = Class.class.getDeclaredFields0(false); // bypass caches2423reflectionDataOffset = objectFieldOffset(fields, "reflectionData");2424annotationTypeOffset = objectFieldOffset(fields, "annotationType");2425annotationDataOffset = objectFieldOffset(fields, "annotationData");2426}24272428private static long objectFieldOffset(Field[] fields, String fieldName) {2429Field field = searchFields(fields, fieldName);2430if (field == null) {2431throw new Error("No " + fieldName + " field found in java.lang.Class");2432}2433return unsafe.objectFieldOffset(field);2434}24352436static <T> boolean casReflectionData(Class<?> clazz,2437SoftReference<ReflectionData<T>> oldData,2438SoftReference<ReflectionData<T>> newData) {2439return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData);2440}24412442static <T> boolean casAnnotationType(Class<?> clazz,2443AnnotationType oldType,2444AnnotationType newType) {2445return unsafe.compareAndSwapObject(clazz, annotationTypeOffset, oldType, newType);2446}24472448static <T> boolean casAnnotationData(Class<?> clazz,2449AnnotationData oldData,2450AnnotationData newData) {2451return unsafe.compareAndSwapObject(clazz, annotationDataOffset, oldData, newData);2452}2453}24542455/**2456* Reflection support.2457*/24582459// Caches for certain reflective results2460private static boolean useCaches = true;24612462// reflection data that might get invalidated when JVM TI RedefineClasses() is called2463private static class ReflectionData<T> {2464volatile Field[] declaredFields;2465volatile Field[] publicFields;2466volatile Method[] declaredMethods;2467volatile Method[] publicMethods;2468volatile Constructor<T>[] declaredConstructors;2469volatile Constructor<T>[] publicConstructors;2470// Intermediate results for getFields and getMethods2471volatile Field[] declaredPublicFields;2472volatile Method[] declaredPublicMethods;2473volatile Class<?>[] interfaces;24742475// Value of classRedefinedCount when we created this ReflectionData instance2476final int redefinedCount;24772478ReflectionData(int redefinedCount) {2479this.redefinedCount = redefinedCount;2480}2481}24822483private volatile transient SoftReference<ReflectionData<T>> reflectionData;24842485// Incremented by the VM on each call to JVM TI RedefineClasses()2486// that redefines this class or a superclass.2487private volatile transient int classRedefinedCount = 0;24882489// Lazily create and cache ReflectionData2490private ReflectionData<T> reflectionData() {2491SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;2492int classRedefinedCount = this.classRedefinedCount;2493ReflectionData<T> rd;2494if (useCaches &&2495reflectionData != null &&2496(rd = reflectionData.get()) != null &&2497rd.redefinedCount == classRedefinedCount) {2498return rd;2499}2500// else no SoftReference or cleared SoftReference or stale ReflectionData2501// -> create and replace new instance2502return newReflectionData(reflectionData, classRedefinedCount);2503}25042505private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,2506int classRedefinedCount) {2507if (!useCaches) return null;25082509while (true) {2510ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);2511// try to CAS it...2512if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {2513return rd;2514}2515// else retry2516oldReflectionData = this.reflectionData;2517classRedefinedCount = this.classRedefinedCount;2518if (oldReflectionData != null &&2519(rd = oldReflectionData.get()) != null &&2520rd.redefinedCount == classRedefinedCount) {2521return rd;2522}2523}2524}25252526// Generic signature handling2527private native String getGenericSignature0();25282529// Generic info repository; lazily initialized2530private volatile transient ClassRepository genericInfo;25312532// accessor for factory2533private GenericsFactory getFactory() {2534// create scope and factory2535return CoreReflectionFactory.make(this, ClassScope.make(this));2536}25372538// accessor for generic info repository;2539// generic info is lazily initialized2540private ClassRepository getGenericInfo() {2541ClassRepository genericInfo = this.genericInfo;2542if (genericInfo == null) {2543String signature = getGenericSignature0();2544if (signature == null) {2545genericInfo = ClassRepository.NONE;2546} else {2547genericInfo = ClassRepository.make(signature, getFactory());2548}2549this.genericInfo = genericInfo;2550}2551return (genericInfo != ClassRepository.NONE) ? genericInfo : null;2552}25532554// Annotations handling2555native byte[] getRawAnnotations();2556// Since 1.82557native byte[] getRawTypeAnnotations();2558static byte[] getExecutableTypeAnnotationBytes(Executable ex) {2559return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);2560}25612562native ConstantPool getConstantPool();25632564//2565//2566// java.lang.reflect.Field handling2567//2568//25692570// Returns an array of "root" fields. These Field objects must NOT2571// be propagated to the outside world, but must instead be copied2572// via ReflectionFactory.copyField.2573private Field[] privateGetDeclaredFields(boolean publicOnly) {2574checkInitted();2575Field[] res;2576ReflectionData<T> rd = reflectionData();2577if (rd != null) {2578res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;2579if (res != null) return res;2580}2581// No cached value available; request value from VM2582res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));2583if (rd != null) {2584if (publicOnly) {2585rd.declaredPublicFields = res;2586} else {2587rd.declaredFields = res;2588}2589}2590return res;2591}25922593// Returns an array of "root" fields. These Field objects must NOT2594// be propagated to the outside world, but must instead be copied2595// via ReflectionFactory.copyField.2596private Field[] privateGetPublicFields(Set<Class<?>> traversedInterfaces) {2597checkInitted();2598Field[] res;2599ReflectionData<T> rd = reflectionData();2600if (rd != null) {2601res = rd.publicFields;2602if (res != null) return res;2603}26042605// No cached value available; compute value recursively.2606// Traverse in correct order for getField().2607List<Field> fields = new ArrayList<>();2608if (traversedInterfaces == null) {2609traversedInterfaces = new HashSet<>();2610}26112612// Local fields2613Field[] tmp = privateGetDeclaredFields(true);2614addAll(fields, tmp);26152616// Direct superinterfaces, recursively2617for (Class<?> c : getInterfaces()) {2618if (!traversedInterfaces.contains(c)) {2619traversedInterfaces.add(c);2620addAll(fields, c.privateGetPublicFields(traversedInterfaces));2621}2622}26232624// Direct superclass, recursively2625if (!isInterface()) {2626Class<?> c = getSuperclass();2627if (c != null) {2628addAll(fields, c.privateGetPublicFields(traversedInterfaces));2629}2630}26312632res = new Field[fields.size()];2633fields.toArray(res);2634if (rd != null) {2635rd.publicFields = res;2636}2637return res;2638}26392640private static void addAll(Collection<Field> c, Field[] o) {2641for (int i = 0; i < o.length; i++) {2642c.add(o[i]);2643}2644}264526462647//2648//2649// java.lang.reflect.Constructor handling2650//2651//26522653// Returns an array of "root" constructors. These Constructor2654// objects must NOT be propagated to the outside world, but must2655// instead be copied via ReflectionFactory.copyConstructor.2656private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {2657checkInitted();2658Constructor<T>[] res;2659ReflectionData<T> rd = reflectionData();2660if (rd != null) {2661res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;2662if (res != null) return res;2663}2664// No cached value available; request value from VM2665if (isInterface()) {2666@SuppressWarnings("unchecked")2667Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];2668res = temporaryRes;2669} else {2670res = getDeclaredConstructors0(publicOnly);2671}2672if (rd != null) {2673if (publicOnly) {2674rd.publicConstructors = res;2675} else {2676rd.declaredConstructors = res;2677}2678}2679return res;2680}26812682//2683//2684// java.lang.reflect.Method handling2685//2686//26872688// Returns an array of "root" methods. These Method objects must NOT2689// be propagated to the outside world, but must instead be copied2690// via ReflectionFactory.copyMethod.2691private Method[] privateGetDeclaredMethods(boolean publicOnly) {2692checkInitted();2693Method[] res;2694ReflectionData<T> rd = reflectionData();2695if (rd != null) {2696res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;2697if (res != null) return res;2698}2699// No cached value available; request value from VM2700res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));2701if (rd != null) {2702if (publicOnly) {2703rd.declaredPublicMethods = res;2704} else {2705rd.declaredMethods = res;2706}2707}2708return res;2709}27102711static class MethodArray {2712// Don't add or remove methods except by add() or remove() calls.2713private Method[] methods;2714private int length;2715private int defaults;27162717MethodArray() {2718this(20);2719}27202721MethodArray(int initialSize) {2722if (initialSize < 2)2723throw new IllegalArgumentException("Size should be 2 or more");27242725methods = new Method[initialSize];2726length = 0;2727defaults = 0;2728}27292730boolean hasDefaults() {2731return defaults != 0;2732}27332734void add(Method m) {2735if (length == methods.length) {2736methods = Arrays.copyOf(methods, 2 * methods.length);2737}2738methods[length++] = m;27392740if (m != null && m.isDefault())2741defaults++;2742}27432744void addAll(Method[] ma) {2745for (int i = 0; i < ma.length; i++) {2746add(ma[i]);2747}2748}27492750void addAll(MethodArray ma) {2751for (int i = 0; i < ma.length(); i++) {2752add(ma.get(i));2753}2754}27552756void addIfNotPresent(Method newMethod) {2757for (int i = 0; i < length; i++) {2758Method m = methods[i];2759if (m == newMethod || (m != null && m.equals(newMethod))) {2760return;2761}2762}2763add(newMethod);2764}27652766void addAllIfNotPresent(MethodArray newMethods) {2767for (int i = 0; i < newMethods.length(); i++) {2768Method m = newMethods.get(i);2769if (m != null) {2770addIfNotPresent(m);2771}2772}2773}27742775/* Add Methods declared in an interface to this MethodArray.2776* Static methods declared in interfaces are not inherited.2777*/2778void addInterfaceMethods(Method[] methods) {2779for (Method candidate : methods) {2780if (!Modifier.isStatic(candidate.getModifiers())) {2781add(candidate);2782}2783}2784}27852786int length() {2787return length;2788}27892790Method get(int i) {2791return methods[i];2792}27932794Method getFirst() {2795for (Method m : methods)2796if (m != null)2797return m;2798return null;2799}28002801void removeByNameAndDescriptor(Method toRemove) {2802for (int i = 0; i < length; i++) {2803Method m = methods[i];2804if (m != null && matchesNameAndDescriptor(m, toRemove)) {2805remove(i);2806}2807}2808}28092810private void remove(int i) {2811if (methods[i] != null && methods[i].isDefault())2812defaults--;2813methods[i] = null;2814}28152816private boolean matchesNameAndDescriptor(Method m1, Method m2) {2817return m1.getReturnType() == m2.getReturnType() &&2818m1.getName() == m2.getName() && // name is guaranteed to be interned2819arrayContentsEq(m1.getParameterTypes(),2820m2.getParameterTypes());2821}28222823void compactAndTrim() {2824int newPos = 0;2825// Get rid of null slots2826for (int pos = 0; pos < length; pos++) {2827Method m = methods[pos];2828if (m != null) {2829if (pos != newPos) {2830methods[newPos] = m;2831}2832newPos++;2833}2834}2835if (newPos != methods.length) {2836methods = Arrays.copyOf(methods, newPos);2837}2838}28392840/* Removes all Methods from this MethodArray that have a more specific2841* default Method in this MethodArray.2842*2843* Users of MethodArray are responsible for pruning Methods that have2844* a more specific <em>concrete</em> Method.2845*/2846void removeLessSpecifics() {2847if (!hasDefaults())2848return;28492850for (int i = 0; i < length; i++) {2851Method m = get(i);2852if (m == null || !m.isDefault())2853continue;28542855for (int j = 0; j < length; j++) {2856if (i == j)2857continue;28582859Method candidate = get(j);2860if (candidate == null)2861continue;28622863if (!matchesNameAndDescriptor(m, candidate))2864continue;28652866if (hasMoreSpecificClass(m, candidate))2867remove(j);2868}2869}2870}28712872Method[] getArray() {2873return methods;2874}28752876// Returns true if m1 is more specific than m22877static boolean hasMoreSpecificClass(Method m1, Method m2) {2878Class<?> m1Class = m1.getDeclaringClass();2879Class<?> m2Class = m2.getDeclaringClass();2880return m1Class != m2Class && m2Class.isAssignableFrom(m1Class);2881}2882}288328842885// Returns an array of "root" methods. These Method objects must NOT2886// be propagated to the outside world, but must instead be copied2887// via ReflectionFactory.copyMethod.2888private Method[] privateGetPublicMethods() {2889checkInitted();2890Method[] res;2891ReflectionData<T> rd = reflectionData();2892if (rd != null) {2893res = rd.publicMethods;2894if (res != null) return res;2895}28962897// No cached value available; compute value recursively.2898// Start by fetching public declared methods2899MethodArray methods = new MethodArray();2900{2901Method[] tmp = privateGetDeclaredMethods(true);2902methods.addAll(tmp);2903}2904// Now recur over superclass and direct superinterfaces.2905// Go over superinterfaces first so we can more easily filter2906// out concrete implementations inherited from superclasses at2907// the end.2908MethodArray inheritedMethods = new MethodArray();2909for (Class<?> i : getInterfaces()) {2910inheritedMethods.addInterfaceMethods(i.privateGetPublicMethods());2911}2912if (!isInterface()) {2913Class<?> c = getSuperclass();2914if (c != null) {2915MethodArray supers = new MethodArray();2916supers.addAll(c.privateGetPublicMethods());2917// Filter out concrete implementations of any2918// interface methods2919for (int i = 0; i < supers.length(); i++) {2920Method m = supers.get(i);2921if (m != null &&2922!Modifier.isAbstract(m.getModifiers()) &&2923!m.isDefault()) {2924inheritedMethods.removeByNameAndDescriptor(m);2925}2926}2927// Insert superclass's inherited methods before2928// superinterfaces' to satisfy getMethod's search2929// order2930supers.addAll(inheritedMethods);2931inheritedMethods = supers;2932}2933}2934// Filter out all local methods from inherited ones2935for (int i = 0; i < methods.length(); i++) {2936Method m = methods.get(i);2937inheritedMethods.removeByNameAndDescriptor(m);2938}2939methods.addAllIfNotPresent(inheritedMethods);2940methods.removeLessSpecifics();2941methods.compactAndTrim();2942res = methods.getArray();2943if (rd != null) {2944rd.publicMethods = res;2945}2946return res;2947}294829492950//2951// Helpers for fetchers of one field, method, or constructor2952//29532954private static Field searchFields(Field[] fields, String name) {2955String internedName = name.intern();2956for (int i = 0; i < fields.length; i++) {2957if (fields[i].getName() == internedName) {2958return getReflectionFactory().copyField(fields[i]);2959}2960}2961return null;2962}29632964private Field getField0(String name) throws NoSuchFieldException {2965// Note: the intent is that the search algorithm this routine2966// uses be equivalent to the ordering imposed by2967// privateGetPublicFields(). It fetches only the declared2968// public fields for each class, however, to reduce the number2969// of Field objects which have to be created for the common2970// case where the field being requested is declared in the2971// class which is being queried.2972Field res;2973// Search declared public fields2974if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {2975return res;2976}2977// Direct superinterfaces, recursively2978Class<?>[] interfaces = getInterfaces();2979for (int i = 0; i < interfaces.length; i++) {2980Class<?> c = interfaces[i];2981if ((res = c.getField0(name)) != null) {2982return res;2983}2984}2985// Direct superclass, recursively2986if (!isInterface()) {2987Class<?> c = getSuperclass();2988if (c != null) {2989if ((res = c.getField0(name)) != null) {2990return res;2991}2992}2993}2994return null;2995}29962997private static Method searchMethods(Method[] methods,2998String name,2999Class<?>[] parameterTypes)3000{3001Method res = null;3002String internedName = name.intern();3003for (int i = 0; i < methods.length; i++) {3004Method m = methods[i];3005if (m.getName() == internedName3006&& arrayContentsEq(parameterTypes, m.getParameterTypes())3007&& (res == null3008|| res.getReturnType().isAssignableFrom(m.getReturnType())))3009res = m;3010}30113012return (res == null ? res : getReflectionFactory().copyMethod(res));3013}30143015private Method getMethod0(String name, Class<?>[] parameterTypes, boolean includeStaticMethods) {3016MethodArray interfaceCandidates = new MethodArray(2);3017Method res = privateGetMethodRecursive(name, parameterTypes, includeStaticMethods, interfaceCandidates);3018if (res != null)3019return res;30203021// Not found on class or superclass directly3022interfaceCandidates.removeLessSpecifics();3023return interfaceCandidates.getFirst(); // may be null3024}30253026private Method privateGetMethodRecursive(String name,3027Class<?>[] parameterTypes,3028boolean includeStaticMethods,3029MethodArray allInterfaceCandidates) {3030// Note: the intent is that the search algorithm this routine3031// uses be equivalent to the ordering imposed by3032// privateGetPublicMethods(). It fetches only the declared3033// public methods for each class, however, to reduce the3034// number of Method objects which have to be created for the3035// common case where the method being requested is declared in3036// the class which is being queried.3037//3038// Due to default methods, unless a method is found on a superclass,3039// methods declared in any superinterface needs to be considered.3040// Collect all candidates declared in superinterfaces in {@code3041// allInterfaceCandidates} and select the most specific if no match on3042// a superclass is found.30433044// Must _not_ return root methods3045Method res;3046// Search declared public methods3047if ((res = searchMethods(privateGetDeclaredMethods(true),3048name,3049parameterTypes)) != null) {3050if (includeStaticMethods || !Modifier.isStatic(res.getModifiers()))3051return res;3052}3053// Search superclass's methods3054if (!isInterface()) {3055Class<? super T> c = getSuperclass();3056if (c != null) {3057if ((res = c.getMethod0(name, parameterTypes, true)) != null) {3058return res;3059}3060}3061}3062// Search superinterfaces' methods3063Class<?>[] interfaces = getInterfaces();3064for (Class<?> c : interfaces)3065if ((res = c.getMethod0(name, parameterTypes, false)) != null)3066allInterfaceCandidates.add(res);3067// Not found3068return null;3069}30703071private Constructor<T> getConstructor0(Class<?>[] parameterTypes,3072int which) throws NoSuchMethodException3073{3074Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));3075for (Constructor<T> constructor : constructors) {3076if (arrayContentsEq(parameterTypes,3077constructor.getParameterTypes())) {3078return getReflectionFactory().copyConstructor(constructor);3079}3080}3081throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));3082}30833084//3085// Other helpers and base implementation3086//30873088private static boolean arrayContentsEq(Object[] a1, Object[] a2) {3089if (a1 == null) {3090return a2 == null || a2.length == 0;3091}30923093if (a2 == null) {3094return a1.length == 0;3095}30963097if (a1.length != a2.length) {3098return false;3099}31003101for (int i = 0; i < a1.length; i++) {3102if (a1[i] != a2[i]) {3103return false;3104}3105}31063107return true;3108}31093110private static Field[] copyFields(Field[] arg) {3111Field[] out = new Field[arg.length];3112ReflectionFactory fact = getReflectionFactory();3113for (int i = 0; i < arg.length; i++) {3114out[i] = fact.copyField(arg[i]);3115}3116return out;3117}31183119private static Method[] copyMethods(Method[] arg) {3120Method[] out = new Method[arg.length];3121ReflectionFactory fact = getReflectionFactory();3122for (int i = 0; i < arg.length; i++) {3123out[i] = fact.copyMethod(arg[i]);3124}3125return out;3126}31273128private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {3129Constructor<U>[] out = arg.clone();3130ReflectionFactory fact = getReflectionFactory();3131for (int i = 0; i < out.length; i++) {3132out[i] = fact.copyConstructor(out[i]);3133}3134return out;3135}31363137private native Field[] getDeclaredFields0(boolean publicOnly);3138private native Method[] getDeclaredMethods0(boolean publicOnly);3139private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);3140private native Class<?>[] getDeclaredClasses0();31413142private static String argumentTypesToString(Class<?>[] argTypes) {3143StringBuilder buf = new StringBuilder();3144buf.append("(");3145if (argTypes != null) {3146for (int i = 0; i < argTypes.length; i++) {3147if (i > 0) {3148buf.append(", ");3149}3150Class<?> c = argTypes[i];3151buf.append((c == null) ? "null" : c.getName());3152}3153}3154buf.append(")");3155return buf.toString();3156}31573158/** use serialVersionUID from JDK 1.1 for interoperability */3159private static final long serialVersionUID = 3206093459760846163L;316031613162/**3163* Class Class is special cased within the Serialization Stream Protocol.3164*3165* A Class instance is written initially into an ObjectOutputStream in the3166* following format:3167* <pre>3168* {@code TC_CLASS} ClassDescriptor3169* A ClassDescriptor is a special cased serialization of3170* a {@code java.io.ObjectStreamClass} instance.3171* </pre>3172* A new handle is generated for the initial time the class descriptor3173* is written into the stream. Future references to the class descriptor3174* are written as references to the initial class descriptor instance.3175*3176* @see java.io.ObjectStreamClass3177*/3178private static final ObjectStreamField[] serialPersistentFields =3179new ObjectStreamField[0];318031813182/**3183* Returns the assertion status that would be assigned to this3184* class if it were to be initialized at the time this method is invoked.3185* If this class has had its assertion status set, the most recent3186* setting will be returned; otherwise, if any package default assertion3187* status pertains to this class, the most recent setting for the most3188* specific pertinent package default assertion status is returned;3189* otherwise, if this class is not a system class (i.e., it has a3190* class loader) its class loader's default assertion status is returned;3191* otherwise, the system class default assertion status is returned.3192* <p>3193* Few programmers will have any need for this method; it is provided3194* for the benefit of the JRE itself. (It allows a class to determine at3195* the time that it is initialized whether assertions should be enabled.)3196* Note that this method is not guaranteed to return the actual3197* assertion status that was (or will be) associated with the specified3198* class when it was (or will be) initialized.3199*3200* @return the desired assertion status of the specified class.3201* @see java.lang.ClassLoader#setClassAssertionStatus3202* @see java.lang.ClassLoader#setPackageAssertionStatus3203* @see java.lang.ClassLoader#setDefaultAssertionStatus3204* @since 1.43205*/3206public boolean desiredAssertionStatus() {3207ClassLoader loader = getClassLoader();3208// If the loader is null this is a system class, so ask the VM3209if (loader == null)3210return desiredAssertionStatus0(this);32113212// If the classloader has been initialized with the assertion3213// directives, ask it. Otherwise, ask the VM.3214synchronized(loader.assertionLock) {3215if (loader.classAssertionStatus != null) {3216return loader.desiredAssertionStatus(getName());3217}3218}3219return desiredAssertionStatus0(this);3220}32213222// Retrieves the desired assertion status of this class from the VM3223private static native boolean desiredAssertionStatus0(Class<?> clazz);32243225/**3226* Returns true if and only if this class was declared as an enum in the3227* source code.3228*3229* @return true if and only if this class was declared as an enum in the3230* source code3231* @since 1.53232*/3233public boolean isEnum() {3234// An enum must both directly extend java.lang.Enum and have3235// the ENUM bit set; classes for specialized enum constants3236// don't do the former.3237return (this.getModifiers() & ENUM) != 0 &&3238this.getSuperclass() == java.lang.Enum.class;3239}32403241// Fetches the factory for reflective objects3242private static ReflectionFactory getReflectionFactory() {3243if (reflectionFactory == null) {3244reflectionFactory =3245java.security.AccessController.doPrivileged3246(new sun.reflect.ReflectionFactory.GetReflectionFactoryAction());3247}3248return reflectionFactory;3249}3250private static ReflectionFactory reflectionFactory;32513252// To be able to query system properties as soon as they're available3253private static boolean initted = false;3254private static void checkInitted() {3255if (initted) return;3256AccessController.doPrivileged(new PrivilegedAction<Void>() {3257public Void run() {3258// Tests to ensure the system properties table is fully3259// initialized. This is needed because reflection code is3260// called very early in the initialization process (before3261// command-line arguments have been parsed and therefore3262// these user-settable properties installed.) We assume that3263// if System.out is non-null then the System class has been3264// fully initialized and that the bulk of the startup code3265// has been run.32663267if (System.out == null) {3268// java.lang.System not yet fully initialized3269return null;3270}32713272// Doesn't use Boolean.getBoolean to avoid class init.3273String val =3274System.getProperty("sun.reflect.noCaches");3275if (val != null && val.equals("true")) {3276useCaches = false;3277}32783279initted = true;3280return null;3281}3282});3283}32843285/**3286* Returns the elements of this enum class or null if this3287* Class object does not represent an enum type.3288*3289* @return an array containing the values comprising the enum class3290* represented by this Class object in the order they're3291* declared, or null if this Class object does not3292* represent an enum type3293* @since 1.53294*/3295public T[] getEnumConstants() {3296T[] values = getEnumConstantsShared();3297return (values != null) ? values.clone() : null;3298}32993300/**3301* Returns the elements of this enum class or null if this3302* Class object does not represent an enum type;3303* identical to getEnumConstants except that the result is3304* uncloned, cached, and shared by all callers.3305*/3306T[] getEnumConstantsShared() {3307if (enumConstants == null) {3308if (!isEnum()) return null;3309try {3310final Method values = getMethod("values");3311java.security.AccessController.doPrivileged(3312new java.security.PrivilegedAction<Void>() {3313public Void run() {3314values.setAccessible(true);3315return null;3316}3317});3318@SuppressWarnings("unchecked")3319T[] temporaryConstants = (T[])values.invoke(null);3320enumConstants = temporaryConstants;3321}3322// These can happen when users concoct enum-like classes3323// that don't comply with the enum spec.3324catch (InvocationTargetException | NoSuchMethodException |3325IllegalAccessException ex) { return null; }3326}3327return enumConstants;3328}3329private volatile transient T[] enumConstants = null;33303331/**3332* Returns a map from simple name to enum constant. This package-private3333* method is used internally by Enum to implement3334* {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}3335* efficiently. Note that the map is returned by this method is3336* created lazily on first use. Typically it won't ever get created.3337*/3338Map<String, T> enumConstantDirectory() {3339if (enumConstantDirectory == null) {3340T[] universe = getEnumConstantsShared();3341if (universe == null)3342throw new IllegalArgumentException(3343getName() + " is not an enum type");3344Map<String, T> m = new HashMap<>(2 * universe.length);3345for (T constant : universe)3346m.put(((Enum<?>)constant).name(), constant);3347enumConstantDirectory = m;3348}3349return enumConstantDirectory;3350}3351private volatile transient Map<String, T> enumConstantDirectory = null;33523353/**3354* Casts an object to the class or interface represented3355* by this {@code Class} object.3356*3357* @param obj the object to be cast3358* @return the object after casting, or null if obj is null3359*3360* @throws ClassCastException if the object is not3361* null and is not assignable to the type T.3362*3363* @since 1.53364*/3365@SuppressWarnings("unchecked")3366public T cast(Object obj) {3367if (obj != null && !isInstance(obj))3368throw new ClassCastException(cannotCastMsg(obj));3369return (T) obj;3370}33713372private String cannotCastMsg(Object obj) {3373return "Cannot cast " + obj.getClass().getName() + " to " + getName();3374}33753376/**3377* Casts this {@code Class} object to represent a subclass of the class3378* represented by the specified class object. Checks that the cast3379* is valid, and throws a {@code ClassCastException} if it is not. If3380* this method succeeds, it always returns a reference to this class object.3381*3382* <p>This method is useful when a client needs to "narrow" the type of3383* a {@code Class} object to pass it to an API that restricts the3384* {@code Class} objects that it is willing to accept. A cast would3385* generate a compile-time warning, as the correctness of the cast3386* could not be checked at runtime (because generic types are implemented3387* by erasure).3388*3389* @param <U> the type to cast this class object to3390* @param clazz the class of the type to cast this class object to3391* @return this {@code Class} object, cast to represent a subclass of3392* the specified class object.3393* @throws ClassCastException if this {@code Class} object does not3394* represent a subclass of the specified class (here "subclass" includes3395* the class itself).3396* @since 1.53397*/3398@SuppressWarnings("unchecked")3399public <U> Class<? extends U> asSubclass(Class<U> clazz) {3400if (clazz.isAssignableFrom(this))3401return (Class<? extends U>) this;3402else3403throw new ClassCastException(this.toString());3404}34053406/**3407* @throws NullPointerException {@inheritDoc}3408* @since 1.53409*/3410@SuppressWarnings("unchecked")3411public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {3412Objects.requireNonNull(annotationClass);34133414return (A) annotationData().annotations.get(annotationClass);3415}34163417/**3418* {@inheritDoc}3419* @throws NullPointerException {@inheritDoc}3420* @since 1.53421*/3422@Override3423public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {3424return GenericDeclaration.super.isAnnotationPresent(annotationClass);3425}34263427/**3428* @throws NullPointerException {@inheritDoc}3429* @since 1.83430*/3431@Override3432public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {3433Objects.requireNonNull(annotationClass);34343435AnnotationData annotationData = annotationData();3436return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations,3437this,3438annotationClass);3439}34403441/**3442* @since 1.53443*/3444public Annotation[] getAnnotations() {3445return AnnotationParser.toArray(annotationData().annotations);3446}34473448/**3449* @throws NullPointerException {@inheritDoc}3450* @since 1.83451*/3452@Override3453@SuppressWarnings("unchecked")3454public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {3455Objects.requireNonNull(annotationClass);34563457return (A) annotationData().declaredAnnotations.get(annotationClass);3458}34593460/**3461* @throws NullPointerException {@inheritDoc}3462* @since 1.83463*/3464@Override3465public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {3466Objects.requireNonNull(annotationClass);34673468return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,3469annotationClass);3470}34713472/**3473* @since 1.53474*/3475public Annotation[] getDeclaredAnnotations() {3476return AnnotationParser.toArray(annotationData().declaredAnnotations);3477}34783479// annotation data that might get invalidated when JVM TI RedefineClasses() is called3480private static class AnnotationData {3481final Map<Class<? extends Annotation>, Annotation> annotations;3482final Map<Class<? extends Annotation>, Annotation> declaredAnnotations;34833484// Value of classRedefinedCount when we created this AnnotationData instance3485final int redefinedCount;34863487AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations,3488Map<Class<? extends Annotation>, Annotation> declaredAnnotations,3489int redefinedCount) {3490this.annotations = annotations;3491this.declaredAnnotations = declaredAnnotations;3492this.redefinedCount = redefinedCount;3493}3494}34953496// Annotations cache3497@SuppressWarnings("UnusedDeclaration")3498private volatile transient AnnotationData annotationData;34993500private AnnotationData annotationData() {3501while (true) { // retry loop3502AnnotationData annotationData = this.annotationData;3503int classRedefinedCount = this.classRedefinedCount;3504if (annotationData != null &&3505annotationData.redefinedCount == classRedefinedCount) {3506return annotationData;3507}3508// null or stale annotationData -> optimistically create new instance3509AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount);3510// try to install it3511if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) {3512// successfully installed new AnnotationData3513return newAnnotationData;3514}3515}3516}35173518private AnnotationData createAnnotationData(int classRedefinedCount) {3519Map<Class<? extends Annotation>, Annotation> declaredAnnotations =3520AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this);3521Class<?> superClass = getSuperclass();3522Map<Class<? extends Annotation>, Annotation> annotations = null;3523if (superClass != null) {3524Map<Class<? extends Annotation>, Annotation> superAnnotations =3525superClass.annotationData().annotations;3526for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) {3527Class<? extends Annotation> annotationClass = e.getKey();3528if (AnnotationType.getInstance(annotationClass).isInherited()) {3529if (annotations == null) { // lazy construction3530annotations = new LinkedHashMap<>((Math.max(3531declaredAnnotations.size(),3532Math.min(12, declaredAnnotations.size() + superAnnotations.size())3533) * 4 + 2) / 33534);3535}3536annotations.put(annotationClass, e.getValue());3537}3538}3539}3540if (annotations == null) {3541// no inherited annotations -> share the Map with declaredAnnotations3542annotations = declaredAnnotations;3543} else {3544// at least one inherited annotation -> declared may override inherited3545annotations.putAll(declaredAnnotations);3546}3547return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount);3548}35493550// Annotation types cache their internal (AnnotationType) form35513552@SuppressWarnings("UnusedDeclaration")3553private volatile transient AnnotationType annotationType;35543555boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {3556return Atomic.casAnnotationType(this, oldType, newType);3557}35583559AnnotationType getAnnotationType() {3560return annotationType;3561}35623563Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() {3564return annotationData().declaredAnnotations;3565}35663567/* Backing store of user-defined values pertaining to this class.3568* Maintained by the ClassValue class.3569*/3570transient ClassValue.ClassValueMap classValueMap;35713572/**3573* Returns an {@code AnnotatedType} object that represents the use of a3574* type to specify the superclass of the entity represented by this {@code3575* Class} object. (The <em>use</em> of type Foo to specify the superclass3576* in '... extends Foo' is distinct from the <em>declaration</em> of type3577* Foo.)3578*3579* <p> If this {@code Class} object represents a type whose declaration3580* does not explicitly indicate an annotated superclass, then the return3581* value is an {@code AnnotatedType} object representing an element with no3582* annotations.3583*3584* <p> If this {@code Class} represents either the {@code Object} class, an3585* interface type, an array type, a primitive type, or void, the return3586* value is {@code null}.3587*3588* @return an object representing the superclass3589* @since 1.83590*/3591public AnnotatedType getAnnotatedSuperclass() {3592if (this == Object.class ||3593isInterface() ||3594isArray() ||3595isPrimitive() ||3596this == Void.TYPE) {3597return null;3598}35993600return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);3601}36023603/**3604* Returns an array of {@code AnnotatedType} objects that represent the use3605* of types to specify superinterfaces of the entity represented by this3606* {@code Class} object. (The <em>use</em> of type Foo to specify a3607* superinterface in '... implements Foo' is distinct from the3608* <em>declaration</em> of type Foo.)3609*3610* <p> If this {@code Class} object represents a class, the return value is3611* an array containing objects representing the uses of interface types to3612* specify interfaces implemented by the class. The order of the objects in3613* the array corresponds to the order of the interface types used in the3614* 'implements' clause of the declaration of this {@code Class} object.3615*3616* <p> If this {@code Class} object represents an interface, the return3617* value is an array containing objects representing the uses of interface3618* types to specify interfaces directly extended by the interface. The3619* order of the objects in the array corresponds to the order of the3620* interface types used in the 'extends' clause of the declaration of this3621* {@code Class} object.3622*3623* <p> If this {@code Class} object represents a class or interface whose3624* declaration does not explicitly indicate any annotated superinterfaces,3625* the return value is an array of length 0.3626*3627* <p> If this {@code Class} object represents either the {@code Object}3628* class, an array type, a primitive type, or void, the return value is an3629* array of length 0.3630*3631* @return an array representing the superinterfaces3632* @since 1.83633*/3634public AnnotatedType[] getAnnotatedInterfaces() {3635return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);3636}3637}363836393640