< prev index next >

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

Print this page

  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.constant.ConstantDescs;
  31 import java.lang.invoke.TypeDescriptor;
  32 import java.lang.invoke.MethodHandles;
  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.AccessFlag;
  40 import java.lang.reflect.Array;

  41 import java.lang.reflect.Constructor;
  42 import java.lang.reflect.Executable;
  43 import java.lang.reflect.Field;
  44 import java.lang.reflect.GenericArrayType;
  45 import java.lang.reflect.GenericDeclaration;
  46 import java.lang.reflect.InvocationTargetException;
  47 import java.lang.reflect.Member;
  48 import java.lang.reflect.Method;
  49 import java.lang.reflect.Modifier;
  50 import java.lang.reflect.RecordComponent;
  51 import java.lang.reflect.Type;
  52 import java.lang.reflect.TypeVariable;
  53 import java.lang.constant.Constable;
  54 import java.net.URL;
  55 import java.security.AllPermission;
  56 import java.security.Permissions;
  57 import java.security.ProtectionDomain;
  58 import java.util.ArrayList;
  59 import java.util.Arrays;
  60 import java.util.Collection;
  61 import java.util.HashMap;

  62 import java.util.LinkedHashMap;
  63 import java.util.LinkedHashSet;
  64 import java.util.List;
  65 import java.util.Map;
  66 import java.util.Objects;
  67 import java.util.Optional;
  68 import java.util.Set;
  69 import java.util.stream.Collectors;
  70 
  71 import jdk.internal.constant.ConstantUtils;

  72 import jdk.internal.loader.BootLoader;
  73 import jdk.internal.loader.BuiltinClassLoader;

  74 import jdk.internal.misc.Unsafe;
  75 import jdk.internal.module.Resources;
  76 import jdk.internal.reflect.CallerSensitive;
  77 import jdk.internal.reflect.CallerSensitiveAdapter;
  78 import jdk.internal.reflect.ConstantPool;
  79 import jdk.internal.reflect.Reflection;
  80 import jdk.internal.reflect.ReflectionFactory;
  81 import jdk.internal.vm.annotation.AOTRuntimeSetup;
  82 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
  83 import jdk.internal.vm.annotation.IntrinsicCandidate;
  84 import jdk.internal.vm.annotation.Stable;
  85 
  86 import sun.invoke.util.Wrapper;
  87 import sun.reflect.generics.factory.CoreReflectionFactory;
  88 import sun.reflect.generics.factory.GenericsFactory;
  89 import sun.reflect.generics.repository.ClassRepository;
  90 import sun.reflect.generics.repository.MethodRepository;
  91 import sun.reflect.generics.repository.ConstructorRepository;
  92 import sun.reflect.generics.scope.ClassScope;
  93 import sun.reflect.annotation.*;

 202  * {@linkplain #getTypeName type name} return results
 203  * equal to {@code "HelloWorld"}. The {@linkplain #getSimpleName
 204  * simple name} of such an implicitly declared class is {@code "HelloWorld"} and
 205  * the {@linkplain #getCanonicalName canonical name} is {@code "HelloWorld"}.
 206  *
 207  * @param <T> the type of the class modeled by this {@code Class}
 208  * object.  For example, the type of {@code String.class} is {@code
 209  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
 210  * unknown.
 211  *
 212  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
 213  * @since   1.0
 214  */
 215 @AOTSafeClassInitializer
 216 public final class Class<T> implements java.io.Serializable,
 217                               GenericDeclaration,
 218                               Type,
 219                               AnnotatedElement,
 220                               TypeDescriptor.OfField<Class<?>>,
 221                               Constable {
 222     private static final int ANNOTATION= 0x00002000;
 223     private static final int ENUM      = 0x00004000;
 224     private static final int SYNTHETIC = 0x00001000;
 225 
 226     private static native void registerNatives();
 227     static {
 228         runtimeSetup();
 229     }
 230 
 231     /// No significant static final fields; [#resetArchivedStates()] handles
 232     /// prevents storing [#reflectionFactory] into AOT image.
 233     @AOTRuntimeSetup
 234     private static void runtimeSetup() {
 235         registerNatives();
 236     }
 237 
 238     /*
 239      * Private constructor. Only the Java Virtual Machine creates Class objects.
 240      * This constructor is not used and prevents the default constructor being
 241      * generated.
 242      */
 243     private Class(ClassLoader loader, Class<?> arrayComponentType, char mods, ProtectionDomain pd, boolean isPrim, char flags) {
 244         // Initialize final field for classLoader.  The initialization value of non-null

 303      *
 304      * @since 1.8
 305      */
 306     public String toGenericString() {
 307         if (isPrimitive()) {
 308             return toString();
 309         } else {
 310             StringBuilder sb = new StringBuilder();
 311             Class<?> component = this;
 312             int arrayDepth = 0;
 313 
 314             if (isArray()) {
 315                 do {
 316                     arrayDepth++;
 317                     component = component.getComponentType();
 318                 } while (component.isArray());
 319                 sb.append(component.getName());
 320             } else {
 321                 // Class modifiers are a superset of interface modifiers
 322                 int modifiers = getModifiers() & Modifier.classModifiers();


 323                 if (modifiers != 0) {
 324                     sb.append(Modifier.toString(modifiers));
 325                     sb.append(' ');
 326                 }
 327 
 328                 // A class cannot be strictfp and sealed/non-sealed so
 329                 // it is sufficient to check for sealed-ness after all
 330                 // modifiers are printed.
 331                 addSealingInfo(modifiers, sb);
 332 
 333                 if (isAnnotation()) {
 334                     sb.append('@');
 335                 }
 336                 if (isInterface()) { // Note: all annotation interfaces are interfaces
 337                     sb.append("interface");
 338                 } else {
 339                     if (isEnum())
 340                         sb.append("enum");
 341                     else if (isRecord())
 342                         sb.append("record");
 343                     else
 344                         sb.append("class");





 345                 }
 346                 sb.append(' ');
 347                 sb.append(getName());
 348             }
 349 
 350             TypeVariable<?>[] typeparms = component.getTypeParameters();
 351             if (typeparms.length > 0) {
 352                 sb.append(Arrays.stream(typeparms)
 353                           .map(Class::typeVarBounds)
 354                           .collect(Collectors.joining(",", "<", ">")));
 355             }
 356 
 357             if (arrayDepth > 0) sb.append("[]".repeat(arrayDepth));
 358 
 359             return sb.toString();
 360         }
 361     }
 362 
 363     private void addSealingInfo(int modifiers, StringBuilder sb) {
 364         // A class can be final XOR sealed XOR non-sealed.

 590      * @throws NullPointerException if the given module or name is {@code null}
 591      *
 592      * @throws LinkageError if the linkage fails
 593      *
 594      * @jls 12.2 Loading of Classes and Interfaces
 595      * @jls 12.3 Linking of Classes and Interfaces
 596      * @since 9
 597      */
 598     public static Class<?> forName(Module module, String name) {
 599         Objects.requireNonNull(module);
 600         Objects.requireNonNull(name);
 601 
 602         ClassLoader cl = module.getClassLoader();
 603         if (cl != null) {
 604             return cl.loadClass(module, name);
 605         } else {
 606             return BootLoader.loadClass(module, name);
 607         }
 608     }
 609 






















































 610     /**
 611      * {@return the {@code Class} object associated with the
 612      * {@linkplain #isPrimitive() primitive type} of the given name}
 613      * If the argument is not the name of a primitive type, {@code
 614      * null} is returned.
 615      *
 616      * @param primitiveName the name of the primitive type to find
 617      *
 618      * @throws NullPointerException if the argument is {@code null}
 619      *
 620      * @jls 4.2 Primitive Types and Values
 621      * @jls 15.8.2 Class Literals
 622      * @since 22
 623      */
 624     public static Class<?> forPrimitiveName(String primitiveName) {
 625         return switch(primitiveName) {
 626         // Integral types
 627         case "int"     -> int.class;
 628         case "long"    -> long.class;
 629         case "short"   -> short.class;

1317         }
1318         return c;
1319     }
1320 
1321     /**
1322      * Returns the Java language modifiers for this class or interface, encoded
1323      * in an integer. The modifiers consist of the Java Virtual Machine's
1324      * constants for {@code public}, {@code protected},
1325      * {@code private}, {@code final}, {@code static},
1326      * {@code abstract} and {@code interface}; they should be decoded
1327      * using the methods of class {@code Modifier}.
1328      *
1329      * <p> If the underlying class is an array class:
1330      * <ul>
1331      * <li> its {@code public}, {@code private} and {@code protected}
1332      *      modifiers are the same as those of its component type
1333      * <li> its {@code abstract} and {@code final} modifiers are always
1334      *      {@code true}
1335      * <li> its interface modifier is always {@code false}, even when
1336      *      the component type is an interface

1337      * </ul>
1338      * If this {@code Class} object represents a primitive type or
1339      * void, its {@code public}, {@code abstract}, and {@code final}
1340      * modifiers are always {@code true}.
1341      * For {@code Class} objects representing void, primitive types, and
1342      * arrays, the values of other modifiers are {@code false} other
1343      * than as specified above.
1344      *
1345      * <p> The modifier encodings are defined in section {@jvms 4.1}
1346      * of <cite>The Java Virtual Machine Specification</cite>.
1347      *
1348      * @return the {@code int} representing the modifiers for this class
1349      * @see     java.lang.reflect.Modifier
1350      * @see #accessFlags()
1351      * @see <a
1352      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1353      * programming language and JVM modeling in core reflection</a>
1354      * @since 1.1
1355      * @jls 8.1.1 Class Modifiers
1356      * @jls 9.1.1 Interface Modifiers
1357      * @jvms 4.1 The {@code ClassFile} Structure
1358      */
1359     public int getModifiers() { return modifiers; }
1360 
1361     /**
1362      * {@return an unmodifiable set of the {@linkplain AccessFlag access
1363      * flags} for this class, possibly empty}

1364      *
1365      * <p> If the underlying class is an array class:
1366      * <ul>
1367      * <li> its {@code PUBLIC}, {@code PRIVATE} and {@code PROTECTED}
1368      *      access flags are the same as those of its component type
1369      * <li> its {@code ABSTRACT} and {@code FINAL} flags are present
1370      * <li> its {@code INTERFACE} flag is absent, even when the
1371      *      component type is an interface

1372      * </ul>
1373      * If this {@code Class} object represents a primitive type or
1374      * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
1375      * {@code FINAL}.
1376      * For {@code Class} objects representing void, primitive types, and
1377      * arrays, access flags are absent other than as specified above.
1378      *
1379      * @see #getModifiers()
1380      * @jvms 4.1 The ClassFile Structure
1381      * @jvms 4.7.6 The InnerClasses Attribute
1382      * @since 20
1383      */
1384     public Set<AccessFlag> accessFlags() {
1385         // Location.CLASS allows SUPER and AccessFlag.MODULE which
1386         // INNER_CLASS forbids. INNER_CLASS allows PRIVATE, PROTECTED,
1387         // and STATIC, which are not allowed on Location.CLASS.
1388         // Use getClassFileAccessFlags to expose SUPER status.

1389         var location = (isMemberClass() || isLocalClass() ||
1390                         isAnonymousClass() || isArray()) ?
1391             AccessFlag.Location.INNER_CLASS :
1392             AccessFlag.Location.CLASS;
1393         return getReflectionFactory().parseAccessFlags((location == AccessFlag.Location.CLASS) ?
1394                         getClassFileAccessFlags() : getModifiers(), location, this);








1395     }
1396 
1397     /**
1398      * Gets the signers of this class.
1399      *
1400      * @return  the signers of this class, or null if there are no signers.  In
1401      *          particular, this method returns null if this {@code Class} object represents
1402      *          a primitive type or void.
1403      * @since   1.1
1404      */

1405     public Object[] getSigners() {
1406         var signers = this.signers;
1407         return signers == null ? null : signers.clone();
1408     }
1409 
1410     /**
1411      * Set the signers of this class.
1412      */
1413     void setSigners(Object[] signers) {
1414         if (!isPrimitive() && !isArray()) {
1415             this.signers = signers;
1416         }
1417     }
1418 
1419     /**
1420      * If this {@code Class} object represents a local or anonymous
1421      * class within a method, returns a {@link
1422      * java.lang.reflect.Method Method} object representing the
1423      * immediately enclosing method of the underlying class. Returns
1424      * {@code null} otherwise.

3772      *
3773      * <p> If this {@code Class} object represents an interface, the return
3774      * value is an array containing objects representing the uses of interface
3775      * types to specify interfaces directly extended by the interface. The
3776      * order of the objects in the array corresponds to the order of the
3777      * interface types used in the 'extends' clause of the declaration of this
3778      * {@code Class} object.
3779      *
3780      * <p> If this {@code Class} object represents a class or interface whose
3781      * declaration does not explicitly indicate any annotated superinterfaces,
3782      * the return value is an array of length 0.
3783      *
3784      * <p> If this {@code Class} object represents either the {@code Object}
3785      * class, an array type, a primitive type, or void, the return value is an
3786      * array of length 0.
3787      *
3788      * @return an array representing the superinterfaces
3789      * @since 1.8
3790      */
3791     public AnnotatedType[] getAnnotatedInterfaces() {
3792          return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3793     }
3794 
3795     private native Class<?> getNestHost0();
3796 
3797     /**
3798      * Returns the nest host of the <a href=#nest>nest</a> to which the class
3799      * or interface represented by this {@code Class} object belongs.
3800      * Every class and interface belongs to exactly one nest.
3801      *
3802      * If the nest host of this class or interface has previously
3803      * been determined, then this method returns the nest host.
3804      * If the nest host of this class or interface has
3805      * not previously been determined, then this method determines the nest
3806      * host using the algorithm of JVMS 5.4.4, and returns it.
3807      *
3808      * Often, a class or interface belongs to a nest consisting only of itself,
3809      * in which case this method returns {@code this} to indicate that the class
3810      * or interface is the nest host.
3811      *
3812      * <p>If this {@code Class} object represents a primitive type, an array type,

4112      * @since 17
4113      */
4114     public boolean isSealed() {
4115         if (isArray() || isPrimitive()) {
4116             return false;
4117         }
4118         return getPermittedSubclasses() != null;
4119     }
4120 
4121     private native Class<?>[] getPermittedSubclasses0();
4122 
4123     /*
4124      * Return the class's major and minor class file version packed into an int.
4125      * The high order 16 bits contain the class's minor version.  The low order
4126      * 16 bits contain the class's major version.
4127      *
4128      * If the class is an array type then the class file version of its element
4129      * type is returned.  If the class is a primitive type then the latest class
4130      * file major version is returned and zero is returned for the minor version.
4131      */

4132     int getClassFileVersion() {
4133         Class<?> c = isArray() ? elementType() : this;
4134         return c.getClassFileVersion0();
4135     }
4136 
4137     private native int getClassFileVersion0();
4138 
4139      /**
4140       * Return the access flags as they were in the class's bytecode, including
4141       * the original setting of ACC_SUPER.
4142       *
4143       * If this {@code Class} object represents a primitive type or
4144       * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
4145       * {@code FINAL}.
4146       * If this {@code Class} object represents an array type, return 0.
4147       */
4148      int getClassFileAccessFlags() {
4149          return classFileAccessFlags;
4150      }
4151 }

  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.constant.ConstantDescs;
  31 import java.lang.invoke.TypeDescriptor;
  32 import java.lang.invoke.MethodHandles;
  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.AccessFlag;
  40 import java.lang.reflect.Array;
  41 import java.lang.reflect.ClassFileFormatVersion;
  42 import java.lang.reflect.Constructor;
  43 import java.lang.reflect.Executable;
  44 import java.lang.reflect.Field;
  45 import java.lang.reflect.GenericArrayType;
  46 import java.lang.reflect.GenericDeclaration;
  47 import java.lang.reflect.InvocationTargetException;
  48 import java.lang.reflect.Member;
  49 import java.lang.reflect.Method;
  50 import java.lang.reflect.Modifier;
  51 import java.lang.reflect.RecordComponent;
  52 import java.lang.reflect.Type;
  53 import java.lang.reflect.TypeVariable;
  54 import java.lang.constant.Constable;
  55 import java.net.URL;
  56 import java.security.AllPermission;
  57 import java.security.Permissions;
  58 import java.security.ProtectionDomain;
  59 import java.util.ArrayList;
  60 import java.util.Arrays;
  61 import java.util.Collection;
  62 import java.util.HashMap;
  63 import java.util.HashSet;
  64 import java.util.LinkedHashMap;
  65 import java.util.LinkedHashSet;
  66 import java.util.List;
  67 import java.util.Map;
  68 import java.util.Objects;
  69 import java.util.Optional;
  70 import java.util.Set;
  71 import java.util.stream.Collectors;
  72 
  73 import jdk.internal.constant.ConstantUtils;
  74 import jdk.internal.javac.PreviewFeature;
  75 import jdk.internal.loader.BootLoader;
  76 import jdk.internal.loader.BuiltinClassLoader;
  77 import jdk.internal.misc.PreviewFeatures;
  78 import jdk.internal.misc.Unsafe;
  79 import jdk.internal.module.Resources;
  80 import jdk.internal.reflect.CallerSensitive;
  81 import jdk.internal.reflect.CallerSensitiveAdapter;
  82 import jdk.internal.reflect.ConstantPool;
  83 import jdk.internal.reflect.Reflection;
  84 import jdk.internal.reflect.ReflectionFactory;
  85 import jdk.internal.vm.annotation.AOTRuntimeSetup;
  86 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
  87 import jdk.internal.vm.annotation.IntrinsicCandidate;
  88 import jdk.internal.vm.annotation.Stable;
  89 
  90 import sun.invoke.util.Wrapper;
  91 import sun.reflect.generics.factory.CoreReflectionFactory;
  92 import sun.reflect.generics.factory.GenericsFactory;
  93 import sun.reflect.generics.repository.ClassRepository;
  94 import sun.reflect.generics.repository.MethodRepository;
  95 import sun.reflect.generics.repository.ConstructorRepository;
  96 import sun.reflect.generics.scope.ClassScope;
  97 import sun.reflect.annotation.*;

 206  * {@linkplain #getTypeName type name} return results
 207  * equal to {@code "HelloWorld"}. The {@linkplain #getSimpleName
 208  * simple name} of such an implicitly declared class is {@code "HelloWorld"} and
 209  * the {@linkplain #getCanonicalName canonical name} is {@code "HelloWorld"}.
 210  *
 211  * @param <T> the type of the class modeled by this {@code Class}
 212  * object.  For example, the type of {@code String.class} is {@code
 213  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
 214  * unknown.
 215  *
 216  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
 217  * @since   1.0
 218  */
 219 @AOTSafeClassInitializer
 220 public final class Class<T> implements java.io.Serializable,
 221                               GenericDeclaration,
 222                               Type,
 223                               AnnotatedElement,
 224                               TypeDescriptor.OfField<Class<?>>,
 225                               Constable {
 226     private static final int ANNOTATION = 0x00002000;
 227     private static final int ENUM       = 0x00004000;
 228     private static final int SYNTHETIC  = 0x00001000;
 229 
 230     private static native void registerNatives();
 231     static {
 232         runtimeSetup();
 233     }
 234 
 235     /// No significant static final fields; [#resetArchivedStates()] handles
 236     /// prevents storing [#reflectionFactory] into AOT image.
 237     @AOTRuntimeSetup
 238     private static void runtimeSetup() {
 239         registerNatives();
 240     }
 241 
 242     /*
 243      * Private constructor. Only the Java Virtual Machine creates Class objects.
 244      * This constructor is not used and prevents the default constructor being
 245      * generated.
 246      */
 247     private Class(ClassLoader loader, Class<?> arrayComponentType, char mods, ProtectionDomain pd, boolean isPrim, char flags) {
 248         // Initialize final field for classLoader.  The initialization value of non-null

 307      *
 308      * @since 1.8
 309      */
 310     public String toGenericString() {
 311         if (isPrimitive()) {
 312             return toString();
 313         } else {
 314             StringBuilder sb = new StringBuilder();
 315             Class<?> component = this;
 316             int arrayDepth = 0;
 317 
 318             if (isArray()) {
 319                 do {
 320                     arrayDepth++;
 321                     component = component.getComponentType();
 322                 } while (component.isArray());
 323                 sb.append(component.getName());
 324             } else {
 325                 // Class modifiers are a superset of interface modifiers
 326                 int modifiers = getModifiers() & Modifier.classModifiers();
 327                 // Modifier.toString() below mis-interprets SYNCHRONIZED, STRICT, and VOLATILE bits
 328                 modifiers &= ~(Modifier.SYNCHRONIZED | Modifier.STRICT | Modifier.VOLATILE);
 329                 if (modifiers != 0) {
 330                     sb.append(Modifier.toString(modifiers));
 331                     sb.append(' ');
 332                 }
 333 
 334                 // A class cannot be strictfp and sealed/non-sealed so
 335                 // it is sufficient to check for sealed-ness after all
 336                 // modifiers are printed.
 337                 addSealingInfo(modifiers, sb);
 338 
 339                 if (isAnnotation()) {
 340                     sb.append('@');
 341                 }
 342                 if (isInterface()) { // Note: all annotation interfaces are interfaces
 343                     sb.append("interface");
 344                 } else {
 345                     if (isEnum())
 346                         sb.append("enum");
 347                     else {
 348                         if (isValue()) {
 349                             sb.append("value ");
 350                         }
 351                         if (isRecord())
 352                             sb.append("record");
 353                         else
 354                             sb.append("class");
 355                     }
 356                 }
 357                 sb.append(' ');
 358                 sb.append(getName());
 359             }
 360 
 361             TypeVariable<?>[] typeparms = component.getTypeParameters();
 362             if (typeparms.length > 0) {
 363                 sb.append(Arrays.stream(typeparms)
 364                           .map(Class::typeVarBounds)
 365                           .collect(Collectors.joining(",", "<", ">")));
 366             }
 367 
 368             if (arrayDepth > 0) sb.append("[]".repeat(arrayDepth));
 369 
 370             return sb.toString();
 371         }
 372     }
 373 
 374     private void addSealingInfo(int modifiers, StringBuilder sb) {
 375         // A class can be final XOR sealed XOR non-sealed.

 601      * @throws NullPointerException if the given module or name is {@code null}
 602      *
 603      * @throws LinkageError if the linkage fails
 604      *
 605      * @jls 12.2 Loading of Classes and Interfaces
 606      * @jls 12.3 Linking of Classes and Interfaces
 607      * @since 9
 608      */
 609     public static Class<?> forName(Module module, String name) {
 610         Objects.requireNonNull(module);
 611         Objects.requireNonNull(name);
 612 
 613         ClassLoader cl = module.getClassLoader();
 614         if (cl != null) {
 615             return cl.loadClass(module, name);
 616         } else {
 617             return BootLoader.loadClass(module, name);
 618         }
 619     }
 620 
 621     /**
 622      * {@return {@code true} if this {@code Class} object represents an identity class,
 623      * otherwise {@code false}}
 624      *
 625      * <ul>
 626      *      <li>
 627      *          If this {@code Class} object represents an array type this method returns {@code true}.
 628      *      <li>
 629      *          If this {@code Class} object represents an interface, a primitive type,
 630      *          or {@code void} this method returns {@code false}.
 631      *      <li>
 632      *          For all other {@code Class} objects, this method returns {@code true} if either
 633      *          preview features are disabled or {@linkplain Modifier#IDENTITY} is set in the
 634      *          {@linkplain #getModifiers() class modifiers}.
 635      * </ul>
 636      * @see AccessFlag#IDENTITY
 637      * @since Valhalla
 638      */
 639     @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS, reflective=true)
 640     public boolean isIdentity() {
 641         if (isPrimitive()) {
 642             return false;
 643         } else if (PreviewFeatures.isEnabled()) {
 644            return isArray() || Modifier.isIdentity(modifiers);
 645         } else {
 646             return !isInterface();
 647         }
 648     }
 649 
 650     /**
 651      * {@return {@code true} if this {@code Class} object represents a value class,
 652      * otherwise {@code false}}
 653      * <ul>
 654      *      <li>
 655      *          If this {@code Class} object represents an array type this method returns {@code false}.
 656      *      <li>
 657      *          If this {@code Class} object represents an interface, a primitive type,
 658      *          or {@code void} this method returns {@code true} only if preview features are enabled.
 659      *      <li>
 660      *          For all other {@code Class} objects, this method returns {@code true} only if
 661      *          preview features are enabled and {@linkplain Modifier#IDENTITY} is not set in the
 662      *          {@linkplain #getModifiers() class modifiers}.
 663      * </ul>
 664      * @see AccessFlag#IDENTITY
 665      * @since Valhalla
 666      */
 667     @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS, reflective=true)
 668     public boolean isValue() {
 669         if (!PreviewFeatures.isEnabled()) {
 670             return false;
 671         }
 672         return !isIdentity();
 673     }
 674 
 675     /**
 676      * {@return the {@code Class} object associated with the
 677      * {@linkplain #isPrimitive() primitive type} of the given name}
 678      * If the argument is not the name of a primitive type, {@code
 679      * null} is returned.
 680      *
 681      * @param primitiveName the name of the primitive type to find
 682      *
 683      * @throws NullPointerException if the argument is {@code null}
 684      *
 685      * @jls 4.2 Primitive Types and Values
 686      * @jls 15.8.2 Class Literals
 687      * @since 22
 688      */
 689     public static Class<?> forPrimitiveName(String primitiveName) {
 690         return switch(primitiveName) {
 691         // Integral types
 692         case "int"     -> int.class;
 693         case "long"    -> long.class;
 694         case "short"   -> short.class;

1382         }
1383         return c;
1384     }
1385 
1386     /**
1387      * Returns the Java language modifiers for this class or interface, encoded
1388      * in an integer. The modifiers consist of the Java Virtual Machine's
1389      * constants for {@code public}, {@code protected},
1390      * {@code private}, {@code final}, {@code static},
1391      * {@code abstract} and {@code interface}; they should be decoded
1392      * using the methods of class {@code Modifier}.
1393      *
1394      * <p> If the underlying class is an array class:
1395      * <ul>
1396      * <li> its {@code public}, {@code private} and {@code protected}
1397      *      modifiers are the same as those of its component type
1398      * <li> its {@code abstract} and {@code final} modifiers are always
1399      *      {@code true}
1400      * <li> its interface modifier is always {@code false}, even when
1401      *      the component type is an interface
1402      * <li> its {@code identity} modifier is always true
1403      * </ul>
1404      * If this {@code Class} object represents a primitive type or
1405      * void, its {@code public}, {@code abstract}, and {@code final}
1406      * modifiers are always {@code true}.
1407      * For {@code Class} objects representing void, primitive types, and
1408      * arrays, the values of other modifiers are {@code false} other
1409      * than as specified above.
1410      *
1411      * <p> The modifier encodings are defined in section {@jvms 4.1}
1412      * of <cite>The Java Virtual Machine Specification</cite>.
1413      *
1414      * @return the {@code int} representing the modifiers for this class
1415      * @see     java.lang.reflect.Modifier
1416      * @see #accessFlags()
1417      * @see <a
1418      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1419      * programming language and JVM modeling in core reflection</a>
1420      * @since 1.1
1421      * @jls 8.1.1 Class Modifiers
1422      * @jls 9.1.1 Interface Modifiers
1423      * @jvms 4.1 The {@code ClassFile} Structure
1424      */
1425     public int getModifiers() { return modifiers; }
1426 
1427    /**
1428      * {@return an unmodifiable set of the {@linkplain AccessFlag access
1429      * flags} for this class, possibly empty}
1430      * The {@code AccessFlags} may depend on the class file format version of the class.
1431      *
1432      * <p> If the underlying class is an array class:
1433      * <ul>
1434      * <li> its {@code PUBLIC}, {@code PRIVATE} and {@code PROTECTED}
1435      *      access flags are the same as those of its component type
1436      * <li> its {@code ABSTRACT} and {@code FINAL} flags are present
1437      * <li> its {@code INTERFACE} flag is absent, even when the
1438      *      component type is an interface
1439     * <li> its {@code identity} modifier is always true
1440      * </ul>
1441      * If this {@code Class} object represents a primitive type or
1442      * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
1443      * {@code FINAL}.
1444      * For {@code Class} objects representing void, primitive types, and
1445      * arrays, access flags are absent other than as specified above.
1446      *
1447      * @see #getModifiers()
1448      * @jvms 4.1 The ClassFile Structure
1449      * @jvms 4.7.6 The InnerClasses Attribute
1450      * @since 20
1451      */
1452     public Set<AccessFlag> accessFlags() {
1453         // Location.CLASS allows SUPER and AccessFlag.MODULE which
1454         // INNER_CLASS forbids. INNER_CLASS allows PRIVATE, PROTECTED,
1455         // and STATIC, which are not allowed on Location.CLASS.
1456         // Use getClassFileAccessFlags to expose SUPER status.
1457         // Arrays need to use PRIVATE/PROTECTED from its component modifiers.
1458         var location = (isMemberClass() || isLocalClass() ||
1459                         isAnonymousClass() || isArray()) ?
1460             AccessFlag.Location.INNER_CLASS :
1461             AccessFlag.Location.CLASS;
1462         int accessFlags = location == AccessFlag.Location.CLASS ? getClassFileAccessFlags() : getModifiers();
1463         var reflectionFactory = getReflectionFactory();
1464         var ans = reflectionFactory.parseAccessFlags(accessFlags, location, this);
1465         if (PreviewFeatures.isEnabled() && reflectionFactory.classFileFormatVersion(this) != ClassFileFormatVersion.CURRENT_PREVIEW_FEATURES
1466                 && isIdentity()) {
1467             var set = new HashSet<>(ans);
1468             set.add(AccessFlag.IDENTITY);
1469             return Set.copyOf(set);
1470         }
1471         return ans;
1472     }
1473 
1474    /**
1475      * Gets the signers of this class.
1476      *
1477      * @return  the signers of this class, or null if there are no signers.  In
1478      *          particular, this method returns null if this {@code Class} object represents
1479      *          a primitive type or void.
1480      * @since   1.1
1481      */
1482 
1483     public Object[] getSigners() {
1484         var signers = this.signers;
1485         return signers == null ? null : signers.clone();
1486     }
1487 
1488     /**
1489      * Set the signers of this class.
1490      */
1491     void setSigners(Object[] signers) {
1492         if (!isPrimitive() && !isArray()) {
1493             this.signers = signers;
1494         }
1495     }
1496 
1497     /**
1498      * If this {@code Class} object represents a local or anonymous
1499      * class within a method, returns a {@link
1500      * java.lang.reflect.Method Method} object representing the
1501      * immediately enclosing method of the underlying class. Returns
1502      * {@code null} otherwise.

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

4190      * @since 17
4191      */
4192     public boolean isSealed() {
4193         if (isArray() || isPrimitive()) {
4194             return false;
4195         }
4196         return getPermittedSubclasses() != null;
4197     }
4198 
4199     private native Class<?>[] getPermittedSubclasses0();
4200 
4201     /*
4202      * Return the class's major and minor class file version packed into an int.
4203      * The high order 16 bits contain the class's minor version.  The low order
4204      * 16 bits contain the class's major version.
4205      *
4206      * If the class is an array type then the class file version of its element
4207      * type is returned.  If the class is a primitive type then the latest class
4208      * file major version is returned and zero is returned for the minor version.
4209      */
4210     /* package-private */
4211     int getClassFileVersion() {
4212         Class<?> c = isArray() ? elementType() : this;
4213         return c.getClassFileVersion0();
4214     }
4215 
4216     private native int getClassFileVersion0();
4217 
4218      /**
4219       * Return the access flags as they were in the class's bytecode, including
4220       * the original setting of ACC_SUPER.
4221       *
4222       * If this {@code Class} object represents a primitive type or
4223       * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
4224       * {@code FINAL}.
4225       * If this {@code Class} object represents an array type, return 0.
4226       */
4227      int getClassFileAccessFlags() {
4228          return classFileAccessFlags;
4229      }
4230 }
< prev index next >