< prev index next >

src/java.base/share/classes/java/lang/Class.java

Print this page




  45 import java.lang.reflect.Member;
  46 import java.lang.reflect.Method;
  47 import java.lang.reflect.Modifier;
  48 import java.lang.reflect.Proxy;
  49 import java.lang.reflect.Type;
  50 import java.lang.reflect.TypeVariable;
  51 import java.lang.constant.Constable;
  52 import java.net.URL;
  53 import java.security.AccessController;
  54 import java.security.PrivilegedAction;
  55 import java.util.ArrayList;
  56 import java.util.Arrays;
  57 import java.util.Collection;
  58 import java.util.HashMap;
  59 import java.util.LinkedHashMap;
  60 import java.util.LinkedHashSet;
  61 import java.util.List;
  62 import java.util.Map;
  63 import java.util.Objects;
  64 import java.util.Optional;
  65 import java.util.StringJoiner;
  66 import java.util.stream.Stream;
  67 import java.util.stream.Collectors;
  68 
  69 import jdk.internal.HotSpotIntrinsicCandidate;
  70 import jdk.internal.loader.BootLoader;
  71 import jdk.internal.loader.BuiltinClassLoader;
  72 import jdk.internal.misc.Unsafe;
  73 import jdk.internal.module.Resources;
  74 import jdk.internal.reflect.CallerSensitive;
  75 import jdk.internal.reflect.ConstantPool;
  76 import jdk.internal.reflect.Reflection;
  77 import jdk.internal.reflect.ReflectionFactory;
  78 import jdk.internal.vm.annotation.ForceInline;
  79 import sun.invoke.util.Wrapper;
  80 import sun.reflect.generics.factory.CoreReflectionFactory;
  81 import sun.reflect.generics.factory.GenericsFactory;
  82 import sun.reflect.generics.repository.ClassRepository;
  83 import sun.reflect.generics.repository.MethodRepository;
  84 import sun.reflect.generics.repository.ConstructorRepository;
  85 import sun.reflect.generics.scope.ClassScope;
  86 import sun.security.util.SecurityConstants;


 145  *
 146  * <blockquote>
 147  *     {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
 148  * </blockquote>
 149  *
 150  * @param <T> the type of the class modeled by this {@code Class}
 151  * object.  For example, the type of {@code String.class} is {@code
 152  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
 153  * unknown.
 154  *
 155  * @author  unascribed
 156  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
 157  * @since   1.0
 158  */
 159 public final class Class<T> implements java.io.Serializable,
 160                               GenericDeclaration,
 161                               Type,
 162                               AnnotatedElement,
 163                               TypeDescriptor.OfField<Class<?>>,
 164                               Constable {
 165     private static final int ANNOTATION= 0x00002000;
 166     private static final int ENUM      = 0x00004000;
 167     private static final int SYNTHETIC = 0x00001000;

 168 
 169     private static native void registerNatives();
 170     static {
 171         registerNatives();
 172     }
 173 
 174     /*
 175      * Private constructor. Only the Java Virtual Machine creates Class objects.
 176      * This constructor is not used and prevents the default constructor being
 177      * generated.
 178      */
 179     private Class(ClassLoader loader, Class<?> arrayComponentType) {
 180         // Initialize final field for classLoader.  The initialization value of non-null
 181         // prevents future JIT optimizations from assuming this final field is null.
 182         classLoader = loader;
 183         componentType = arrayComponentType;
 184     }
 185 
 186     /**
 187      * Converts the object to a string. The string representation is the
 188      * string "class" or "interface", followed by a space, and then by the
 189      * fully qualified name of the class in the format returned by
 190      * {@code getName}.  If this {@code Class} object represents a
 191      * primitive type, this method returns the name of the primitive type.  If
 192      * this {@code Class} object represents void this method returns
 193      * "void". If this {@code Class} object represents an array type,
 194      * this method returns "class " followed by {@code getName}.
 195      *
 196      * @return a string representation of this class object.
 197      */
 198     public String toString() {
 199         return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
 200             + getName();

 201     }
 202 
 203     /**
 204      * Returns a string describing this {@code Class}, including
 205      * information about modifiers and type parameters.
 206      *
 207      * The string is formatted as a list of type modifiers, if any,
 208      * followed by the kind of type (empty string for primitive types
 209      * and {@code class}, {@code enum}, {@code interface}, or
 210      * <code>@</code>{@code interface}, as appropriate), followed
 211      * by the type's name, followed by an angle-bracketed
 212      * comma-separated list of the type's type parameters, if any,
 213      * including informative bounds on the type parameters, if any.
 214      *
 215      * A space is used to separate modifiers from one another and to
 216      * separate any modifiers from the kind of type. The modifiers
 217      * occur in canonical order. If there are no type parameters, the
 218      * type parameter list is elided.
 219      *
 220      * For an array type, the string starts with the type name,


 241             Class<?> component = this;
 242             int arrayDepth = 0;
 243 
 244             if (isArray()) {
 245                 do {
 246                     arrayDepth++;
 247                     component = component.getComponentType();
 248                 } while (component.isArray());
 249                 sb.append(component.getName());
 250             } else {
 251                 // Class modifiers are a superset of interface modifiers
 252                 int modifiers = getModifiers() & Modifier.classModifiers();
 253                 if (modifiers != 0) {
 254                     sb.append(Modifier.toString(modifiers));
 255                     sb.append(' ');
 256                 }
 257 
 258                 if (isAnnotation()) {
 259                     sb.append('@');
 260                 }




 261                 if (isInterface()) { // Note: all annotation types are interfaces
 262                     sb.append("interface");
 263                 } else {
 264                     if (isEnum())
 265                         sb.append("enum");
 266                     else
 267                         sb.append("class");
 268                 }
 269                 sb.append(' ');
 270                 sb.append(getName());
 271             }
 272 
 273             TypeVariable<?>[] typeparms = component.getTypeParameters();
 274             if (typeparms.length > 0) {
 275                 sb.append(Arrays.stream(typeparms)
 276                           .map(Class::typeVarBounds)
 277                           .collect(Collectors.joining(",", "<", ">")));
 278             }
 279 
 280             if (arrayDepth > 0) sb.append("[]".repeat(arrayDepth));


 401     {
 402         Class<?> caller = null;
 403         SecurityManager sm = System.getSecurityManager();
 404         if (sm != null) {
 405             // Reflective call to get caller class is only needed if a security manager
 406             // is present.  Avoid the overhead of making this call otherwise.
 407             caller = Reflection.getCallerClass();
 408             if (loader == null) {
 409                 ClassLoader ccl = ClassLoader.getClassLoader(caller);
 410                 if (ccl != null) {
 411                     sm.checkPermission(
 412                         SecurityConstants.GET_CLASSLOADER_PERMISSION);
 413                 }
 414             }
 415         }
 416         return forName0(name, initialize, loader, caller);
 417     }
 418 
 419     /** Called after security check for system loader access checks have been made. */
 420     private static native Class<?> forName0(String name, boolean initialize,
 421                                             ClassLoader loader,
 422                                             Class<?> caller)
 423         throws ClassNotFoundException;
 424 
 425 
 426     /**
 427      * Returns the {@code Class} with the given <a href="ClassLoader.html#binary-name">
 428      * binary name</a> in the given module.
 429      *
 430      * <p> This method attempts to locate, load, and link the class or interface.
 431      * It does not run the class initializer.  If the class is not found, this
 432      * method returns {@code null}. </p>
 433      *
 434      * <p> If the class loader of the given module defines other modules and
 435      * the given name is a class defined in a different module, this method
 436      * returns {@code null} after the class is loaded. </p>
 437      *
 438      * <p> This method does not check whether the requested class is
 439      * accessible to its caller. </p>
 440      *
 441      * @apiNote
 442      * This method returns {@code null} on failure rather than


 478         if (sm != null) {
 479             Class<?> caller = Reflection.getCallerClass();
 480             if (caller != null && caller.getModule() != module) {
 481                 // if caller is null, Class.forName is the last java frame on the stack.
 482                 // java.base has all permissions
 483                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 484             }
 485             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
 486             cl = AccessController.doPrivileged(pa);
 487         } else {
 488             cl = module.getClassLoader();
 489         }
 490 
 491         if (cl != null) {
 492             return cl.loadClass(module, name);
 493         } else {
 494             return BootLoader.loadClass(module, name);
 495         }
 496     }
 497 

























































































 498     /**
 499      * Creates a new instance of the class represented by this {@code Class}
 500      * object.  The class is instantiated as if by a {@code new}
 501      * expression with an empty argument list.  The class is initialized if it
 502      * has not already been initialized.
 503      *
 504      * @deprecated This method propagates any exception thrown by the
 505      * nullary constructor, including a checked exception.  Use of
 506      * this method effectively bypasses the compile-time exception
 507      * checking that would otherwise be performed by the compiler.
 508      * The {@link
 509      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
 510      * Constructor.newInstance} method avoids this problem by wrapping
 511      * any exception thrown by the constructor in a (checked) {@link
 512      * java.lang.reflect.InvocationTargetException}.
 513      *
 514      * <p>The call
 515      *
 516      * <pre>{@code
 517      * clazz.newInstance()


 751      * <p> If this class object represents a primitive type or void, then the
 752      * name returned is a {@code String} equal to the Java language
 753      * keyword corresponding to the primitive type or void.
 754      *
 755      * <p> If this class object represents a class of arrays, then the internal
 756      * form of the name consists of the name of the element type preceded by
 757      * one or more '{@code [}' characters representing the depth of the array
 758      * nesting.  The encoding of element type names is as follows:
 759      *
 760      * <blockquote><table class="striped">
 761      * <caption style="display:none">Element types and encodings</caption>
 762      * <thead>
 763      * <tr><th scope="col"> Element Type <th scope="col"> Encoding
 764      * </thead>
 765      * <tbody style="text-align:left">
 766      * <tr><th scope="row"> boolean      <td style="text-align:center"> Z
 767      * <tr><th scope="row"> byte         <td style="text-align:center"> B
 768      * <tr><th scope="row"> char         <td style="text-align:center"> C
 769      * <tr><th scope="row"> class or interface
 770      *                                   <td style="text-align:center"> L<i>classname</i>;


 771      * <tr><th scope="row"> double       <td style="text-align:center"> D
 772      * <tr><th scope="row"> float        <td style="text-align:center"> F
 773      * <tr><th scope="row"> int          <td style="text-align:center"> I
 774      * <tr><th scope="row"> long         <td style="text-align:center"> J
 775      * <tr><th scope="row"> short        <td style="text-align:center"> S
 776      * </tbody>
 777      * </table></blockquote>
 778      *
 779      * <p> The class or interface name <i>classname</i> is the binary name of
 780      * the class specified above.
 781      *
 782      * <p> Examples:
 783      * <blockquote><pre>
 784      * String.class.getName()
 785      *     returns "java.lang.String"
 786      * byte.class.getName()
 787      *     returns "byte"


 788      * (new Object[3]).getClass().getName()
 789      *     returns "[Ljava.lang.Object;"




 790      * (new int[3][4][5][6][7][8][9]).getClass().getName()
 791      *     returns "[[[[[[[I"
 792      * </pre></blockquote>
 793      *
 794      * @return  the name of the class or interface
 795      *          represented by this object.
 796      */
 797     public String getName() {
 798         String name = this.name;
 799         return name != null ? name : initClassName();
 800     }
 801 
 802     // Cache the name to reduce the number of calls into the VM.
 803     // This field would be set by VM itself during initClassName call.
 804     private transient String name;
 805     private native String initClassName();
 806 
 807     /**
 808      * Returns the class loader for the class.  Some implementations may use
 809      * null to represent the bootstrap class loader. This method will return


1179      * modifiers are the same as those of its component type.  If this
1180      * {@code Class} represents a primitive type or void, its
1181      * {@code public} modifier is always {@code true}, and its
1182      * {@code protected} and {@code private} modifiers are always
1183      * {@code false}. If this object represents an array class, a
1184      * primitive type or void, then its {@code final} modifier is always
1185      * {@code true} and its interface modifier is always
1186      * {@code false}. The values of its other modifiers are not determined
1187      * by this specification.
1188      *
1189      * <p> The modifier encodings are defined in <em>The Java Virtual Machine
1190      * Specification</em>, table 4.1.
1191      *
1192      * @return the {@code int} representing the modifiers for this class
1193      * @see     java.lang.reflect.Modifier
1194      * @since 1.1
1195      */
1196     @HotSpotIntrinsicCandidate
1197     public native int getModifiers();
1198 
1199 
1200     /**
1201      * Gets the signers of this class.
1202      *
1203      * @return  the signers of this class, or null if there are no signers.  In
1204      *          particular, this method returns null if this object represents
1205      *          a primitive type or void.
1206      * @since   1.1
1207      */
1208     public native Object[] getSigners();


1209 

1210 
1211     /**
1212      * Set the signers of this class.
1213      */
1214     native void setSigners(Object[] signers);




1215 
1216 
1217     /**
1218      * If this {@code Class} object represents a local or anonymous
1219      * class within a method, returns a {@link
1220      * java.lang.reflect.Method Method} object representing the
1221      * immediately enclosing method of the underlying class. Returns
1222      * {@code null} otherwise.
1223      *
1224      * In particular, this method returns {@code null} if the underlying
1225      * class is a local or anonymous class immediately enclosed by a type
1226      * declaration, instance initializer or static initializer.
1227      *
1228      * @return the immediately enclosing method of the underlying class, if
1229      *     that class is a local or anonymous class; otherwise {@code null}.
1230      *
1231      * @throws SecurityException
1232      *         If a security manager, <i>s</i>, is present and any of the
1233      *         following conditions is met:
1234      *


1553      * @since 1.5
1554      */
1555     public String getSimpleName() {
1556         ReflectionData<T> rd = reflectionData();
1557         String simpleName = rd.simpleName;
1558         if (simpleName == null) {
1559             rd.simpleName = simpleName = getSimpleName0();
1560         }
1561         return simpleName;
1562     }
1563 
1564     private String getSimpleName0() {
1565         if (isArray()) {
1566             return getComponentType().getSimpleName() + "[]";
1567         }
1568         String simpleName = getSimpleBinaryName();
1569         if (simpleName == null) { // top level class
1570             simpleName = getName();
1571             simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1572         }
1573         return simpleName;
1574     }
1575 
1576     /**
1577      * Return an informative string for the name of this type.
1578      *
1579      * @return an informative string for the name of this type
1580      * @since 1.8
1581      */
1582     public String getTypeName() {
1583         if (isArray()) {
1584             try {
1585                 Class<?> cl = this;
1586                 int dimensions = 0;
1587                 do {
1588                     dimensions++;
1589                     cl = cl.getComponentType();
1590                 } while (cl.isArray());
1591                 return cl.getName() + "[]".repeat(dimensions);
1592             } catch (Throwable e) { /*FALLTHRU*/ }
1593         }
1594         return getName();
1595     }
1596 
1597     /**
1598      * Returns the canonical name of the underlying class as
1599      * defined by the Java Language Specification.  Returns null if
1600      * the underlying class does not have a canonical name (i.e., if
1601      * it is a local or anonymous class or an array whose component
1602      * type does not have a canonical name).
1603      * @return the canonical name of the underlying class if it exists, and
1604      * {@code null} otherwise.
1605      * @since 1.5
1606      */
1607     public String getCanonicalName() {
1608         ReflectionData<T> rd = reflectionData();
1609         String canonicalName = rd.canonicalName;
1610         if (canonicalName == null) {
1611             rd.canonicalName = canonicalName = getCanonicalName0();
1612         }
1613         return canonicalName == ReflectionData.NULL_SENTINEL? null : canonicalName;
1614     }


3399         ReflectionFactory fact = getReflectionFactory();
3400         for (int i = 0; i < out.length; i++) {
3401             out[i] = fact.copyConstructor(out[i]);
3402         }
3403         return out;
3404     }
3405 
3406     private native Field[]       getDeclaredFields0(boolean publicOnly);
3407     private native Method[]      getDeclaredMethods0(boolean publicOnly);
3408     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3409     private native Class<?>[]   getDeclaredClasses0();
3410 
3411     /**
3412      * Helper method to get the method name from arguments.
3413      */
3414     private String methodToString(String name, Class<?>[] argTypes) {
3415         return getName() + '.' + name +
3416                 ((argTypes == null || argTypes.length == 0) ?
3417                 "()" :
3418                 Arrays.stream(argTypes)
3419                         .map(c -> c == null ? "null" : c.getName())
3420                         .collect(Collectors.joining(",", "(", ")")));
3421     }
3422 








3423     /** use serialVersionUID from JDK 1.1 for interoperability */
3424     private static final long serialVersionUID = 3206093459760846163L;
3425 
3426 
3427     /**
3428      * Class Class is special cased within the Serialization Stream Protocol.
3429      *
3430      * A Class instance is written initially into an ObjectOutputStream in the
3431      * following format:
3432      * <pre>
3433      *      {@code TC_CLASS} ClassDescriptor
3434      *      A ClassDescriptor is a special cased serialization of
3435      *      a {@code java.io.ObjectStreamClass} instance.
3436      * </pre>
3437      * A new handle is generated for the initial time the class descriptor
3438      * is written into the stream. Future references to the class descriptor
3439      * are written as references to the initial class descriptor instance.
3440      *
3441      * @see java.io.ObjectStreamClass
3442      */


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


3597      *
3598      * @since 1.5
3599      */
3600     @SuppressWarnings("unchecked")
3601     @HotSpotIntrinsicCandidate
3602     public T cast(Object obj) {



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


3851      *
3852      * <p> If this {@code Class} object represents an interface, the return
3853      * value is an array containing objects representing the uses of interface
3854      * types to specify interfaces directly extended by the interface. The
3855      * order of the objects in the array corresponds to the order of the
3856      * interface types used in the 'extends' clause of the declaration of this
3857      * {@code Class} object.
3858      *
3859      * <p> If this {@code Class} object represents a class or interface whose
3860      * declaration does not explicitly indicate any annotated superinterfaces,
3861      * the return value is an array of length 0.
3862      *
3863      * <p> If this {@code Class} object represents either the {@code Object}
3864      * class, an array type, a primitive type, or void, the return value is an
3865      * array of length 0.
3866      *
3867      * @return an array representing the superinterfaces
3868      * @since 1.8
3869      */
3870     public AnnotatedType[] getAnnotatedInterfaces() {
3871          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3872     }
3873 
3874     private native Class<?> getNestHost0();
3875 
3876     /**
3877      * Returns the nest host of the <a href=#nest>nest</a> to which the class
3878      * or interface represented by this {@code Class} object belongs.
3879      * Every class and interface is a member of exactly one nest.
3880      * A class or interface that is not recorded as belonging to a nest
3881      * belongs to the nest consisting only of itself, and is the nest
3882      * host.
3883      *
3884      * <p>Each of the {@code Class} objects representing array types,
3885      * primitive types, and {@code void} returns {@code this} to indicate
3886      * that the represented entity belongs to the nest consisting only of
3887      * itself, and is the nest host.
3888      *
3889      * <p>If there is a {@linkplain LinkageError linkage error} accessing
3890      * the nest host, or if this class or interface is not enumerated as
3891      * a member of the nest by the nest host, then it is considered to belong




  45 import java.lang.reflect.Member;
  46 import java.lang.reflect.Method;
  47 import java.lang.reflect.Modifier;
  48 import java.lang.reflect.Proxy;
  49 import java.lang.reflect.Type;
  50 import java.lang.reflect.TypeVariable;
  51 import java.lang.constant.Constable;
  52 import java.net.URL;
  53 import java.security.AccessController;
  54 import java.security.PrivilegedAction;
  55 import java.util.ArrayList;
  56 import java.util.Arrays;
  57 import java.util.Collection;
  58 import java.util.HashMap;
  59 import java.util.LinkedHashMap;
  60 import java.util.LinkedHashSet;
  61 import java.util.List;
  62 import java.util.Map;
  63 import java.util.Objects;
  64 import java.util.Optional;


  65 import java.util.stream.Collectors;
  66 
  67 import jdk.internal.HotSpotIntrinsicCandidate;
  68 import jdk.internal.loader.BootLoader;
  69 import jdk.internal.loader.BuiltinClassLoader;
  70 import jdk.internal.misc.Unsafe;
  71 import jdk.internal.module.Resources;
  72 import jdk.internal.reflect.CallerSensitive;
  73 import jdk.internal.reflect.ConstantPool;
  74 import jdk.internal.reflect.Reflection;
  75 import jdk.internal.reflect.ReflectionFactory;
  76 import jdk.internal.vm.annotation.ForceInline;
  77 import sun.invoke.util.Wrapper;
  78 import sun.reflect.generics.factory.CoreReflectionFactory;
  79 import sun.reflect.generics.factory.GenericsFactory;
  80 import sun.reflect.generics.repository.ClassRepository;
  81 import sun.reflect.generics.repository.MethodRepository;
  82 import sun.reflect.generics.repository.ConstructorRepository;
  83 import sun.reflect.generics.scope.ClassScope;
  84 import sun.security.util.SecurityConstants;


 143  *
 144  * <blockquote>
 145  *     {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
 146  * </blockquote>
 147  *
 148  * @param <T> the type of the class modeled by this {@code Class}
 149  * object.  For example, the type of {@code String.class} is {@code
 150  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
 151  * unknown.
 152  *
 153  * @author  unascribed
 154  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
 155  * @since   1.0
 156  */
 157 public final class Class<T> implements java.io.Serializable,
 158                               GenericDeclaration,
 159                               Type,
 160                               AnnotatedElement,
 161                               TypeDescriptor.OfField<Class<?>>,
 162                               Constable {
 163     private static final int ANNOTATION = 0x00002000;
 164     private static final int ENUM       = 0x00004000;
 165     private static final int SYNTHETIC  = 0x00001000;
 166     private static final int VALUE_TYPE = 0x00000100;
 167 
 168     private static native void registerNatives();
 169     static {
 170         registerNatives();
 171     }
 172 
 173     /*
 174      * Private constructor. Only the Java Virtual Machine creates Class objects.
 175      * This constructor is not used and prevents the default constructor being
 176      * generated.
 177      */
 178     private Class(ClassLoader loader, Class<?> arrayComponentType) {
 179         // Initialize final field for classLoader.  The initialization value of non-null
 180         // prevents future JIT optimizations from assuming this final field is null.
 181         classLoader = loader;
 182         componentType = arrayComponentType;
 183     }
 184 
 185     /**
 186      * Converts the object to a string. The string representation is the
 187      * string "class" or "interface", followed by a space, and then by the
 188      * fully qualified name of the class in the format returned by
 189      * {@code getName}.  If this {@code Class} object represents a
 190      * primitive type, this method returns the name of the primitive type.  If
 191      * this {@code Class} object represents void this method returns
 192      * "void". If this {@code Class} object represents an array type,
 193      * this method returns "class " followed by {@code getName}.
 194      *
 195      * @return a string representation of this class object.
 196      */
 197     public String toString() {
 198         return (isInlineClass() ? "inline " : "")
 199                + (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
 200                + getName() + (isInlineClass() && isIndirectType() ? "?" : "");
 201     }
 202 
 203     /**
 204      * Returns a string describing this {@code Class}, including
 205      * information about modifiers and type parameters.
 206      *
 207      * The string is formatted as a list of type modifiers, if any,
 208      * followed by the kind of type (empty string for primitive types
 209      * and {@code class}, {@code enum}, {@code interface}, or
 210      * <code>@</code>{@code interface}, as appropriate), followed
 211      * by the type's name, followed by an angle-bracketed
 212      * comma-separated list of the type's type parameters, if any,
 213      * including informative bounds on the type parameters, if any.
 214      *
 215      * A space is used to separate modifiers from one another and to
 216      * separate any modifiers from the kind of type. The modifiers
 217      * occur in canonical order. If there are no type parameters, the
 218      * type parameter list is elided.
 219      *
 220      * For an array type, the string starts with the type name,


 241             Class<?> component = this;
 242             int arrayDepth = 0;
 243 
 244             if (isArray()) {
 245                 do {
 246                     arrayDepth++;
 247                     component = component.getComponentType();
 248                 } while (component.isArray());
 249                 sb.append(component.getName());
 250             } else {
 251                 // Class modifiers are a superset of interface modifiers
 252                 int modifiers = getModifiers() & Modifier.classModifiers();
 253                 if (modifiers != 0) {
 254                     sb.append(Modifier.toString(modifiers));
 255                     sb.append(' ');
 256                 }
 257 
 258                 if (isAnnotation()) {
 259                     sb.append('@');
 260                 }
 261                 if (isInlineClass()) {
 262                     sb.append("inline");
 263                     sb.append(' ');
 264                 }
 265                 if (isInterface()) { // Note: all annotation types are interfaces
 266                     sb.append("interface");
 267                 } else {
 268                     if (isEnum())
 269                         sb.append("enum");
 270                     else
 271                         sb.append("class");
 272                 }
 273                 sb.append(' ');
 274                 sb.append(getName());
 275             }
 276 
 277             TypeVariable<?>[] typeparms = component.getTypeParameters();
 278             if (typeparms.length > 0) {
 279                 sb.append(Arrays.stream(typeparms)
 280                           .map(Class::typeVarBounds)
 281                           .collect(Collectors.joining(",", "<", ">")));
 282             }
 283 
 284             if (arrayDepth > 0) sb.append("[]".repeat(arrayDepth));


 405     {
 406         Class<?> caller = null;
 407         SecurityManager sm = System.getSecurityManager();
 408         if (sm != null) {
 409             // Reflective call to get caller class is only needed if a security manager
 410             // is present.  Avoid the overhead of making this call otherwise.
 411             caller = Reflection.getCallerClass();
 412             if (loader == null) {
 413                 ClassLoader ccl = ClassLoader.getClassLoader(caller);
 414                 if (ccl != null) {
 415                     sm.checkPermission(
 416                         SecurityConstants.GET_CLASSLOADER_PERMISSION);
 417                 }
 418             }
 419         }
 420         return forName0(name, initialize, loader, caller);
 421     }
 422 
 423     /** Called after security check for system loader access checks have been made. */
 424     private static native Class<?> forName0(String name, boolean initialize,
 425                                     ClassLoader loader,
 426                                     Class<?> caller)
 427         throws ClassNotFoundException;
 428 
 429 
 430     /**
 431      * Returns the {@code Class} with the given <a href="ClassLoader.html#binary-name">
 432      * binary name</a> in the given module.
 433      *
 434      * <p> This method attempts to locate, load, and link the class or interface.
 435      * It does not run the class initializer.  If the class is not found, this
 436      * method returns {@code null}. </p>
 437      *
 438      * <p> If the class loader of the given module defines other modules and
 439      * the given name is a class defined in a different module, this method
 440      * returns {@code null} after the class is loaded. </p>
 441      *
 442      * <p> This method does not check whether the requested class is
 443      * accessible to its caller. </p>
 444      *
 445      * @apiNote
 446      * This method returns {@code null} on failure rather than


 482         if (sm != null) {
 483             Class<?> caller = Reflection.getCallerClass();
 484             if (caller != null && caller.getModule() != module) {
 485                 // if caller is null, Class.forName is the last java frame on the stack.
 486                 // java.base has all permissions
 487                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 488             }
 489             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
 490             cl = AccessController.doPrivileged(pa);
 491         } else {
 492             cl = module.getClassLoader();
 493         }
 494 
 495         if (cl != null) {
 496             return cl.loadClass(module, name);
 497         } else {
 498             return BootLoader.loadClass(module, name);
 499         }
 500     }
 501 
 502 
 503     /**
 504      * Returns {@code true} if this class is an inline class.
 505      *
 506      * @return {@code true} if this class is an inline class.
 507      */
 508     public boolean isInlineClass() {
 509         return (this.getModifiers() & VALUE_TYPE) != 0;
 510     }
 511 
 512     /**
 513      * Returns a {@code Class} object representing the primary type of
 514      * this class.
 515      *
 516      * <p> For class {@code C}, {@code C.class} is the primary type of {@code C}.
 517      * For a primitive type, the {@code Class} instance representing
 518      * that primitive type is its primary type, for example {@code int.class}.
 519      *
 520      * @return the {@code Class} object representing the primary type of
 521      *         this class
 522      */
 523     @HotSpotIntrinsicCandidate
 524     public Class<T> asPrimaryType() {
 525         return isInlineClass() ? inlineType : this;
 526     }
 527 
 528     /**
 529      * Returns a {@code Class} object representing the <em>indirect projection</em>
 530      * type if this class is an {@linkplain #isInlineClass() inline class};
 531      * otherwise, returns this class.
 532      *
 533      * <p> An inline class, {@code V}, has two {@code Class} representations,
 534      * {@code V.class} and its {@linkplain #asIndirectType() indirect projection
 535      * type}.  The indirect projection type is always
 536      * {@linkplain #isNullableType() nullable}.
 537      * The indirect projection type of a zero-default inline class
 538      * is also its nullable projection type.
 539      *
 540      * @return the {@code Class} object representing the indirect projection type of
 541      *         this class if this class is an inline class; otherwise, this class.
 542      */
 543     @HotSpotIntrinsicCandidate
 544     public Class<T> asIndirectType() {
 545         return isInlineClass() ? indirectType : this;
 546     }
 547 
 548     /**
 549      * Returns a {@code Class} object representing the <em>nullable projection</em>
 550      * type if this class is an {@linkplain #isInlineClass() inline class};
 551      * otherwise, returns this class.
 552      *
 553      * <p> An inline class, {@code V}, has two {@code Class} representations,
 554      * {@code V.class} and its {@linkplain #asIndirectType() indirect projection
 555      * type}.  The indirect projection type is always
 556      * {@linkplain #isNullableType() nullable}.
 557      * The indirect projection type of a zero-default inline class
 558      * is also its nullable projection type.
 559      *
 560      * @return the {@code Class} object representing the nullable projection type of
 561      *         this class if this class is an inline class; otherwise, this class.
 562      */
 563     public Class<T> asNullableType() {
 564         return asIndirectType();
 565     }
 566 
 567     /**
 568      * Returns {@code true} if this class is an indirect type.
 569      * An indirect type is always {@linkplain #isNullableType() nullable}.
 570      *
 571      * @return {@code true} if this class is an indirect type.
 572      */
 573     public boolean isIndirectType() {
 574         return indirectType == null || this == indirectType;
 575     }
 576 
 577     /**
 578      * Returns {@code true} if this class is a nullable type.
 579      *
 580      * @return {@code true} if this class is a nullable type.
 581      */
 582     public boolean isNullableType() {
 583         return isIndirectType();
 584     }
 585 
 586     // set by VM if this class is an inline type
 587     // otherwise, these two fields are null
 588     private transient Class<T> inlineType;
 589     private transient Class<T> indirectType;
 590 
 591     /**
 592      * Creates a new instance of the class represented by this {@code Class}
 593      * object.  The class is instantiated as if by a {@code new}
 594      * expression with an empty argument list.  The class is initialized if it
 595      * has not already been initialized.
 596      *
 597      * @deprecated This method propagates any exception thrown by the
 598      * nullary constructor, including a checked exception.  Use of
 599      * this method effectively bypasses the compile-time exception
 600      * checking that would otherwise be performed by the compiler.
 601      * The {@link
 602      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
 603      * Constructor.newInstance} method avoids this problem by wrapping
 604      * any exception thrown by the constructor in a (checked) {@link
 605      * java.lang.reflect.InvocationTargetException}.
 606      *
 607      * <p>The call
 608      *
 609      * <pre>{@code
 610      * clazz.newInstance()


 844      * <p> If this class object represents a primitive type or void, then the
 845      * name returned is a {@code String} equal to the Java language
 846      * keyword corresponding to the primitive type or void.
 847      *
 848      * <p> If this class object represents a class of arrays, then the internal
 849      * form of the name consists of the name of the element type preceded by
 850      * one or more '{@code [}' characters representing the depth of the array
 851      * nesting.  The encoding of element type names is as follows:
 852      *
 853      * <blockquote><table class="striped">
 854      * <caption style="display:none">Element types and encodings</caption>
 855      * <thead>
 856      * <tr><th scope="col"> Element Type <th scope="col"> Encoding
 857      * </thead>
 858      * <tbody style="text-align:left">
 859      * <tr><th scope="row"> boolean      <td style="text-align:center"> Z
 860      * <tr><th scope="row"> byte         <td style="text-align:center"> B
 861      * <tr><th scope="row"> char         <td style="text-align:center"> C
 862      * <tr><th scope="row"> class or interface
 863      *                                   <td style="text-align:center"> L<i>classname</i>;
 864      * <tr><th scope="row"> non-nullable {@linkplain #isInlineClass() inline class}
 865      *                                   <td style="text-align:center"> Q<i>classname</i>;
 866      * <tr><th scope="row"> double       <td style="text-align:center"> D
 867      * <tr><th scope="row"> float        <td style="text-align:center"> F
 868      * <tr><th scope="row"> int          <td style="text-align:center"> I
 869      * <tr><th scope="row"> long         <td style="text-align:center"> J
 870      * <tr><th scope="row"> short        <td style="text-align:center"> S
 871      * </tbody>
 872      * </table></blockquote>
 873      *
 874      * <p> The class or interface name <i>classname</i> is the binary name of
 875      * the class specified above.
 876      *
 877      * <p> Examples:
 878      * <blockquote><pre>
 879      * String.class.getName()
 880      *     returns "java.lang.String"
 881      * byte.class.getName()
 882      *     returns "byte"
 883      * Point.class.getName()
 884      *     returns "Point"
 885      * (new Object[3]).getClass().getName()
 886      *     returns "[Ljava.lang.Object;"
 887      * (new Point[3]).getClass().getName()
 888      *     returns "[QPoint;"
 889      * (new Point?[3][4]).getClass().getName()
 890      *     returns "[[LPoint;"
 891      * (new int[3][4][5][6][7][8][9]).getClass().getName()
 892      *     returns "[[[[[[[I"
 893      * </pre></blockquote>
 894      *
 895      * @return  the name of the class or interface
 896      *          represented by this object.
 897      */
 898     public String getName() {
 899         String name = this.name;
 900         return name != null ? name : initClassName();
 901     }
 902 
 903     // Cache the name to reduce the number of calls into the VM.
 904     // This field would be set by VM itself during initClassName call.
 905     private transient String name;
 906     private native String initClassName();
 907 
 908     /**
 909      * Returns the class loader for the class.  Some implementations may use
 910      * null to represent the bootstrap class loader. This method will return


1280      * modifiers are the same as those of its component type.  If this
1281      * {@code Class} represents a primitive type or void, its
1282      * {@code public} modifier is always {@code true}, and its
1283      * {@code protected} and {@code private} modifiers are always
1284      * {@code false}. If this object represents an array class, a
1285      * primitive type or void, then its {@code final} modifier is always
1286      * {@code true} and its interface modifier is always
1287      * {@code false}. The values of its other modifiers are not determined
1288      * by this specification.
1289      *
1290      * <p> The modifier encodings are defined in <em>The Java Virtual Machine
1291      * Specification</em>, table 4.1.
1292      *
1293      * @return the {@code int} representing the modifiers for this class
1294      * @see     java.lang.reflect.Modifier
1295      * @since 1.1
1296      */
1297     @HotSpotIntrinsicCandidate
1298     public native int getModifiers();
1299 

1300     /**
1301      * Gets the signers of this class.
1302      *
1303      * @return  the signers of this class, or null if there are no signers.  In
1304      *          particular, this method returns null if this object represents
1305      *          a primitive type or void.
1306      * @since   1.1
1307      */
1308     public Object[] getSigners() {
1309         return asPrimaryType().getSigners0();
1310     }
1311 
1312     private native Object[] getSigners0();
1313 
1314     /**
1315      * Set the signers of this class.
1316      */
1317     void setSigners(Object[] signers) {
1318         asPrimaryType().setSigners0(signers);
1319     }
1320 
1321     native void setSigners0(Object[] signers);
1322 
1323 
1324     /**
1325      * If this {@code Class} object represents a local or anonymous
1326      * class within a method, returns a {@link
1327      * java.lang.reflect.Method Method} object representing the
1328      * immediately enclosing method of the underlying class. Returns
1329      * {@code null} otherwise.
1330      *
1331      * In particular, this method returns {@code null} if the underlying
1332      * class is a local or anonymous class immediately enclosed by a type
1333      * declaration, instance initializer or static initializer.
1334      *
1335      * @return the immediately enclosing method of the underlying class, if
1336      *     that class is a local or anonymous class; otherwise {@code null}.
1337      *
1338      * @throws SecurityException
1339      *         If a security manager, <i>s</i>, is present and any of the
1340      *         following conditions is met:
1341      *


1660      * @since 1.5
1661      */
1662     public String getSimpleName() {
1663         ReflectionData<T> rd = reflectionData();
1664         String simpleName = rd.simpleName;
1665         if (simpleName == null) {
1666             rd.simpleName = simpleName = getSimpleName0();
1667         }
1668         return simpleName;
1669     }
1670 
1671     private String getSimpleName0() {
1672         if (isArray()) {
1673             return getComponentType().getSimpleName() + "[]";
1674         }
1675         String simpleName = getSimpleBinaryName();
1676         if (simpleName == null) { // top level class
1677             simpleName = getName();
1678             simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1679         }
1680         return isInlineClass() && isIndirectType() ? simpleName + "?" : simpleName;
1681     }
1682 
1683     /**
1684      * Return an informative string for the name of this type.
1685      *
1686      * @return an informative string for the name of this type
1687      * @since 1.8
1688      */
1689     public String getTypeName() {
1690         if (isArray()) {
1691             try {
1692                 Class<?> cl = this;
1693                 int dimensions = 0;
1694                 do {
1695                     dimensions++;
1696                     cl = cl.getComponentType();
1697                 } while (cl.isArray());
1698                 return cl.getTypeName() + "[]".repeat(dimensions);
1699             } catch (Throwable e) { /*FALLTHRU*/ }
1700         }
1701         return toTypeName();
1702     }
1703 
1704     /**
1705      * Returns the canonical name of the underlying class as
1706      * defined by the Java Language Specification.  Returns null if
1707      * the underlying class does not have a canonical name (i.e., if
1708      * it is a local or anonymous class or an array whose component
1709      * type does not have a canonical name).
1710      * @return the canonical name of the underlying class if it exists, and
1711      * {@code null} otherwise.
1712      * @since 1.5
1713      */
1714     public String getCanonicalName() {
1715         ReflectionData<T> rd = reflectionData();
1716         String canonicalName = rd.canonicalName;
1717         if (canonicalName == null) {
1718             rd.canonicalName = canonicalName = getCanonicalName0();
1719         }
1720         return canonicalName == ReflectionData.NULL_SENTINEL? null : canonicalName;
1721     }


3506         ReflectionFactory fact = getReflectionFactory();
3507         for (int i = 0; i < out.length; i++) {
3508             out[i] = fact.copyConstructor(out[i]);
3509         }
3510         return out;
3511     }
3512 
3513     private native Field[]       getDeclaredFields0(boolean publicOnly);
3514     private native Method[]      getDeclaredMethods0(boolean publicOnly);
3515     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3516     private native Class<?>[]   getDeclaredClasses0();
3517 
3518     /**
3519      * Helper method to get the method name from arguments.
3520      */
3521     private String methodToString(String name, Class<?>[] argTypes) {
3522         return getName() + '.' + name +
3523                 ((argTypes == null || argTypes.length == 0) ?
3524                 "()" :
3525                 Arrays.stream(argTypes)
3526                         .map(c -> c == null ? "null" : c.toTypeName())
3527                         .collect(Collectors.joining(",", "(", ")")));
3528     }
3529 
3530     /*
3531      * Returns the class name appended with "?" if it is the nullable projection
3532      * of an inline class.
3533      */
3534     private String toTypeName() {
3535         return isInlineClass() && isIndirectType() ? getName() + "?" : getName();
3536     }
3537 
3538     /** use serialVersionUID from JDK 1.1 for interoperability */
3539     private static final long serialVersionUID = 3206093459760846163L;
3540 
3541 
3542     /**
3543      * Class Class is special cased within the Serialization Stream Protocol.
3544      *
3545      * A Class instance is written initially into an ObjectOutputStream in the
3546      * following format:
3547      * <pre>
3548      *      {@code TC_CLASS} ClassDescriptor
3549      *      A ClassDescriptor is a special cased serialization of
3550      *      a {@code java.io.ObjectStreamClass} instance.
3551      * </pre>
3552      * A new handle is generated for the initial time the class descriptor
3553      * is written into the stream. Future references to the class descriptor
3554      * are written as references to the initial class descriptor instance.
3555      *
3556      * @see java.io.ObjectStreamClass
3557      */


3691                 throw new IllegalArgumentException(
3692                     getName() + " is not an enum type");
3693             directory = new HashMap<>((int)(universe.length / 0.75f) + 1);
3694             for (T constant : universe) {
3695                 directory.put(((Enum<?>)constant).name(), constant);
3696             }
3697             enumConstantDirectory = directory;
3698         }
3699         return directory;
3700     }
3701     private transient volatile Map<String, T> enumConstantDirectory;
3702 
3703     /**
3704      * Casts an object to the class or interface represented
3705      * by this {@code Class} object.
3706      *
3707      * @param obj the object to be cast
3708      * @return the object after casting, or null if obj is null
3709      *
3710      * @throws ClassCastException if the object is not
3711      * {@code null} and is not assignable to the type T.
3712      * @throws NullPointerException if this is not a {@linkplain #isNullableType()
3713      * nullable type} and the object is {@code null}
3714      *
3715      * @since 1.5
3716      */
3717     @SuppressWarnings("unchecked")
3718     @HotSpotIntrinsicCandidate
3719     public T cast(Object obj) {
3720         if (!isNullableType() && obj == null)
3721             throw new NullPointerException(getName() + " is an inline class");
3722 
3723         if (obj != null && !isInstance(obj))
3724             throw new ClassCastException(cannotCastMsg(obj));
3725         return (T) obj;
3726     }
3727 
3728     private String cannotCastMsg(Object obj) {
3729         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3730     }
3731 
3732     /**
3733      * Casts this {@code Class} object to represent a subclass of the class
3734      * represented by the specified class object.  Checks that the cast
3735      * is valid, and throws a {@code ClassCastException} if it is not.  If
3736      * this method succeeds, it always returns a reference to this class object.
3737      *
3738      * <p>This method is useful when a client needs to "narrow" the type of
3739      * a {@code Class} object to pass it to an API that restricts the
3740      * {@code Class} objects that it is willing to accept.  A cast would
3741      * generate a compile-time warning, as the correctness of the cast
3742      * could not be checked at runtime (because generic types are implemented


3971      *
3972      * <p> If this {@code Class} object represents an interface, the return
3973      * value is an array containing objects representing the uses of interface
3974      * types to specify interfaces directly extended by the interface. The
3975      * order of the objects in the array corresponds to the order of the
3976      * interface types used in the 'extends' clause of the declaration of this
3977      * {@code Class} object.
3978      *
3979      * <p> If this {@code Class} object represents a class or interface whose
3980      * declaration does not explicitly indicate any annotated superinterfaces,
3981      * the return value is an array of length 0.
3982      *
3983      * <p> If this {@code Class} object represents either the {@code Object}
3984      * class, an array type, a primitive type, or void, the return value is an
3985      * array of length 0.
3986      *
3987      * @return an array representing the superinterfaces
3988      * @since 1.8
3989      */
3990     public AnnotatedType[] getAnnotatedInterfaces() {
3991         return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3992     }
3993 
3994     private native Class<?> getNestHost0();
3995 
3996     /**
3997      * Returns the nest host of the <a href=#nest>nest</a> to which the class
3998      * or interface represented by this {@code Class} object belongs.
3999      * Every class and interface is a member of exactly one nest.
4000      * A class or interface that is not recorded as belonging to a nest
4001      * belongs to the nest consisting only of itself, and is the nest
4002      * host.
4003      *
4004      * <p>Each of the {@code Class} objects representing array types,
4005      * primitive types, and {@code void} returns {@code this} to indicate
4006      * that the represented entity belongs to the nest consisting only of
4007      * itself, and is the nest host.
4008      *
4009      * <p>If there is a {@linkplain LinkageError linkage error} accessing
4010      * the nest host, or if this class or interface is not enumerated as
4011      * a member of the nest by the nest host, then it is considered to belong


< prev index next >