< prev index next >

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

Print this page




  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 import java.lang.annotation.Annotation;
  29 import java.lang.constant.ClassDesc;
  30 import java.lang.invoke.TypeDescriptor;

  31 import java.lang.module.ModuleReader;
  32 import java.lang.ref.SoftReference;
  33 import java.io.IOException;
  34 import java.io.InputStream;
  35 import java.io.ObjectStreamField;
  36 import java.lang.reflect.AnnotatedElement;
  37 import java.lang.reflect.AnnotatedType;
  38 import java.lang.reflect.Array;
  39 import java.lang.reflect.Constructor;
  40 import java.lang.reflect.Executable;
  41 import java.lang.reflect.Field;
  42 import java.lang.reflect.GenericArrayType;
  43 import java.lang.reflect.GenericDeclaration;
  44 import java.lang.reflect.InvocationTargetException;
  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;


 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));

 281 
 282             return sb.toString();
 283         }
 284     }
 285 
 286     static String typeVarBounds(TypeVariable<?> typeVar) {
 287         Type[] bounds = typeVar.getBounds();
 288         if (bounds.length == 1 && bounds[0].equals(Object.class)) {
 289             return typeVar.getName();
 290         } else {
 291             return typeVar.getName() + " extends " +
 292                 Arrays.stream(bounds)
 293                 .map(Type::getTypeName)
 294                 .collect(Collectors.joining(" & "));
 295         }
 296     }
 297 
 298     /**
 299      * Returns the {@code Class} object associated with the class or
 300      * interface with the given string name.  Invoking this method is


 307      * where {@code currentLoader} denotes the defining class loader of
 308      * the current class.
 309      *
 310      * <p> For example, the following code fragment returns the
 311      * runtime {@code Class} descriptor for the class named
 312      * {@code java.lang.Thread}:
 313      *
 314      * <blockquote>
 315      *   {@code Class t = Class.forName("java.lang.Thread")}
 316      * </blockquote>
 317      * <p>
 318      * A call to {@code forName("X")} causes the class named
 319      * {@code X} to be initialized.
 320      *
 321      * @param      className   the fully qualified name of the desired class.
 322      * @return     the {@code Class} object for the class with the
 323      *             specified name.
 324      * @exception LinkageError if the linkage fails
 325      * @exception ExceptionInInitializerError if the initialization provoked
 326      *            by this method fails
 327      * @exception ClassNotFoundException if the class cannot be located



 328      */
 329     @CallerSensitive
 330     public static Class<?> forName(String className)
 331                 throws ClassNotFoundException {
 332         Class<?> caller = Reflection.getCallerClass();
 333         return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
 334     }
 335 
 336 
 337     /**
 338      * Returns the {@code Class} object associated with the class or
 339      * interface with the given string name, using the given class loader.
 340      * Given the fully qualified name for a class or interface (in the same
 341      * format returned by {@code getName}) this method attempts to
 342      * locate, load, and link the class or interface.  The specified class
 343      * loader is used to load the class or interface.  If the parameter
 344      * {@code loader} is null, the class is loaded through the bootstrap
 345      * class loader.  The class is initialized only if the
 346      * {@code initialize} parameter is {@code true} and if it has
 347      * not been initialized earlier.


 366      * <blockquote>
 367      *  {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
 368      * </blockquote>
 369      *
 370      * Note that this method throws errors related to loading, linking or
 371      * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
 372      * Java Language Specification</em>.
 373      * Note that this method does not check whether the requested class
 374      * is accessible to its caller.
 375      *
 376      * @param name       fully qualified name of the desired class
 377      * @param initialize if {@code true} the class will be initialized.
 378      *                   See Section 12.4 of <em>The Java Language Specification</em>.
 379      * @param loader     class loader from which the class must be loaded
 380      * @return           class object representing the desired class
 381      *
 382      * @exception LinkageError if the linkage fails
 383      * @exception ExceptionInInitializerError if the initialization provoked
 384      *            by this method fails
 385      * @exception ClassNotFoundException if the class cannot be located by
 386      *            the specified class loader

 387      * @exception SecurityException
 388      *            if a security manager is present, and the {@code loader} is
 389      *            {@code null}, and the caller's class loader is not
 390      *            {@code null}, and the caller does not have the
 391      *            {@link RuntimePermission}{@code ("getClassLoader")}
 392      *
 393      * @see       java.lang.Class#forName(String)
 394      * @see       java.lang.ClassLoader

 395      * @since     1.2
 396      */
 397     @CallerSensitive
 398     public static Class<?> forName(String name, boolean initialize,
 399                                    ClassLoader loader)
 400         throws ClassNotFoundException
 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             }


 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
 443      * throwing a {@link ClassNotFoundException}, as is done by
 444      * the {@link #forName(String, boolean, ClassLoader)} method.
 445      * The security check is a stack-based permission check if the caller
 446      * loads a class in another module.
 447      *
 448      * @param  module   A module
 449      * @param  name     The <a href="ClassLoader.html#binary-name">binary name</a>
 450      *                  of the class
 451      * @return {@code Class} object of the given name defined in the given module;
 452      *         {@code null} if not found.

 453      *
 454      * @throws NullPointerException if the given module or name is {@code null}
 455      *
 456      * @throws LinkageError if the linkage fails
 457      *
 458      * @throws SecurityException
 459      *         <ul>
 460      *         <li> if the caller is not the specified module and
 461      *         {@code RuntimePermission("getClassLoader")} permission is denied; or</li>
 462      *         <li> access to the module content is denied. For example,
 463      *         permission check will be performed when a class loader calls
 464      *         {@link ModuleReader#open(String)} to read the bytes of a class file
 465      *         in a module.</li>
 466      *         </ul>
 467      *

 468      * @since 9
 469      * @spec JPMS
 470      */
 471     @CallerSensitive
 472     public static Class<?> forName(Module module, String name) {
 473         Objects.requireNonNull(module);
 474         Objects.requireNonNull(name);
 475 
 476         ClassLoader cl;
 477         SecurityManager sm = System.getSecurityManager();
 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 {


 848      * {@code Module} for the element type. If this class represents a
 849      * primitive type or void, then the {@code Module} object for the
 850      * {@code java.base} module is returned.
 851      *
 852      * If this class is in an unnamed module then the {@linkplain
 853      * ClassLoader#getUnnamedModule() unnamed} {@code Module} of the class
 854      * loader for this class is returned.
 855      *
 856      * @return the module that this class or interface is a member of
 857      *
 858      * @since 9
 859      * @spec JPMS
 860      */
 861     public Module getModule() {
 862         return module;
 863     }
 864 
 865     // set by VM
 866     private transient Module module;
 867 






 868     // Initialized in JVM not by private constructor
 869     // This field is filtered from reflection access, i.e. getDeclaredField
 870     // will throw NoSuchFieldException
 871     private final ClassLoader classLoader;
 872 
 873     /**
 874      * Returns an array of {@code TypeVariable} objects that represent the
 875      * type variables declared by the generic declaration represented by this
 876      * {@code GenericDeclaration} object, in declaration order.  Returns an
 877      * array of length 0 if the underlying generic declaration declares no type
 878      * variables.
 879      *
 880      * @return an array of {@code TypeVariable} objects that represent
 881      *     the type variables declared by this generic declaration
 882      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
 883      *     signature of this generic declaration does not conform to
 884      *     the format specified in
 885      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 886      * @since 1.5
 887      */


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();


2780      * ensure it's ok to get the
2781      * {@code ProtectionDomain}.
2782      *
2783      * @return the ProtectionDomain of this class
2784      *
2785      * @throws SecurityException
2786      *        if a security manager exists and its
2787      *        {@code checkPermission} method doesn't allow
2788      *        getting the ProtectionDomain.
2789      *
2790      * @see java.security.ProtectionDomain
2791      * @see SecurityManager#checkPermission
2792      * @see java.lang.RuntimePermission
2793      * @since 1.2
2794      */
2795     public java.security.ProtectionDomain getProtectionDomain() {
2796         SecurityManager sm = System.getSecurityManager();
2797         if (sm != null) {
2798             sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
2799         }





2800         java.security.ProtectionDomain pd = getProtectionDomain0();
2801         if (pd == null) {
2802             if (allPermDomain == null) {
2803                 java.security.Permissions perms =
2804                     new java.security.Permissions();
2805                 perms.add(SecurityConstants.ALL_PERMISSION);
2806                 allPermDomain =
2807                     new java.security.ProtectionDomain(null, perms);
2808             }
2809             pd = allPermDomain;
2810         }
2811         return pd;
2812     }
2813 
2814 
2815     /**
2816      * Returns the ProtectionDomain of this class.
2817      */
2818     private native java.security.ProtectionDomain getProtectionDomain0();
2819 
2820     /*
2821      * Return the Virtual Machine's Class object for the named
2822      * primitive type.
2823      */
2824     static native Class<?> getPrimitiveClass(String name);
2825 
2826     /*
2827      * Check if client is allowed to access members.  If access is denied,
2828      * throw a SecurityException.
2829      *
2830      * This method also enforces package access.
2831      *
2832      * <p> Default policy: allow all clients access with normal Java access
2833      * control.
2834      *


3395     }
3396 
3397     private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
3398         Constructor<U>[] out = arg.clone();
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      *


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
3892      * to its own nest and {@code this} is returned as the host.
3893      *
3894      * @apiNote A {@code class} file of version 55.0 or greater may record the
3895      * host of the nest to which it belongs by using the {@code NestHost}
3896      * attribute (JVMS 4.7.28). Alternatively, a {@code class} file of
3897      * version 55.0 or greater may act as a nest host by enumerating the nest's
3898      * other members with the
3899      * {@code NestMembers} attribute (JVMS 4.7.29).
3900      * A {@code class} file of version 54.0 or lower does not use these
3901      * attributes.




3902      *
3903      * @return the nest host of this class or interface
3904      *
3905      * @throws SecurityException
3906      *         If the returned class is not the current class, and
3907      *         if a security manager, <i>s</i>, is present and the caller's
3908      *         class loader is not the same as or an ancestor of the class
3909      *         loader for the returned class and invocation of {@link
3910      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
3911      *         denies access to the package of the returned class
3912      * @since 11
3913      * @jvms 4.7.28 and 4.7.29 NestHost and NestMembers attributes
3914      * @jvms 5.4.4 Access Control
3915      */
3916     @CallerSensitive
3917     public Class<?> getNestHost() {
3918         if (isPrimitive() || isArray()) {
3919             return this;
3920         }
3921         Class<?> host;


3973      * Returns an array containing {@code Class} objects representing all the
3974      * classes and interfaces that are members of the nest to which the class
3975      * or interface represented by this {@code Class} object belongs.
3976      * The {@linkplain #getNestHost() nest host} of that nest is the zeroth
3977      * element of the array. Subsequent elements represent any classes or
3978      * interfaces that are recorded by the nest host as being members of
3979      * the nest; the order of such elements is unspecified. Duplicates are
3980      * permitted.
3981      * If the nest host of that nest does not enumerate any members, then the
3982      * array has a single element containing {@code this}.
3983      *
3984      * <p>Each of the {@code Class} objects representing array types,
3985      * primitive types, and {@code void} returns an array containing only
3986      * {@code this}.
3987      *
3988      * <p>This method validates that, for each class or interface which is
3989      * recorded as a member of the nest by the nest host, that class or
3990      * interface records itself as a member of that same nest. Any exceptions
3991      * that occur during this validation are rethrown by this method.
3992      *











3993      * @return an array of all classes and interfaces in the same nest as
3994      * this class
3995      *
3996      * @throws LinkageError
3997      *         If there is any problem loading or validating a nest member or
3998      *         its nest host
3999      * @throws SecurityException
4000      *         If any returned class is not the current class, and
4001      *         if a security manager, <i>s</i>, is present and the caller's
4002      *         class loader is not the same as or an ancestor of the class
4003      *         loader for that returned class and invocation of {@link
4004      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
4005      *         denies access to the package of that returned class
4006      *
4007      * @since 11
4008      * @see #getNestHost()

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


4073      *
4074      * @return a {@code Class} describing the array type
4075      * @since 12
4076      */
4077     @Override
4078     public Class<?> arrayType() {
4079         return Array.newInstance(this, 0).getClass();
4080     }
4081 
4082     /**
4083      * Returns a nominal descriptor for this instance, if one can be
4084      * constructed, or an empty {@link Optional} if one cannot be.
4085      *
4086      * @return An {@link Optional} containing the resulting nominal descriptor,
4087      * or an empty {@link Optional} if one cannot be constructed.
4088      * @since 12
4089      */
4090     @Override
4091     public Optional<ClassDesc> describeConstable() {
4092         return Optional.of(ClassDesc.ofDescriptor(descriptorString()));





































4093     }
4094 }


  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 import java.lang.annotation.Annotation;
  29 import java.lang.constant.ClassDesc;
  30 import java.lang.invoke.TypeDescriptor;
  31 import java.lang.invoke.MethodHandles;
  32 import java.lang.module.ModuleReader;
  33 import java.lang.ref.SoftReference;
  34 import java.io.IOException;
  35 import java.io.InputStream;
  36 import java.io.ObjectStreamField;
  37 import java.lang.reflect.AnnotatedElement;
  38 import java.lang.reflect.AnnotatedType;
  39 import java.lang.reflect.Array;
  40 import java.lang.reflect.Constructor;
  41 import java.lang.reflect.Executable;
  42 import java.lang.reflect.Field;
  43 import java.lang.reflect.GenericArrayType;
  44 import java.lang.reflect.GenericDeclaration;
  45 import java.lang.reflect.InvocationTargetException;
  46 import java.lang.reflect.Member;
  47 import java.lang.reflect.Method;
  48 import java.lang.reflect.Modifier;
  49 import java.lang.reflect.Proxy;
  50 import java.lang.reflect.Type;
  51 import java.lang.reflect.TypeVariable;


 261                 }
 262                 if (isInterface()) { // Note: all annotation types are interfaces
 263                     sb.append("interface");
 264                 } else {
 265                     if (isEnum())
 266                         sb.append("enum");
 267                     else
 268                         sb.append("class");
 269                 }
 270                 sb.append(' ');
 271                 sb.append(getName());
 272             }
 273 
 274             TypeVariable<?>[] typeparms = component.getTypeParameters();
 275             if (typeparms.length > 0) {
 276                 sb.append(Arrays.stream(typeparms)
 277                           .map(Class::typeVarBounds)
 278                           .collect(Collectors.joining(",", "<", ">")));
 279             }
 280 
 281             for (int i = 0; i < arrayDepth; i++)
 282                 sb.append("[]");
 283 
 284             return sb.toString();
 285         }
 286     }
 287 
 288     static String typeVarBounds(TypeVariable<?> typeVar) {
 289         Type[] bounds = typeVar.getBounds();
 290         if (bounds.length == 1 && bounds[0].equals(Object.class)) {
 291             return typeVar.getName();
 292         } else {
 293             return typeVar.getName() + " extends " +
 294                 Arrays.stream(bounds)
 295                 .map(Type::getTypeName)
 296                 .collect(Collectors.joining(" & "));
 297         }
 298     }
 299 
 300     /**
 301      * Returns the {@code Class} object associated with the class or
 302      * interface with the given string name.  Invoking this method is


 309      * where {@code currentLoader} denotes the defining class loader of
 310      * the current class.
 311      *
 312      * <p> For example, the following code fragment returns the
 313      * runtime {@code Class} descriptor for the class named
 314      * {@code java.lang.Thread}:
 315      *
 316      * <blockquote>
 317      *   {@code Class t = Class.forName("java.lang.Thread")}
 318      * </blockquote>
 319      * <p>
 320      * A call to {@code forName("X")} causes the class named
 321      * {@code X} to be initialized.
 322      *
 323      * @param      className   the fully qualified name of the desired class.
 324      * @return     the {@code Class} object for the class with the
 325      *             specified name.
 326      * @exception LinkageError if the linkage fails
 327      * @exception ExceptionInInitializerError if the initialization provoked
 328      *            by this method fails
 329      * @exception ClassNotFoundException if the class cannot be located, or
 330      *            the class is {@linkplain #isHidden() hidden}
 331      *
 332      * @see Class#isHidden
 333      */
 334     @CallerSensitive
 335     public static Class<?> forName(String className)
 336                 throws ClassNotFoundException {
 337         Class<?> caller = Reflection.getCallerClass();
 338         return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
 339     }
 340 
 341 
 342     /**
 343      * Returns the {@code Class} object associated with the class or
 344      * interface with the given string name, using the given class loader.
 345      * Given the fully qualified name for a class or interface (in the same
 346      * format returned by {@code getName}) this method attempts to
 347      * locate, load, and link the class or interface.  The specified class
 348      * loader is used to load the class or interface.  If the parameter
 349      * {@code loader} is null, the class is loaded through the bootstrap
 350      * class loader.  The class is initialized only if the
 351      * {@code initialize} parameter is {@code true} and if it has
 352      * not been initialized earlier.


 371      * <blockquote>
 372      *  {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
 373      * </blockquote>
 374      *
 375      * Note that this method throws errors related to loading, linking or
 376      * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
 377      * Java Language Specification</em>.
 378      * Note that this method does not check whether the requested class
 379      * is accessible to its caller.
 380      *
 381      * @param name       fully qualified name of the desired class
 382      * @param initialize if {@code true} the class will be initialized.
 383      *                   See Section 12.4 of <em>The Java Language Specification</em>.
 384      * @param loader     class loader from which the class must be loaded
 385      * @return           class object representing the desired class
 386      *
 387      * @exception LinkageError if the linkage fails
 388      * @exception ExceptionInInitializerError if the initialization provoked
 389      *            by this method fails
 390      * @exception ClassNotFoundException if the class cannot be located by
 391      *            the specified class loader, or
 392      *            the class is {@linkplain #isHidden() hidden}
 393      * @exception SecurityException
 394      *            if a security manager is present, and the {@code loader} is
 395      *            {@code null}, and the caller's class loader is not
 396      *            {@code null}, and the caller does not have the
 397      *            {@link RuntimePermission}{@code ("getClassLoader")}
 398      *
 399      * @see       java.lang.Class#forName(String)
 400      * @see       java.lang.ClassLoader
 401      * @see       java.lang.Class#isHidden
 402      * @since     1.2
 403      */
 404     @CallerSensitive
 405     public static Class<?> forName(String name, boolean initialize,
 406                                    ClassLoader loader)
 407         throws ClassNotFoundException
 408     {
 409         Class<?> caller = null;
 410         SecurityManager sm = System.getSecurityManager();
 411         if (sm != null) {
 412             // Reflective call to get caller class is only needed if a security manager
 413             // is present.  Avoid the overhead of making this call otherwise.
 414             caller = Reflection.getCallerClass();
 415             if (loader == null) {
 416                 ClassLoader ccl = ClassLoader.getClassLoader(caller);
 417                 if (ccl != null) {
 418                     sm.checkPermission(
 419                         SecurityConstants.GET_CLASSLOADER_PERMISSION);
 420                 }
 421             }


 439      * method returns {@code null}. </p>
 440      *
 441      * <p> If the class loader of the given module defines other modules and
 442      * the given name is a class defined in a different module, this method
 443      * returns {@code null} after the class is loaded. </p>
 444      *
 445      * <p> This method does not check whether the requested class is
 446      * accessible to its caller. </p>
 447      *
 448      * @apiNote
 449      * This method returns {@code null} on failure rather than
 450      * throwing a {@link ClassNotFoundException}, as is done by
 451      * the {@link #forName(String, boolean, ClassLoader)} method.
 452      * The security check is a stack-based permission check if the caller
 453      * loads a class in another module.
 454      *
 455      * @param  module   A module
 456      * @param  name     The <a href="ClassLoader.html#binary-name">binary name</a>
 457      *                  of the class
 458      * @return {@code Class} object of the given name defined in the given module;
 459      *         {@code null} if not found or the class is defined in
 460      *         the given module but {@linkplain #isHidden() hidden}
 461      *
 462      * @throws NullPointerException if the given module or name is {@code null}
 463      *
 464      * @throws LinkageError if the linkage fails
 465      *
 466      * @throws SecurityException
 467      *         <ul>
 468      *         <li> if the caller is not the specified module and
 469      *         {@code RuntimePermission("getClassLoader")} permission is denied; or</li>
 470      *         <li> access to the module content is denied. For example,
 471      *         permission check will be performed when a class loader calls
 472      *         {@link ModuleReader#open(String)} to read the bytes of a class file
 473      *         in a module.</li>
 474      *         </ul>
 475      *
 476      * @see       java.lang.Class#isHidden
 477      * @since 9
 478      * @spec JPMS
 479      */
 480     @CallerSensitive
 481     public static Class<?> forName(Module module, String name) {
 482         Objects.requireNonNull(module);
 483         Objects.requireNonNull(name);
 484 
 485         ClassLoader cl;
 486         SecurityManager sm = System.getSecurityManager();
 487         if (sm != null) {
 488             Class<?> caller = Reflection.getCallerClass();
 489             if (caller != null && caller.getModule() != module) {
 490                 // if caller is null, Class.forName is the last java frame on the stack.
 491                 // java.base has all permissions
 492                 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
 493             }
 494             PrivilegedAction<ClassLoader> pa = module::getClassLoader;
 495             cl = AccessController.doPrivileged(pa);
 496         } else {


 857      * {@code Module} for the element type. If this class represents a
 858      * primitive type or void, then the {@code Module} object for the
 859      * {@code java.base} module is returned.
 860      *
 861      * If this class is in an unnamed module then the {@linkplain
 862      * ClassLoader#getUnnamedModule() unnamed} {@code Module} of the class
 863      * loader for this class is returned.
 864      *
 865      * @return the module that this class or interface is a member of
 866      *
 867      * @since 9
 868      * @spec JPMS
 869      */
 870     public Module getModule() {
 871         return module;
 872     }
 873 
 874     // set by VM
 875     private transient Module module;
 876 
 877     // set by VM (to be revisited if needed)
 878     // for static nestmate, set to non-null when the first time Class::getNestHost is called
 879     // for dynamic nestmate, set to non-null when it's defined and this keeps the host alive
 880     // (the host may be temporary)
 881     private transient Class<?> nestHost;
 882 
 883     // Initialized in JVM not by private constructor
 884     // This field is filtered from reflection access, i.e. getDeclaredField
 885     // will throw NoSuchFieldException
 886     private final ClassLoader classLoader;
 887 
 888     /**
 889      * Returns an array of {@code TypeVariable} objects that represent the
 890      * type variables declared by the generic declaration represented by this
 891      * {@code GenericDeclaration} object, in declaration order.  Returns an
 892      * array of length 0 if the underlying generic declaration declares no type
 893      * variables.
 894      *
 895      * @return an array of {@code TypeVariable} objects that represent
 896      *     the type variables declared by this generic declaration
 897      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
 898      *     signature of this generic declaration does not conform to
 899      *     the format specified in
 900      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 901      * @since 1.5
 902      */


1586             simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1587         }
1588         return simpleName;
1589     }
1590 
1591     /**
1592      * Return an informative string for the name of this type.
1593      *
1594      * @return an informative string for the name of this type
1595      * @since 1.8
1596      */
1597     public String getTypeName() {
1598         if (isArray()) {
1599             try {
1600                 Class<?> cl = this;
1601                 int dimensions = 0;
1602                 do {
1603                     dimensions++;
1604                     cl = cl.getComponentType();
1605                 } while (cl.isArray());
1606                 StringBuilder sb = new StringBuilder();
1607                 sb.append(cl.getName());
1608                 for (int i = 0; i < dimensions; i++) {
1609                     sb.append("[]");
1610                 }
1611                 return sb.toString();
1612             } catch (Throwable e) { /*FALLTHRU*/ }
1613         }
1614         return getName();
1615     }
1616 
1617     /**
1618      * Returns the canonical name of the underlying class as
1619      * defined by the Java Language Specification.  Returns null if
1620      * the underlying class does not have a canonical name (i.e., if
1621      * it is a local or anonymous class or an array whose component
1622      * type does not have a canonical name).
1623      * @return the canonical name of the underlying class if it exists, and
1624      * {@code null} otherwise.
1625      * @since 1.5
1626      */
1627     public String getCanonicalName() {
1628         ReflectionData<T> rd = reflectionData();
1629         String canonicalName = rd.canonicalName;
1630         if (canonicalName == null) {
1631             rd.canonicalName = canonicalName = getCanonicalName0();


2800      * ensure it's ok to get the
2801      * {@code ProtectionDomain}.
2802      *
2803      * @return the ProtectionDomain of this class
2804      *
2805      * @throws SecurityException
2806      *        if a security manager exists and its
2807      *        {@code checkPermission} method doesn't allow
2808      *        getting the ProtectionDomain.
2809      *
2810      * @see java.security.ProtectionDomain
2811      * @see SecurityManager#checkPermission
2812      * @see java.lang.RuntimePermission
2813      * @since 1.2
2814      */
2815     public java.security.ProtectionDomain getProtectionDomain() {
2816         SecurityManager sm = System.getSecurityManager();
2817         if (sm != null) {
2818             sm.checkPermission(SecurityConstants.GET_PD_PERMISSION);
2819         }
2820         return protectionDomain();
2821     }
2822 
2823     // package-private
2824     java.security.ProtectionDomain protectionDomain() {
2825         java.security.ProtectionDomain pd = getProtectionDomain0();
2826         if (pd == null) {
2827             if (allPermDomain == null) {
2828                 java.security.Permissions perms =
2829                     new java.security.Permissions();
2830                 perms.add(SecurityConstants.ALL_PERMISSION);
2831                 allPermDomain =
2832                     new java.security.ProtectionDomain(null, perms);
2833             }
2834             pd = allPermDomain;
2835         }
2836         return pd;
2837     }
2838 

2839     /**
2840      * Returns the ProtectionDomain of this class.
2841      */
2842     private native java.security.ProtectionDomain getProtectionDomain0();
2843 
2844     /*
2845      * Return the Virtual Machine's Class object for the named
2846      * primitive type.
2847      */
2848     static native Class<?> getPrimitiveClass(String name);
2849 
2850     /*
2851      * Check if client is allowed to access members.  If access is denied,
2852      * throw a SecurityException.
2853      *
2854      * This method also enforces package access.
2855      *
2856      * <p> Default policy: allow all clients access with normal Java access
2857      * control.
2858      *


3419     }
3420 
3421     private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
3422         Constructor<U>[] out = arg.clone();
3423         ReflectionFactory fact = getReflectionFactory();
3424         for (int i = 0; i < out.length; i++) {
3425             out[i] = fact.copyConstructor(out[i]);
3426         }
3427         return out;
3428     }
3429 
3430     private native Field[]       getDeclaredFields0(boolean publicOnly);
3431     private native Method[]      getDeclaredMethods0(boolean publicOnly);
3432     private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3433     private native Class<?>[]   getDeclaredClasses0();
3434 
3435     /**
3436      * Helper method to get the method name from arguments.
3437      */
3438     private String methodToString(String name, Class<?>[] argTypes) {
3439         StringBuilder sb = new StringBuilder();
3440         sb.append(getName() + "." + name + "(");
3441         if (argTypes != null) {
3442             sb.append(Arrays.stream(argTypes)
3443                       .map(c -> (c == null) ? "null" : c.getName())
3444                       .collect(Collectors.joining(",")));
3445         }
3446         sb.append(")");
3447         return sb.toString();
3448     }
3449 
3450     /** use serialVersionUID from JDK 1.1 for interoperability */
3451     private static final long serialVersionUID = 3206093459760846163L;
3452 
3453 
3454     /**
3455      * Class Class is special cased within the Serialization Stream Protocol.
3456      *
3457      * A Class instance is written initially into an ObjectOutputStream in the
3458      * following format:
3459      * <pre>
3460      *      {@code TC_CLASS} ClassDescriptor
3461      *      A ClassDescriptor is a special cased serialization of
3462      *      a {@code java.io.ObjectStreamClass} instance.
3463      * </pre>
3464      * A new handle is generated for the initial time the class descriptor
3465      * is written into the stream. Future references to the class descriptor
3466      * are written as references to the initial class descriptor instance.
3467      *


3909      * host.
3910      *
3911      * <p>Each of the {@code Class} objects representing array types,
3912      * primitive types, and {@code void} returns {@code this} to indicate
3913      * that the represented entity belongs to the nest consisting only of
3914      * itself, and is the nest host.
3915      *
3916      * <p>If there is a {@linkplain LinkageError linkage error} accessing
3917      * the nest host, or if this class or interface is not enumerated as
3918      * a member of the nest by the nest host, then it is considered to belong
3919      * to its own nest and {@code this} is returned as the host.
3920      *
3921      * @apiNote A {@code class} file of version 55.0 or greater may record the
3922      * host of the nest to which it belongs by using the {@code NestHost}
3923      * attribute (JVMS 4.7.28). Alternatively, a {@code class} file of
3924      * version 55.0 or greater may act as a nest host by enumerating the nest's
3925      * other members with the
3926      * {@code NestMembers} attribute (JVMS 4.7.29).
3927      * A {@code class} file of version 54.0 or lower does not use these
3928      * attributes.
3929      * A class defined at runtime in a nest via
3930      * {@link MethodHandles.Lookup#defineClass(byte[], MethodHandles.Lookup.ClassProperty[])}
3931      * must not have the {@code NestHost} attribute and is not enumerated
3932      * in the {@code NestMembers} attribute of the class file of the nest host.
3933      *
3934      * @return the nest host of this class or interface
3935      *
3936      * @throws SecurityException
3937      *         If the returned class is not the current class, and
3938      *         if a security manager, <i>s</i>, is present and the caller's
3939      *         class loader is not the same as or an ancestor of the class
3940      *         loader for the returned class and invocation of {@link
3941      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
3942      *         denies access to the package of the returned class
3943      * @since 11
3944      * @jvms 4.7.28 and 4.7.29 NestHost and NestMembers attributes
3945      * @jvms 5.4.4 Access Control
3946      */
3947     @CallerSensitive
3948     public Class<?> getNestHost() {
3949         if (isPrimitive() || isArray()) {
3950             return this;
3951         }
3952         Class<?> host;


4004      * Returns an array containing {@code Class} objects representing all the
4005      * classes and interfaces that are members of the nest to which the class
4006      * or interface represented by this {@code Class} object belongs.
4007      * The {@linkplain #getNestHost() nest host} of that nest is the zeroth
4008      * element of the array. Subsequent elements represent any classes or
4009      * interfaces that are recorded by the nest host as being members of
4010      * the nest; the order of such elements is unspecified. Duplicates are
4011      * permitted.
4012      * If the nest host of that nest does not enumerate any members, then the
4013      * array has a single element containing {@code this}.
4014      *
4015      * <p>Each of the {@code Class} objects representing array types,
4016      * primitive types, and {@code void} returns an array containing only
4017      * {@code this}.
4018      *
4019      * <p>This method validates that, for each class or interface which is
4020      * recorded as a member of the nest by the nest host, that class or
4021      * interface records itself as a member of that same nest. Any exceptions
4022      * that occur during this validation are rethrown by this method.
4023      *
4024      * <p>This method does not return the
4025      * {@linkplain MethodHandles.Lookup.ClassProperty#NESTMATE nest members}
4026      * defined dynamically via
4027      * {@link MethodHandles.Lookup#defineClass(byte[], MethodHandles.Lookup.ClassProperty...)}.
4028      *
4029      * @apiNote
4030      * Reflection API presents the static view of this class. The dynamic
4031      * nestmates are not listed in the {@code NestMembers} attribute.
4032      * We can revisit this in the future if there is a need to find
4033      * all dynamically defined nest members.
4034      *
4035      * @return an array of all classes and interfaces in the same nest as
4036      * this class
4037      *
4038      * @throws LinkageError
4039      *         If there is any problem loading or validating a nest member or
4040      *         its nest host
4041      * @throws SecurityException
4042      *         If any returned class is not the current class, and
4043      *         if a security manager, <i>s</i>, is present and the caller's
4044      *         class loader is not the same as or an ancestor of the class
4045      *         loader for that returned class and invocation of {@link
4046      *         SecurityManager#checkPackageAccess s.checkPackageAccess()}
4047      *         denies access to the package of that returned class
4048      *
4049      * @since 11
4050      * @see #getNestHost()
4051      * @see MethodHandles.Lookup#defineClass(byte[], MethodHandles.Lookup.ClassProperty...)
4052      */
4053     @CallerSensitive
4054     public Class<?>[] getNestMembers() {
4055         if (isPrimitive() || isArray()) {
4056             return new Class<?>[] { this };
4057         }
4058         Class<?>[] members = getNestMembers0();
4059         // Can't actually enable this due to bootstrapping issues
4060         // assert(members.length != 1 || members[0] == this); // expected invariant from VM
4061 
4062         if (members.length > 1) {
4063             // If we return anything other than the current class we need
4064             // a security check
4065             SecurityManager sm = System.getSecurityManager();
4066             if (sm != null) {
4067                 checkPackageAccess(sm,
4068                                    ClassLoader.getClassLoader(Reflection.getCallerClass()), true);
4069             }
4070         }
4071         return members;


4116      *
4117      * @return a {@code Class} describing the array type
4118      * @since 12
4119      */
4120     @Override
4121     public Class<?> arrayType() {
4122         return Array.newInstance(this, 0).getClass();
4123     }
4124 
4125     /**
4126      * Returns a nominal descriptor for this instance, if one can be
4127      * constructed, or an empty {@link Optional} if one cannot be.
4128      *
4129      * @return An {@link Optional} containing the resulting nominal descriptor,
4130      * or an empty {@link Optional} if one cannot be constructed.
4131      * @since 12
4132      */
4133     @Override
4134     public Optional<ClassDesc> describeConstable() {
4135         return Optional.of(ClassDesc.ofDescriptor(descriptorString()));
4136    }
4137 
4138     /**
4139      * Returns {@code true} if this class is hidden from being referenced
4140      * by other classes; otherwise, {@code false}.
4141      *
4142      * <p> A <em>hidden class</em> is a class that cannot be referenced
4143      * by other classes and cannot be loaded by its name.
4144      * <p> A hidden class can be defined via
4145      * {@link MethodHandles.Lookup#defineClass(byte[], MethodHandles.Lookup.ClassProperty[])
4146      * Lookup.defineClass} with
4147      * {@link MethodHandles.Lookup.ClassProperty#HIDDEN HIDDEN} property.
4148      *
4149      * <p> If this class is hidden then it cannot be found via its name.
4150      * For example, {@code Class.forName(this.getName())} cannot find this class
4151      * and {@code ClassNotFoundException} will be thrown.
4152      *
4153      * <p> If this class is an array class and its component class is hidden,
4154      * then this array class is also hidden.
4155      *
4156      * @return {@code true} if this class is hidden;
4157      * otherwise {@code false}.
4158      *
4159      * @since 12
4160      * @see MethodHandles.Lookup#defineClass(byte[], MethodHandles.Lookup.ClassProperty[])
4161      */
4162     public boolean isHidden() {
4163         return getName().indexOf('\\') > -1 || isVMAnonymousClass();
4164     }
4165 
4166     /**
4167      * Checks if this {@code Class} is a VM-anonymous class
4168      * as defined by {@link jdk.internal.misc.Unsafe#defineAnonymousClass}
4169      * (not to be confused with a Java Language anonymous inner class).
4170      */
4171     private boolean isVMAnonymousClass() {
4172         return getName().indexOf('/') > -1;
4173     }
4174 }
< prev index next >