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.GenericSignatureFormatError;
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.LinkedHashMap;
64 import java.util.LinkedHashSet;
65 import java.util.List;
66 import java.util.Map;
67 import java.util.Objects;
68 import java.util.Optional;
69 import java.util.Set;
70 import java.util.stream.Collectors;
71
72 import jdk.internal.constant.ConstantUtils;
73 import jdk.internal.loader.BootLoader;
74 import jdk.internal.loader.BuiltinClassLoader;
75 import jdk.internal.misc.Unsafe;
76 import jdk.internal.module.Resources;
77 import jdk.internal.reflect.CallerSensitive;
78 import jdk.internal.reflect.CallerSensitiveAdapter;
79 import jdk.internal.reflect.ConstantPool;
80 import jdk.internal.reflect.Reflection;
81 import jdk.internal.reflect.ReflectionFactory;
82 import jdk.internal.util.ModifiedUtf;
83 import jdk.internal.vm.annotation.AOTRuntimeSetup;
84 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
85 import jdk.internal.vm.annotation.IntrinsicCandidate;
86 import jdk.internal.vm.annotation.Stable;
87
88 import sun.invoke.util.BytecodeDescriptor;
89 import sun.invoke.util.Wrapper;
90 import sun.reflect.generics.factory.CoreReflectionFactory;
91 import sun.reflect.generics.factory.GenericsFactory;
92 import sun.reflect.generics.repository.ClassRepository;
93 import sun.reflect.generics.scope.ClassScope;
94 import sun.reflect.annotation.*;
95
96 /**
97 * Instances of the class {@code Class} represent classes and
98 * interfaces in a running Java application. An enum class and a record
99 * class are kinds of class; an annotation interface is a kind of
207 * {@linkplain #getTypeName type name} return results
208 * equal to {@code "HelloWorld"}. The {@linkplain #getSimpleName
209 * simple name} of such an implicitly declared class is {@code "HelloWorld"} and
210 * the {@linkplain #getCanonicalName canonical name} is {@code "HelloWorld"}.
211 *
212 * @param <T> the type of the class modeled by this {@code Class}
213 * object. For example, the type of {@code String.class} is {@code
214 * Class<String>}. Use {@code Class<?>} if the class being modeled is
215 * unknown.
216 *
217 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
218 * @since 1.0
219 */
220 @AOTSafeClassInitializer
221 public final class Class<T> implements java.io.Serializable,
222 GenericDeclaration,
223 Type,
224 AnnotatedElement,
225 TypeDescriptor.OfField<Class<?>>,
226 Constable {
227 private static final int ANNOTATION = 0x00002000;
228 private static final int ENUM = 0x00004000;
229 private static final int SYNTHETIC = 0x00001000;
230
231 private static native void registerNatives();
232 static {
233 runtimeSetup();
234 }
235
236 /// No significant static final fields
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
249 // prevents future JIT optimizations from assuming this final field is null.
326 Reflection.appendAccessControlModifiers(sb, modifiers);
327 if (Modifier.isAbstract(modifiers))
328 sb.append("abstract "); // Intentionally printed for interfaces
329 if (Modifier.isStatic(modifiers))
330 sb.append("static ");
331 if (Modifier.isFinal(modifiers))
332 sb.append("final ");
333
334 addSealingInfo(modifiers, sb);
335
336 // Note: class strictfp modifier is not recoverable from a class file
337
338 if (isAnnotation()) {
339 sb.append('@');
340 }
341 if (isInterface()) { // Note: all annotation interfaces are interfaces
342 sb.append("interface");
343 } else {
344 if (isEnum())
345 sb.append("enum");
346 else if (isRecord())
347 sb.append("record");
348 else
349 sb.append("class");
350 }
351 sb.append(' ');
352 sb.append(getName());
353 }
354
355 TypeVariable<?>[] typeparms = component.getTypeParameters();
356 if (typeparms.length > 0) {
357 sb.append(Arrays.stream(typeparms)
358 .map(Class::typeVarBounds)
359 .collect(Collectors.joining(",", "<", ">")));
360 }
361
362 if (arrayDepth > 0) sb.append("[]".repeat(arrayDepth));
363
364 return sb.toString();
365 }
366 }
367
368 private void addSealingInfo(int modifiers, StringBuilder sb) {
369 // A class can be final XOR sealed XOR non-sealed.
598 *
599 * @jls 12.2 Loading of Classes and Interfaces
600 * @jls 12.3 Linking of Classes and Interfaces
601 * @since 9
602 */
603 public static Class<?> forName(Module module, String name) {
604 Objects.requireNonNull(module);
605 Objects.requireNonNull(name);
606 if (!ModifiedUtf.isValidLengthInConstantPool(name)) {
607 return null;
608 }
609
610 ClassLoader cl = module.getClassLoader();
611 if (cl != null) {
612 return cl.loadClass(module, name);
613 } else {
614 return BootLoader.loadClass(module, name);
615 }
616 }
617
618 /**
619 * {@return the {@code Class} object associated with the
620 * {@linkplain #isPrimitive() primitive type} of the given name}
621 * If the argument is not the name of a primitive type, {@code
622 * null} is returned.
623 *
624 * @param primitiveName the name of the primitive type to find
625 *
626 * @jls 4.2 Primitive Types and Values
627 * @jls 15.8.2 Class Literals
628 * @since 22
629 */
630 public static Class<?> forPrimitiveName(String primitiveName) {
631 return switch(primitiveName) {
632 // Integral types
633 case "int" -> int.class;
634 case "long" -> long.class;
635 case "short" -> short.class;
636 case "char" -> char.class;
637 case "byte" -> byte.class;
854 * @see java.lang.Float#TYPE
855 * @see java.lang.Double#TYPE
856 * @see java.lang.Void#TYPE
857 * @since 1.1
858 * @jls 15.8.2 Class Literals
859 */
860 public boolean isPrimitive() {
861 return primitive;
862 }
863
864 /**
865 * Returns true if this {@code Class} object represents an annotation
866 * interface. Note that if this method returns true, {@link #isInterface()}
867 * would also return true, as all annotation interfaces are also interfaces.
868 *
869 * @return {@code true} if this {@code Class} object represents an annotation
870 * interface; {@code false} otherwise
871 * @since 1.5
872 */
873 public boolean isAnnotation() {
874 return (getModifiers() & ANNOTATION) != 0;
875 }
876
877 /**
878 *{@return {@code true} if and only if this class has the synthetic modifier
879 * bit set}
880 *
881 * @jls 13.1 The Form of a Binary
882 * @jvms 4.1 The {@code ClassFile} Structure
883 * @see <a
884 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
885 * programming language and JVM modeling in core reflection</a>
886 * @since 1.5
887 */
888 public boolean isSynthetic() {
889 return (getModifiers() & SYNTHETIC) != 0;
890 }
891
892 /**
893 * Returns the name of the entity (class, interface, array class,
894 * primitive type, or void) represented by this {@code Class} object.
895 *
896 * <p> If this {@code Class} object represents a class or interface,
897 * not an array class, then:
898 * <ul>
899 * <li> If the class or interface is not {@linkplain #isHidden() hidden},
900 * then the {@linkplain ClassLoader##binary-name binary name}
901 * of the class or interface is returned.
902 * <li> If the class or interface is hidden, then the result is a string
903 * of the form: {@code N + '/' + <suffix>}
904 * where {@code N} is the {@linkplain ClassLoader##binary-name binary name}
905 * indicated by the {@code class} file passed to
906 * {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
907 * Lookup::defineHiddenClass}, and {@code <suffix>} is an unqualified name.
908 * </ul>
909 *
1002 *
1003 * @since 9
1004 */
1005 public Module getModule() {
1006 return module;
1007 }
1008
1009 // set by VM
1010 @Stable
1011 private transient Module module;
1012
1013 // Initialized in JVM not by private constructor
1014 // This field is filtered from reflection access, i.e. getDeclaredField
1015 // will throw NoSuchFieldException
1016 private final ClassLoader classLoader;
1017
1018 private transient Object classData; // Set by VM
1019 private transient Object[] signers; // Read by VM, mutable
1020 private final transient char modifiers; // Set by the VM
1021 private final transient char classFileAccessFlags; // Set by the VM
1022 private final transient boolean primitive; // Set by the VM if the Class is a primitive type.
1023
1024 // package-private
1025 Object getClassData() {
1026 return classData;
1027 }
1028
1029 /**
1030 * Returns an array of {@code TypeVariable} objects that represent the
1031 * type variables declared by the generic declaration represented by this
1032 * {@code GenericDeclaration} object, in declaration order. Returns an
1033 * array of length 0 if the underlying generic declaration declares no type
1034 * variables.
1035 *
1036 * @return an array of {@code TypeVariable} objects that represent
1037 * the type variables declared by this generic declaration
1038 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
1039 * signature of this generic declaration does not conform to
1040 * the format specified in section {@jvms 4.7.9} of
1041 * <cite>The Java Virtual Machine Specification</cite>
1042 * @since 1.5
1322 }
1323 return c;
1324 }
1325
1326 /**
1327 * Returns the Java language modifiers for this class or interface, encoded
1328 * in an integer. The modifiers consist of the Java Virtual Machine's
1329 * constants for {@code public}, {@code protected},
1330 * {@code private}, {@code final}, {@code static},
1331 * {@code abstract} and {@code interface}; they should be decoded
1332 * using the methods of class {@code Modifier}.
1333 *
1334 * <p> If the underlying class is an array class:
1335 * <ul>
1336 * <li> its {@code public}, {@code private} and {@code protected}
1337 * modifiers are the same as those of its component type
1338 * <li> its {@code abstract} and {@code final} modifiers are always
1339 * {@code true}
1340 * <li> its interface modifier is always {@code false}, even when
1341 * the component type is an interface
1342 * </ul>
1343 * If this {@code Class} object represents a primitive type or
1344 * void, its {@code public}, {@code abstract}, and {@code final}
1345 * modifiers are always {@code true}.
1346 * For {@code Class} objects representing void, primitive types, and
1347 * arrays, the values of other modifiers are {@code false} other
1348 * than as specified above.
1349 *
1350 * <p> The modifier encodings are defined in section {@jvms 4.1}
1351 * of <cite>The Java Virtual Machine Specification</cite>.
1352 *
1353 * @return the {@code int} representing the modifiers for this class
1354 * @see java.lang.reflect.Modifier
1355 * @see #accessFlags()
1356 * @see <a
1357 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1358 * programming language and JVM modeling in core reflection</a>
1359 * @since 1.1
1360 * @jls 8.1.1 Class Modifiers
1361 * @jls 9.1.1 Interface Modifiers
1362 * @jvms 4.1 The {@code ClassFile} Structure
1363 */
1364 public int getModifiers() { return modifiers; }
1365
1366 /**
1367 * {@return an unmodifiable set of the {@linkplain AccessFlag access
1368 * flags} for this class, possibly empty}
1369 *
1370 * <p> If the underlying class is an array class:
1371 * <ul>
1372 * <li> its {@code PUBLIC}, {@code PRIVATE} and {@code PROTECTED}
1373 * access flags are the same as those of its component type
1374 * <li> its {@code ABSTRACT} and {@code FINAL} flags are present
1375 * <li> its {@code INTERFACE} flag is absent, even when the
1376 * component type is an interface
1377 * </ul>
1378 * If this {@code Class} object represents a primitive type or
1379 * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
1380 * {@code FINAL}.
1381 * For {@code Class} objects representing void, primitive types, and
1382 * arrays, access flags are absent other than as specified above.
1383 *
1384 * @see #getModifiers()
1385 * @jvms 4.1 The ClassFile Structure
1386 * @jvms 4.7.6 The InnerClasses Attribute
1387 * @since 20
1388 */
1389 public Set<AccessFlag> accessFlags() {
1390 // Location.CLASS allows SUPER and AccessFlag.MODULE which
1391 // INNER_CLASS forbids. INNER_CLASS allows PRIVATE, PROTECTED,
1392 // and STATIC, which are not allowed on Location.CLASS.
1393 // Use getClassFileAccessFlags to expose SUPER status.
1394 // Arrays need to use PRIVATE/PROTECTED from its component modifiers.
1395 var location = (isMemberClass() || isLocalClass() ||
1396 isAnonymousClass() || isArray()) ?
1397 AccessFlag.Location.INNER_CLASS :
1398 AccessFlag.Location.CLASS;
1399 return ReflectionFactory.getReflectionFactory().parseAccessFlags(
1400 (location == AccessFlag.Location.CLASS) ? getClassFileAccessFlags() : getModifiers(),
1401 location, this);
1402 }
1403
1404 /**
1405 * Gets the signers of this class.
1406 *
1407 * @return the signers of this class, or null if there are no signers. In
1408 * particular, this method returns null if this {@code Class} object represents
1409 * a primitive type or void.
1410 * @since 1.1
1411 */
1412 public Object[] getSigners() {
1413 var signers = this.signers;
1414 return signers == null ? null : signers.clone();
1415 }
1416
1417 /**
1418 * Set the signers of this class.
1419 */
1420 void setSigners(Object[] signers) {
1421 if (!isPrimitive() && !isArray()) {
3347 * source code.
3348 *
3349 * Note that {@link java.lang.Enum} is not itself an enum class.
3350 *
3351 * Also note that if an enum constant is declared with a class body,
3352 * the class of that enum constant object is an anonymous class
3353 * and <em>not</em> the class of the declaring enum class. The
3354 * {@link Enum#getDeclaringClass} method of an enum constant can
3355 * be used to get the class of the enum class declaring the
3356 * constant.
3357 *
3358 * @return true if and only if this class was declared as an enum in the
3359 * source code
3360 * @since 1.5
3361 * @jls 8.9.1 Enum Constants
3362 */
3363 public boolean isEnum() {
3364 // An enum must both directly extend java.lang.Enum and have
3365 // the ENUM bit set; classes for specialized enum constants
3366 // don't do the former.
3367 return (this.getModifiers() & ENUM) != 0 &&
3368 this.getSuperclass() == java.lang.Enum.class;
3369 }
3370
3371 /**
3372 * Returns {@code true} if and only if this class is a record class.
3373 *
3374 * <p> The {@linkplain #getSuperclass() direct superclass} of a record
3375 * class is {@code java.lang.Record}. A record class is {@linkplain
3376 * Modifier#FINAL final}. A record class has (possibly zero) record
3377 * components; {@link #getRecordComponents()} returns a non-null but
3378 * possibly empty value for a record.
3379 *
3380 * <p> Note that class {@link Record} is not a record class and thus
3381 * invoking this method on class {@code Record} returns {@code false}.
3382 *
3383 * @return true if and only if this class is a record class, otherwise false
3384 * @jls 8.10 Record Classes
3385 * @since 16
3386 */
3387 public boolean isRecord() {
|
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.GenericSignatureFormatError;
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.lang.classfile.ClassFile;
56 import java.net.URL;
57 import java.security.AllPermission;
58 import java.security.Permissions;
59 import java.security.ProtectionDomain;
60 import java.util.ArrayList;
61 import java.util.Arrays;
62 import java.util.Collection;
63 import java.util.HashMap;
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.AccessFlagSet;
81 import jdk.internal.reflect.CallerSensitive;
82 import jdk.internal.reflect.CallerSensitiveAdapter;
83 import jdk.internal.reflect.ConstantPool;
84 import jdk.internal.reflect.PreviewAccessFlags;
85 import jdk.internal.reflect.Reflection;
86 import jdk.internal.reflect.ReflectionFactory;
87 import jdk.internal.util.ModifiedUtf;
88 import jdk.internal.vm.annotation.AOTRuntimeSetup;
89 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
90 import jdk.internal.vm.annotation.IntrinsicCandidate;
91 import jdk.internal.vm.annotation.Stable;
92
93 import sun.invoke.util.BytecodeDescriptor;
94 import sun.invoke.util.Wrapper;
95 import sun.reflect.generics.factory.CoreReflectionFactory;
96 import sun.reflect.generics.factory.GenericsFactory;
97 import sun.reflect.generics.repository.ClassRepository;
98 import sun.reflect.generics.scope.ClassScope;
99 import sun.reflect.annotation.*;
100
101 /**
102 * Instances of the class {@code Class} represent classes and
103 * interfaces in a running Java application. An enum class and a record
104 * class are kinds of class; an annotation interface is a kind of
212 * {@linkplain #getTypeName type name} return results
213 * equal to {@code "HelloWorld"}. The {@linkplain #getSimpleName
214 * simple name} of such an implicitly declared class is {@code "HelloWorld"} and
215 * the {@linkplain #getCanonicalName canonical name} is {@code "HelloWorld"}.
216 *
217 * @param <T> the type of the class modeled by this {@code Class}
218 * object. For example, the type of {@code String.class} is {@code
219 * Class<String>}. Use {@code Class<?>} if the class being modeled is
220 * unknown.
221 *
222 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
223 * @since 1.0
224 */
225 @AOTSafeClassInitializer
226 public final class Class<T> implements java.io.Serializable,
227 GenericDeclaration,
228 Type,
229 AnnotatedElement,
230 TypeDescriptor.OfField<Class<?>>,
231 Constable {
232
233 private static native void registerNatives();
234 static {
235 runtimeSetup();
236 }
237
238 /// No significant static final fields
239 @AOTRuntimeSetup
240 private static void runtimeSetup() {
241 registerNatives();
242 }
243
244 /*
245 * Private constructor. Only the Java Virtual Machine creates Class objects.
246 * This constructor is not used and prevents the default constructor being
247 * generated.
248 */
249 private Class(ClassLoader loader, Class<?> arrayComponentType, char mods, ProtectionDomain pd, boolean isPrim, char flags) {
250 // Initialize final field for classLoader. The initialization value of non-null
251 // prevents future JIT optimizations from assuming this final field is null.
328 Reflection.appendAccessControlModifiers(sb, modifiers);
329 if (Modifier.isAbstract(modifiers))
330 sb.append("abstract "); // Intentionally printed for interfaces
331 if (Modifier.isStatic(modifiers))
332 sb.append("static ");
333 if (Modifier.isFinal(modifiers))
334 sb.append("final ");
335
336 addSealingInfo(modifiers, sb);
337
338 // Note: class strictfp modifier is not recoverable from a class file
339
340 if (isAnnotation()) {
341 sb.append('@');
342 }
343 if (isInterface()) { // Note: all annotation interfaces are interfaces
344 sb.append("interface");
345 } else {
346 if (isEnum())
347 sb.append("enum");
348 else {
349 if (isValue()) {
350 sb.append("value ");
351 }
352 if (isRecord()) {
353 sb.append("record");
354 } else {
355 sb.append("class");
356 }
357 }
358 }
359 sb.append(' ');
360 sb.append(getName());
361 }
362
363 TypeVariable<?>[] typeparms = component.getTypeParameters();
364 if (typeparms.length > 0) {
365 sb.append(Arrays.stream(typeparms)
366 .map(Class::typeVarBounds)
367 .collect(Collectors.joining(",", "<", ">")));
368 }
369
370 if (arrayDepth > 0) sb.append("[]".repeat(arrayDepth));
371
372 return sb.toString();
373 }
374 }
375
376 private void addSealingInfo(int modifiers, StringBuilder sb) {
377 // A class can be final XOR sealed XOR non-sealed.
606 *
607 * @jls 12.2 Loading of Classes and Interfaces
608 * @jls 12.3 Linking of Classes and Interfaces
609 * @since 9
610 */
611 public static Class<?> forName(Module module, String name) {
612 Objects.requireNonNull(module);
613 Objects.requireNonNull(name);
614 if (!ModifiedUtf.isValidLengthInConstantPool(name)) {
615 return null;
616 }
617
618 ClassLoader cl = module.getClassLoader();
619 if (cl != null) {
620 return cl.loadClass(module, name);
621 } else {
622 return BootLoader.loadClass(module, name);
623 }
624 }
625
626 /**
627 * {@return {@code true} if this {@code Class} object represents a value class,
628 * otherwise {@code false}}
629 *
630 * <p>A value class is declared with the {@code value} modifier. If this
631 * {@code Class} object represents an interface, array type, primitive type,
632 * or {@code void}, the result is {@code false}.
633 *
634 * <p>This method returns {@code true} if and only if this {@code Class}
635 * object represents a class that uses preview features, and the class does
636 * not have the {@link AccessFlag#IDENTITY ACC_IDENTITY} flag set.
637 * The {@code ACC_IDENTITY} flag is considered always set for a class that
638 * does not use preview features; consequently, this method always returns
639 * {@code false} when preview features are disabled.
640 *
641 * @jls value-objects-8.1.1.5 {@code value} Classes
642 * @see AccessFlag#IDENTITY
643 * @since 28
644 */
645 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS, reflective=true)
646 public boolean isValue() {
647 if (!PreviewFeatures.isEnabled()) {
648 return false;
649 } else {
650 int mask = ClassFile.ACC_IDENTITY | ClassFile.ACC_INTERFACE;
651 return !primitive && (getModifiers() & mask) == 0;
652 }
653 }
654
655 /**
656 * {@return the {@code Class} object associated with the
657 * {@linkplain #isPrimitive() primitive type} of the given name}
658 * If the argument is not the name of a primitive type, {@code
659 * null} is returned.
660 *
661 * @param primitiveName the name of the primitive type to find
662 *
663 * @jls 4.2 Primitive Types and Values
664 * @jls 15.8.2 Class Literals
665 * @since 22
666 */
667 public static Class<?> forPrimitiveName(String primitiveName) {
668 return switch(primitiveName) {
669 // Integral types
670 case "int" -> int.class;
671 case "long" -> long.class;
672 case "short" -> short.class;
673 case "char" -> char.class;
674 case "byte" -> byte.class;
891 * @see java.lang.Float#TYPE
892 * @see java.lang.Double#TYPE
893 * @see java.lang.Void#TYPE
894 * @since 1.1
895 * @jls 15.8.2 Class Literals
896 */
897 public boolean isPrimitive() {
898 return primitive;
899 }
900
901 /**
902 * Returns true if this {@code Class} object represents an annotation
903 * interface. Note that if this method returns true, {@link #isInterface()}
904 * would also return true, as all annotation interfaces are also interfaces.
905 *
906 * @return {@code true} if this {@code Class} object represents an annotation
907 * interface; {@code false} otherwise
908 * @since 1.5
909 */
910 public boolean isAnnotation() {
911 return (getModifiers() & ClassFile.ACC_ANNOTATION) != 0;
912 }
913
914 /**
915 *{@return {@code true} if and only if this class has the synthetic modifier
916 * bit set}
917 *
918 * @jls 13.1 The Form of a Binary
919 * @jvms 4.1 The {@code ClassFile} Structure
920 * @see <a
921 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
922 * programming language and JVM modeling in core reflection</a>
923 * @since 1.5
924 */
925 public boolean isSynthetic() {
926 return (getModifiers() & ClassFile.ACC_SYNTHETIC) != 0;
927 }
928
929 /**
930 * Returns the name of the entity (class, interface, array class,
931 * primitive type, or void) represented by this {@code Class} object.
932 *
933 * <p> If this {@code Class} object represents a class or interface,
934 * not an array class, then:
935 * <ul>
936 * <li> If the class or interface is not {@linkplain #isHidden() hidden},
937 * then the {@linkplain ClassLoader##binary-name binary name}
938 * of the class or interface is returned.
939 * <li> If the class or interface is hidden, then the result is a string
940 * of the form: {@code N + '/' + <suffix>}
941 * where {@code N} is the {@linkplain ClassLoader##binary-name binary name}
942 * indicated by the {@code class} file passed to
943 * {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
944 * Lookup::defineHiddenClass}, and {@code <suffix>} is an unqualified name.
945 * </ul>
946 *
1039 *
1040 * @since 9
1041 */
1042 public Module getModule() {
1043 return module;
1044 }
1045
1046 // set by VM
1047 @Stable
1048 private transient Module module;
1049
1050 // Initialized in JVM not by private constructor
1051 // This field is filtered from reflection access, i.e. getDeclaredField
1052 // will throw NoSuchFieldException
1053 private final ClassLoader classLoader;
1054
1055 private transient Object classData; // Set by VM
1056 private transient Object[] signers; // Read by VM, mutable
1057 private final transient char modifiers; // Set by the VM
1058 private final transient char classFileAccessFlags; // Set by the VM
1059 private final transient boolean primitive; // Set by the VM if the Class is a primitive type
1060
1061 // package-private
1062 Object getClassData() {
1063 return classData;
1064 }
1065
1066 /**
1067 * Returns an array of {@code TypeVariable} objects that represent the
1068 * type variables declared by the generic declaration represented by this
1069 * {@code GenericDeclaration} object, in declaration order. Returns an
1070 * array of length 0 if the underlying generic declaration declares no type
1071 * variables.
1072 *
1073 * @return an array of {@code TypeVariable} objects that represent
1074 * the type variables declared by this generic declaration
1075 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
1076 * signature of this generic declaration does not conform to
1077 * the format specified in section {@jvms 4.7.9} of
1078 * <cite>The Java Virtual Machine Specification</cite>
1079 * @since 1.5
1359 }
1360 return c;
1361 }
1362
1363 /**
1364 * Returns the Java language modifiers for this class or interface, encoded
1365 * in an integer. The modifiers consist of the Java Virtual Machine's
1366 * constants for {@code public}, {@code protected},
1367 * {@code private}, {@code final}, {@code static},
1368 * {@code abstract} and {@code interface}; they should be decoded
1369 * using the methods of class {@code Modifier}.
1370 *
1371 * <p> If the underlying class is an array class:
1372 * <ul>
1373 * <li> its {@code public}, {@code private} and {@code protected}
1374 * modifiers are the same as those of its component type
1375 * <li> its {@code abstract} and {@code final} modifiers are always
1376 * {@code true}
1377 * <li> its interface modifier is always {@code false}, even when
1378 * the component type is an interface
1379 * <li> when preview features are enabled, its {@link
1380 * AccessFlag#IDENTITY identity} modifier is always true
1381 * </ul>
1382 * If this {@code Class} object represents a primitive type or
1383 * void, its {@code public}, {@code abstract}, and {@code final}
1384 * modifiers are always {@code true}.
1385 * For {@code Class} objects representing void, primitive types, and
1386 * arrays, the values of other modifiers are {@code false} other
1387 * than as specified above.
1388 *
1389 * <div class="preview-block">
1390 * <div class="preview-comment">
1391 * When preview features are enabled and this {@code Class} object
1392 * either represents a class whose {@code class} file does not
1393 * depend on preview features or represents an array type, its
1394 * {@code identity} modifier is always true.
1395 * <p>
1396 * When preview features are disabled, the {@code Class} object
1397 * does not have its {@code identity} modifier set.
1398 * </div>
1399 * </div>
1400 *
1401 * <p> The modifier encodings are defined in section {@jvms 4.1}
1402 * of <cite>The Java Virtual Machine Specification</cite>.
1403 *
1404 * @apiNote
1405 * <div class="preview-block">
1406 * <div class="preview-comment">
1407 * Developers should be aware that the presence of the {@code
1408 * identity} modifier is dependent on whether preview features are
1409 * enabled. Use the {@link #isValue() Class.isValue()} method to
1410 * test if a class is an identity class or a value class.
1411 * <p>
1412 * This snippet below checks whether a given {@code Class<?> clazz}
1413 * would have its {@code identity} modifier set when preview
1414 * features are enabled, yet behaves consistently regardless of
1415 * whether preview features are enabled.
1416 * {@snippet lang=java :
1417 * !clazz.isPrimitive() && !clazz.isValue() && !clazz.isInterface()
1418 * }
1419 * </div>
1420 * </div>
1421 *
1422 * @return the {@code int} representing the modifiers for this class
1423 * @see java.lang.reflect.Modifier
1424 * @see #accessFlags()
1425 * @see <a
1426 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1427 * programming language and JVM modeling in core reflection</a>
1428 * @since 1.1
1429 * @jls 8.1.1 Class Modifiers
1430 * @jls 9.1.1 Interface Modifiers
1431 * @jvms 4.1 The {@code ClassFile} Structure
1432 */
1433 public int getModifiers() { return modifiers; }
1434
1435 /**
1436 * {@return an unmodifiable set of the {@linkplain AccessFlag access
1437 * flags} for this class, possibly empty}
1438 *
1439 * <p> If the underlying class is an array class:
1440 * <ul>
1441 * <li> its {@code PUBLIC}, {@code PRIVATE} and {@code PROTECTED}
1442 * access flags are the same as those of its component type
1443 * <li> its {@code ABSTRACT} and {@code FINAL} flags are present
1444 * <li> its {@code INTERFACE} flag is absent, even when the
1445 * component type is an interface
1446 * <li> when preview features are enabled, its {@code IDENTITY} flag
1447 * is present
1448 * </ul>
1449 * If this {@code Class} object represents a primitive type or
1450 * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
1451 * {@code FINAL}.
1452 * For {@code Class} objects representing void, primitive types, and
1453 * arrays, access flags are absent other than as specified above.
1454 *
1455 * <div class="preview-block">
1456 * <div class="preview-comment">
1457 * When preview features are enabled and this {@code Class} object
1458 * either represents a class whose {@code class} file does not
1459 * depend on preview features or represents an array type, its
1460 * flags always include {@code IDENTITY}.
1461 * <p>
1462 * When preview features are disabled, the {@code Class} object
1463 * does not have the {@code IDENTITY} flag set.
1464 * </div>
1465 * </div>
1466 *
1467 * @apiNote
1468 * <div class="preview-block">
1469 * <div class="preview-comment">
1470 * Developers should be aware that the presence of the {@code
1471 * identity} modifier is dependent on whether preview features are
1472 * enabled. Use the {@link #isValue() Class.isValue()} method to
1473 * test if a class is an identity class or a value class.
1474 * <p>
1475 * This snippet below checks whether a given {@code Class<?> clazz}
1476 * would have its {@code IDENTITY} modifier set when preview
1477 * features are enabled, yet behaves consistently regardless of
1478 * whether preview features are enabled.
1479 * {@snippet lang=java :
1480 * !clazz.isPrimitive() && !clazz.isValue() && !clazz.isInterface()
1481 * }
1482 * </div>
1483 * </div>
1484 *
1485 * @see #getModifiers()
1486 * @jvms 4.1 The ClassFile Structure
1487 * @jvms 4.7.6 The InnerClasses Attribute
1488 * @since 20
1489 */
1490 public Set<AccessFlag> accessFlags() {
1491 if (!PreviewFeatures.isEnabled()) {
1492 // INNER_CLASS_FLAGS exclusively defines PRIVATE, PROTECTED, and STATIC.
1493 // CLASS_FLAGS exclusively defines SUPER and MODULE.
1494 // Nested classes and interfaces need to report PRIVATE/PROTECTED/STATIC.
1495 // Arrays need to report PRIVATE/PROTECTED.
1496 // Top-level classes need to report SUPER, using getClassFileAccessFlags.
1497 // Module descriptors do not have Class objects so nothing reports MODULE.
1498 return (isArray() || getEnclosingClass() != null)
1499 ? AccessFlagSet.ofValidated(AccessFlagSet.INNER_CLASS_FLAGS, getModifiers())
1500 : AccessFlagSet.ofValidated(AccessFlagSet.CLASS_FLAGS, getClassFileAccessFlags());
1501 }
1502 // CLASS_FLAGS exclusively defines MODULE, but module descriptors are
1503 // never represented with Class objects, so INNER_CLASS_FLAGS works
1504 return AccessFlagSet.ofValidated(PreviewAccessFlags.INNER_CLASS_PREVIEW_FLAGS, getModifiers());
1505 }
1506
1507 /**
1508 * Gets the signers of this class.
1509 *
1510 * @return the signers of this class, or null if there are no signers. In
1511 * particular, this method returns null if this {@code Class} object represents
1512 * a primitive type or void.
1513 * @since 1.1
1514 */
1515 public Object[] getSigners() {
1516 var signers = this.signers;
1517 return signers == null ? null : signers.clone();
1518 }
1519
1520 /**
1521 * Set the signers of this class.
1522 */
1523 void setSigners(Object[] signers) {
1524 if (!isPrimitive() && !isArray()) {
3450 * source code.
3451 *
3452 * Note that {@link java.lang.Enum} is not itself an enum class.
3453 *
3454 * Also note that if an enum constant is declared with a class body,
3455 * the class of that enum constant object is an anonymous class
3456 * and <em>not</em> the class of the declaring enum class. The
3457 * {@link Enum#getDeclaringClass} method of an enum constant can
3458 * be used to get the class of the enum class declaring the
3459 * constant.
3460 *
3461 * @return true if and only if this class was declared as an enum in the
3462 * source code
3463 * @since 1.5
3464 * @jls 8.9.1 Enum Constants
3465 */
3466 public boolean isEnum() {
3467 // An enum must both directly extend java.lang.Enum and have
3468 // the ENUM bit set; classes for specialized enum constants
3469 // don't do the former.
3470 return (this.getModifiers() & ClassFile.ACC_ENUM) != 0 &&
3471 this.getSuperclass() == java.lang.Enum.class;
3472 }
3473
3474 /**
3475 * Returns {@code true} if and only if this class is a record class.
3476 *
3477 * <p> The {@linkplain #getSuperclass() direct superclass} of a record
3478 * class is {@code java.lang.Record}. A record class is {@linkplain
3479 * Modifier#FINAL final}. A record class has (possibly zero) record
3480 * components; {@link #getRecordComponents()} returns a non-null but
3481 * possibly empty value for a record.
3482 *
3483 * <p> Note that class {@link Record} is not a record class and thus
3484 * invoking this method on class {@code Record} returns {@code false}.
3485 *
3486 * @return true if and only if this class is a record class, otherwise false
3487 * @jls 8.10 Record Classes
3488 * @since 16
3489 */
3490 public boolean isRecord() {
|