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.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.*;
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; [#resetArchivedStates()] handles
237 /// prevents storing [#reflectionFactory] into AOT image.
238 @AOTRuntimeSetup
239 private static void runtimeSetup() {
240 registerNatives();
241 }
242
243 /*
244 * Private constructor. Only the Java Virtual Machine creates Class objects.
245 * This constructor is not used and prevents the default constructor being
246 * generated.
247 */
248 private Class(ClassLoader loader, Class<?> arrayComponentType, char mods, ProtectionDomain pd, boolean isPrim, char flags) {
249 // Initialize final field for classLoader. The initialization value of non-null
250 // prevents future JIT optimizations from assuming this final field is null.
251 // The following assignments are done directly by the VM without calling this constructor.
252 classLoader = loader;
253 componentType = arrayComponentType;
254 modifiers = mods;
255 protectionDomain = pd;
256 primitive = isPrim;
257 classFileAccessFlags = flags;
258 }
259
260 /**
261 * Converts the object to a string. The string representation is the
262 * string "class" or "interface", followed by a space, and then by the
263 * name of the class in the format returned by {@code getName}.
264 * If this {@code Class} object represents a primitive type,
265 * this method returns the name of the primitive type. If
266 * this {@code Class} object represents void this method returns
267 * "void". If this {@code Class} object represents an array type,
268 * this method returns "class " followed by {@code getName}.
269 *
270 * @return a string representation of this {@code Class} object.
271 */
272 public String toString() {
273 String kind = isInterface() ? "interface " : isPrimitive() ? "" : "class ";
274 return kind.concat(getName());
275 }
276
308 *
309 * @since 1.8
310 */
311 public String toGenericString() {
312 if (isPrimitive()) {
313 return toString();
314 } else {
315 StringBuilder sb = new StringBuilder();
316 Class<?> component = this;
317 int arrayDepth = 0;
318
319 if (isArray()) {
320 do {
321 arrayDepth++;
322 component = component.getComponentType();
323 } while (component.isArray());
324 sb.append(component.getName());
325 } else {
326 // Class modifiers are a superset of interface modifiers
327 int modifiers = getModifiers() & Modifier.classModifiers();
328 if (modifiers != 0) {
329 sb.append(Modifier.toString(modifiers));
330 sb.append(' ');
331 }
332
333 // A class cannot be strictfp and sealed/non-sealed so
334 // it is sufficient to check for sealed-ness after all
335 // modifiers are printed.
336 addSealingInfo(modifiers, sb);
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;
1001 *
1002 * @since 9
1003 */
1004 public Module getModule() {
1005 return module;
1006 }
1007
1008 // set by VM
1009 @Stable
1010 private transient Module module;
1011
1012 // Initialized in JVM not by private constructor
1013 // This field is filtered from reflection access, i.e. getDeclaredField
1014 // will throw NoSuchFieldException
1015 private final ClassLoader classLoader;
1016
1017 private transient Object classData; // Set by VM
1018 private transient Object[] signers; // Read by VM, mutable
1019 private final transient char modifiers; // Set by the VM
1020 private final transient char classFileAccessFlags; // Set by the VM
1021 private final transient boolean primitive; // Set by the VM if the Class is a primitive type.
1022
1023 // package-private
1024 Object getClassData() {
1025 return classData;
1026 }
1027
1028 /**
1029 * Returns an array of {@code TypeVariable} objects that represent the
1030 * type variables declared by the generic declaration represented by this
1031 * {@code GenericDeclaration} object, in declaration order. Returns an
1032 * array of length 0 if the underlying generic declaration declares no type
1033 * variables.
1034 *
1035 * @return an array of {@code TypeVariable} objects that represent
1036 * the type variables declared by this generic declaration
1037 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
1038 * signature of this generic declaration does not conform to
1039 * the format specified in section {@jvms 4.7.9} of
1040 * <cite>The Java Virtual Machine Specification</cite>
1041 * @since 1.5
1321 }
1322 return c;
1323 }
1324
1325 /**
1326 * Returns the Java language modifiers for this class or interface, encoded
1327 * in an integer. The modifiers consist of the Java Virtual Machine's
1328 * constants for {@code public}, {@code protected},
1329 * {@code private}, {@code final}, {@code static},
1330 * {@code abstract} and {@code interface}; they should be decoded
1331 * using the methods of class {@code Modifier}.
1332 *
1333 * <p> If the underlying class is an array class:
1334 * <ul>
1335 * <li> its {@code public}, {@code private} and {@code protected}
1336 * modifiers are the same as those of its component type
1337 * <li> its {@code abstract} and {@code final} modifiers are always
1338 * {@code true}
1339 * <li> its interface modifier is always {@code false}, even when
1340 * the component type is an interface
1341 * </ul>
1342 * If this {@code Class} object represents a primitive type or
1343 * void, its {@code public}, {@code abstract}, and {@code final}
1344 * modifiers are always {@code true}.
1345 * For {@code Class} objects representing void, primitive types, and
1346 * arrays, the values of other modifiers are {@code false} other
1347 * than as specified above.
1348 *
1349 * <p> The modifier encodings are defined in section {@jvms 4.1}
1350 * of <cite>The Java Virtual Machine Specification</cite>.
1351 *
1352 * @return the {@code int} representing the modifiers for this class
1353 * @see java.lang.reflect.Modifier
1354 * @see #accessFlags()
1355 * @see <a
1356 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1357 * programming language and JVM modeling in core reflection</a>
1358 * @since 1.1
1359 * @jls 8.1.1 Class Modifiers
1360 * @jls 9.1.1 Interface Modifiers
1361 * @jvms 4.1 The {@code ClassFile} Structure
1362 */
1363 public int getModifiers() { return modifiers; }
1364
1365 /**
1366 * {@return an unmodifiable set of the {@linkplain AccessFlag access
1367 * flags} for this class, possibly empty}
1368 *
1369 * <p> If the underlying class is an array class:
1370 * <ul>
1371 * <li> its {@code PUBLIC}, {@code PRIVATE} and {@code PROTECTED}
1372 * access flags are the same as those of its component type
1373 * <li> its {@code ABSTRACT} and {@code FINAL} flags are present
1374 * <li> its {@code INTERFACE} flag is absent, even when the
1375 * component type is an interface
1376 * </ul>
1377 * If this {@code Class} object represents a primitive type or
1378 * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
1379 * {@code FINAL}.
1380 * For {@code Class} objects representing void, primitive types, and
1381 * arrays, access flags are absent other than as specified above.
1382 *
1383 * @see #getModifiers()
1384 * @jvms 4.1 The ClassFile Structure
1385 * @jvms 4.7.6 The InnerClasses Attribute
1386 * @since 20
1387 */
1388 public Set<AccessFlag> accessFlags() {
1389 // Location.CLASS allows SUPER and AccessFlag.MODULE which
1390 // INNER_CLASS forbids. INNER_CLASS allows PRIVATE, PROTECTED,
1391 // and STATIC, which are not allowed on Location.CLASS.
1392 // Use getClassFileAccessFlags to expose SUPER status.
1393 var location = (isMemberClass() || isLocalClass() ||
1394 isAnonymousClass() || isArray()) ?
1395 AccessFlag.Location.INNER_CLASS :
1396 AccessFlag.Location.CLASS;
1397 return getReflectionFactory().parseAccessFlags((location == AccessFlag.Location.CLASS) ?
1398 getClassFileAccessFlags() : getModifiers(), location, this);
1399 }
1400
1401 /**
1402 * Gets the signers of this class.
1403 *
1404 * @return the signers of this class, or null if there are no signers. In
1405 * particular, this method returns null if this {@code Class} object represents
1406 * a primitive type or void.
1407 * @since 1.1
1408 */
1409 public Object[] getSigners() {
1410 var signers = this.signers;
1411 return signers == null ? null : signers.clone();
1412 }
1413
1414 /**
1415 * Set the signers of this class.
1416 */
1417 void setSigners(Object[] signers) {
1418 if (!isPrimitive() && !isArray()) {
1419 this.signers = signers;
1420 }
1421 }
1422
1423 /**
1424 * If this {@code Class} object represents a local or anonymous
1425 * class within a method, returns a {@link
1426 * java.lang.reflect.Method Method} object representing the
1427 * immediately enclosing method of the underlying class. Returns
1428 * {@code null} otherwise.
3762 *
3763 * <p> If this {@code Class} object represents an interface, the return
3764 * value is an array containing objects representing the uses of interface
3765 * types to specify interfaces directly extended by the interface. The
3766 * order of the objects in the array corresponds to the order of the
3767 * interface types used in the 'extends' clause of the declaration of this
3768 * {@code Class} object.
3769 *
3770 * <p> If this {@code Class} object represents a class or interface whose
3771 * declaration does not explicitly indicate any annotated superinterfaces,
3772 * the return value is an array of length 0.
3773 *
3774 * <p> If this {@code Class} object represents either the {@code Object}
3775 * class, an array type, a primitive type, or void, the return value is an
3776 * array of length 0.
3777 *
3778 * @return an array representing the superinterfaces
3779 * @since 1.8
3780 */
3781 public AnnotatedType[] getAnnotatedInterfaces() {
3782 return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3783 }
3784
3785 private native Class<?> getNestHost0();
3786
3787 /**
3788 * Returns the nest host of the <a href=#nest>nest</a> to which the class
3789 * or interface represented by this {@code Class} object belongs.
3790 * Every class and interface belongs to exactly one nest.
3791 *
3792 * If the nest host of this class or interface has previously
3793 * been determined, then this method returns the nest host.
3794 * If the nest host of this class or interface has
3795 * not previously been determined, then this method determines the nest
3796 * host using the algorithm of JVMS 5.4.4, and returns it.
3797 *
3798 * Often, a class or interface belongs to a nest consisting only of itself,
3799 * in which case this method returns {@code this} to indicate that the class
3800 * or interface is the nest host.
3801 *
3802 * <p>If this {@code Class} object represents a primitive type, an array type,
4103 * @since 17
4104 */
4105 public boolean isSealed() {
4106 if (isArray() || isPrimitive()) {
4107 return false;
4108 }
4109 return getPermittedSubclasses() != null;
4110 }
4111
4112 private native Class<?>[] getPermittedSubclasses0();
4113
4114 /*
4115 * Return the class's major and minor class file version packed into an int.
4116 * The high order 16 bits contain the class's minor version. The low order
4117 * 16 bits contain the class's major version.
4118 *
4119 * If the class is an array type then the class file version of its element
4120 * type is returned. If the class is a primitive type then the latest class
4121 * file major version is returned and zero is returned for the minor version.
4122 */
4123 int getClassFileVersion() {
4124 Class<?> c = isArray() ? elementType() : this;
4125 return c.getClassFileVersion0();
4126 }
4127
4128 private native int getClassFileVersion0();
4129
4130 /**
4131 * Return the access flags as they were in the class's bytecode, including
4132 * the original setting of ACC_SUPER.
4133 *
4134 * If this {@code Class} object represents a primitive type or
4135 * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
4136 * {@code FINAL}.
4137 * If this {@code Class} object represents an array type, return 0.
4138 */
4139 int getClassFileAccessFlags() {
4140 return classFileAccessFlags;
4141 }
4142
|
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.GenericSignatureFormatError;
48 import java.lang.reflect.InvocationTargetException;
49 import java.lang.reflect.Member;
50 import java.lang.reflect.Method;
51 import java.lang.reflect.Modifier;
52 import java.lang.reflect.RecordComponent;
53 import java.lang.reflect.Type;
54 import java.lang.reflect.TypeVariable;
55 import java.lang.constant.Constable;
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.HashSet;
65 import java.util.LinkedHashMap;
66 import java.util.LinkedHashSet;
67 import java.util.List;
68 import java.util.Map;
69 import java.util.Objects;
70 import java.util.Optional;
71 import java.util.Set;
72 import java.util.stream.Collectors;
73
74 import jdk.internal.constant.ConstantUtils;
75 import jdk.internal.javac.PreviewFeature;
76 import jdk.internal.loader.BootLoader;
77 import jdk.internal.loader.BuiltinClassLoader;
78 import jdk.internal.misc.PreviewFeatures;
79 import jdk.internal.misc.Unsafe;
80 import jdk.internal.module.Resources;
81 import jdk.internal.reflect.CallerSensitive;
82 import jdk.internal.reflect.CallerSensitiveAdapter;
83 import jdk.internal.reflect.ConstantPool;
84 import jdk.internal.reflect.Reflection;
85 import jdk.internal.reflect.ReflectionFactory;
86 import jdk.internal.util.ModifiedUtf;
87 import jdk.internal.vm.annotation.AOTRuntimeSetup;
88 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
89 import jdk.internal.vm.annotation.IntrinsicCandidate;
90 import jdk.internal.vm.annotation.Stable;
91
92 import sun.invoke.util.BytecodeDescriptor;
93 import sun.invoke.util.Wrapper;
94 import sun.reflect.generics.factory.CoreReflectionFactory;
95 import sun.reflect.generics.factory.GenericsFactory;
96 import sun.reflect.generics.repository.ClassRepository;
97 import sun.reflect.generics.scope.ClassScope;
98 import sun.reflect.annotation.*;
211 * {@linkplain #getTypeName type name} return results
212 * equal to {@code "HelloWorld"}. The {@linkplain #getSimpleName
213 * simple name} of such an implicitly declared class is {@code "HelloWorld"} and
214 * the {@linkplain #getCanonicalName canonical name} is {@code "HelloWorld"}.
215 *
216 * @param <T> the type of the class modeled by this {@code Class}
217 * object. For example, the type of {@code String.class} is {@code
218 * Class<String>}. Use {@code Class<?>} if the class being modeled is
219 * unknown.
220 *
221 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
222 * @since 1.0
223 */
224 @AOTSafeClassInitializer
225 public final class Class<T> implements java.io.Serializable,
226 GenericDeclaration,
227 Type,
228 AnnotatedElement,
229 TypeDescriptor.OfField<Class<?>>,
230 Constable {
231 private static final int ANNOTATION = 0x00002000;
232 private static final int ENUM = 0x00004000;
233 private static final int SYNTHETIC = 0x00001000;
234
235 private static native void registerNatives();
236 static {
237 runtimeSetup();
238 }
239
240 /// No significant static final fields; [#resetArchivedStates()] handles
241 /// prevents storing [#reflectionFactory] into AOT image.
242 @AOTRuntimeSetup
243 private static void runtimeSetup() {
244 registerNatives();
245 }
246
247 /*
248 * Private constructor. Only the Java Virtual Machine creates Class objects.
249 * This constructor is not used and prevents the default constructor being
250 * generated.
251 */
252 private Class(ClassLoader loader, Class<?> arrayComponentType, char mods, ProtectionDomain pd, boolean isPrim, boolean isIdentity, char flags) {
253 // Initialize final field for classLoader. The initialization value of non-null
254 // prevents future JIT optimizations from assuming this final field is null.
255 // The following assignments are done directly by the VM without calling this constructor.
256 classLoader = loader;
257 componentType = arrayComponentType;
258 modifiers = mods;
259 protectionDomain = pd;
260 primitive = isPrim;
261 identity = isIdentity;
262 classFileAccessFlags = flags;
263 }
264
265 /**
266 * Converts the object to a string. The string representation is the
267 * string "class" or "interface", followed by a space, and then by the
268 * name of the class in the format returned by {@code getName}.
269 * If this {@code Class} object represents a primitive type,
270 * this method returns the name of the primitive type. If
271 * this {@code Class} object represents void this method returns
272 * "void". If this {@code Class} object represents an array type,
273 * this method returns "class " followed by {@code getName}.
274 *
275 * @return a string representation of this {@code Class} object.
276 */
277 public String toString() {
278 String kind = isInterface() ? "interface " : isPrimitive() ? "" : "class ";
279 return kind.concat(getName());
280 }
281
313 *
314 * @since 1.8
315 */
316 public String toGenericString() {
317 if (isPrimitive()) {
318 return toString();
319 } else {
320 StringBuilder sb = new StringBuilder();
321 Class<?> component = this;
322 int arrayDepth = 0;
323
324 if (isArray()) {
325 do {
326 arrayDepth++;
327 component = component.getComponentType();
328 } while (component.isArray());
329 sb.append(component.getName());
330 } else {
331 // Class modifiers are a superset of interface modifiers
332 int modifiers = getModifiers() & Modifier.classModifiers();
333 // Modifier.toString() below mis-interprets SYNCHRONIZED, STRICT, and VOLATILE bits
334 modifiers &= ~(Modifier.SYNCHRONIZED | Modifier.STRICT | Modifier.VOLATILE);
335 if (modifiers != 0) {
336 sb.append(Modifier.toString(modifiers));
337 sb.append(' ');
338 }
339
340 // A class cannot be strictfp and sealed/non-sealed so
341 // it is sufficient to check for sealed-ness after all
342 // modifiers are printed.
343 addSealingInfo(modifiers, sb);
344
345 if (isAnnotation()) {
346 sb.append('@');
347 }
348 if (isInterface()) { // Note: all annotation interfaces are interfaces
349 sb.append("interface");
350 } else {
351 if (isEnum())
352 sb.append("enum");
353 else {
354 if (isValue()) {
355 sb.append("value ");
356 }
357 if (isRecord())
358 sb.append("record");
359 else
360 sb.append("class");
361 }
362 }
363 sb.append(' ');
364 sb.append(getName());
365 }
366
367 TypeVariable<?>[] typeparms = component.getTypeParameters();
368 if (typeparms.length > 0) {
369 sb.append(Arrays.stream(typeparms)
370 .map(Class::typeVarBounds)
371 .collect(Collectors.joining(",", "<", ">")));
372 }
373
374 if (arrayDepth > 0) sb.append("[]".repeat(arrayDepth));
375
376 return sb.toString();
377 }
378 }
379
380 private void addSealingInfo(int modifiers, StringBuilder sb) {
381 // A class can be final XOR sealed XOR non-sealed.
610 *
611 * @jls 12.2 Loading of Classes and Interfaces
612 * @jls 12.3 Linking of Classes and Interfaces
613 * @since 9
614 */
615 public static Class<?> forName(Module module, String name) {
616 Objects.requireNonNull(module);
617 Objects.requireNonNull(name);
618 if (!ModifiedUtf.isValidLengthInConstantPool(name)) {
619 return null;
620 }
621
622 ClassLoader cl = module.getClassLoader();
623 if (cl != null) {
624 return cl.loadClass(module, name);
625 } else {
626 return BootLoader.loadClass(module, name);
627 }
628 }
629
630 /**
631 * {@return {@code true} if this {@code Class} object represents an identity class,
632 * otherwise {@code false}}
633 *
634 * <ul>
635 * <li>
636 * If this {@code Class} object represents an array type this method returns {@code true}.
637 * <li>
638 * If this {@code Class} object represents an interface, a primitive type,
639 * or {@code void} this method returns {@code false}.
640 * <li>
641 * For all other {@code Class} objects, this method returns {@code true} if either
642 * preview features are disabled or {@linkplain Modifier#IDENTITY} is set in the
643 * {@linkplain #getModifiers() class modifiers}.
644 * </ul>
645 * @see AccessFlag#IDENTITY
646 * @since Valhalla
647 */
648 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS, reflective=true)
649 public boolean isIdentity() {
650 return identity;
651 }
652
653 /**
654 * {@return {@code true} if this {@code Class} object represents a value class,
655 * otherwise {@code false}}
656 * <ul>
657 * <li>
658 * If this {@code Class} object represents an array type this method returns {@code false}.
659 * <li>
660 * If this {@code Class} object represents an interface, a primitive type,
661 * or {@code void} this method returns {@code true} only if preview features are enabled.
662 * <li>
663 * For all other {@code Class} objects, this method returns {@code true} only if
664 * preview features are enabled and {@linkplain Modifier#IDENTITY} is not set in the
665 * {@linkplain #getModifiers() class modifiers}.
666 * </ul>
667 * @see AccessFlag#IDENTITY
668 * @since Valhalla
669 */
670 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS, reflective=true)
671 public boolean isValue() {
672 if (!PreviewFeatures.isEnabled()) {
673 return false;
674 }
675 return !isIdentity();
676 }
677
678 /**
679 * {@return the {@code Class} object associated with the
680 * {@linkplain #isPrimitive() primitive type} of the given name}
681 * If the argument is not the name of a primitive type, {@code
682 * null} is returned.
683 *
684 * @param primitiveName the name of the primitive type to find
685 *
686 * @jls 4.2 Primitive Types and Values
687 * @jls 15.8.2 Class Literals
688 * @since 22
689 */
690 public static Class<?> forPrimitiveName(String primitiveName) {
691 return switch(primitiveName) {
692 // Integral types
693 case "int" -> int.class;
694 case "long" -> long.class;
695 case "short" -> short.class;
696 case "char" -> char.class;
697 case "byte" -> byte.class;
1061 *
1062 * @since 9
1063 */
1064 public Module getModule() {
1065 return module;
1066 }
1067
1068 // set by VM
1069 @Stable
1070 private transient Module module;
1071
1072 // Initialized in JVM not by private constructor
1073 // This field is filtered from reflection access, i.e. getDeclaredField
1074 // will throw NoSuchFieldException
1075 private final ClassLoader classLoader;
1076
1077 private transient Object classData; // Set by VM
1078 private transient Object[] signers; // Read by VM, mutable
1079 private final transient char modifiers; // Set by the VM
1080 private final transient char classFileAccessFlags; // Set by the VM
1081 private final transient boolean primitive; // Set by the VM if the Class is a primitive type
1082 private final transient boolean identity; // Set by the VM if the Class is an identity class
1083
1084 // package-private
1085 Object getClassData() {
1086 return classData;
1087 }
1088
1089 /**
1090 * Returns an array of {@code TypeVariable} objects that represent the
1091 * type variables declared by the generic declaration represented by this
1092 * {@code GenericDeclaration} object, in declaration order. Returns an
1093 * array of length 0 if the underlying generic declaration declares no type
1094 * variables.
1095 *
1096 * @return an array of {@code TypeVariable} objects that represent
1097 * the type variables declared by this generic declaration
1098 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
1099 * signature of this generic declaration does not conform to
1100 * the format specified in section {@jvms 4.7.9} of
1101 * <cite>The Java Virtual Machine Specification</cite>
1102 * @since 1.5
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.
3836 *
3837 * <p> If this {@code Class} object represents an interface, the return
3838 * value is an array containing objects representing the uses of interface
3839 * types to specify interfaces directly extended by the interface. The
3840 * order of the objects in the array corresponds to the order of the
3841 * interface types used in the 'extends' clause of the declaration of this
3842 * {@code Class} object.
3843 *
3844 * <p> If this {@code Class} object represents a class or interface whose
3845 * declaration does not explicitly indicate any annotated superinterfaces,
3846 * the return value is an array of length 0.
3847 *
3848 * <p> If this {@code Class} object represents either the {@code Object}
3849 * class, an array type, a primitive type, or void, the return value is an
3850 * array of length 0.
3851 *
3852 * @return an array representing the superinterfaces
3853 * @since 1.8
3854 */
3855 public AnnotatedType[] getAnnotatedInterfaces() {
3856 return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3857 }
3858
3859 private native Class<?> getNestHost0();
3860
3861 /**
3862 * Returns the nest host of the <a href=#nest>nest</a> to which the class
3863 * or interface represented by this {@code Class} object belongs.
3864 * Every class and interface belongs to exactly one nest.
3865 *
3866 * If the nest host of this class or interface has previously
3867 * been determined, then this method returns the nest host.
3868 * If the nest host of this class or interface has
3869 * not previously been determined, then this method determines the nest
3870 * host using the algorithm of JVMS 5.4.4, and returns it.
3871 *
3872 * Often, a class or interface belongs to a nest consisting only of itself,
3873 * in which case this method returns {@code this} to indicate that the class
3874 * or interface is the nest host.
3875 *
3876 * <p>If this {@code Class} object represents a primitive type, an array type,
4177 * @since 17
4178 */
4179 public boolean isSealed() {
4180 if (isArray() || isPrimitive()) {
4181 return false;
4182 }
4183 return getPermittedSubclasses() != null;
4184 }
4185
4186 private native Class<?>[] getPermittedSubclasses0();
4187
4188 /*
4189 * Return the class's major and minor class file version packed into an int.
4190 * The high order 16 bits contain the class's minor version. The low order
4191 * 16 bits contain the class's major version.
4192 *
4193 * If the class is an array type then the class file version of its element
4194 * type is returned. If the class is a primitive type then the latest class
4195 * file major version is returned and zero is returned for the minor version.
4196 */
4197 /* package-private */
4198 int getClassFileVersion() {
4199 Class<?> c = isArray() ? elementType() : this;
4200 return c.getClassFileVersion0();
4201 }
4202
4203 private native int getClassFileVersion0();
4204
4205 /**
4206 * Return the access flags as they were in the class's bytecode, including
4207 * the original setting of ACC_SUPER.
4208 *
4209 * If this {@code Class} object represents a primitive type or
4210 * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
4211 * {@code FINAL}.
4212 * If this {@code Class} object represents an array type, return 0.
4213 */
4214 int getClassFileAccessFlags() {
4215 return classFileAccessFlags;
4216 }
4217
|