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.util.ModifiedUtf;
82 import jdk.internal.vm.annotation.AOTRuntimeSetup;
83 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
84 import jdk.internal.vm.annotation.IntrinsicCandidate;
85 import jdk.internal.vm.annotation.Stable;
86
87 import sun.invoke.util.BytecodeDescriptor;
88 import sun.invoke.util.Wrapper;
89 import sun.reflect.generics.factory.CoreReflectionFactory;
90 import sun.reflect.generics.factory.GenericsFactory;
91 import sun.reflect.generics.repository.ClassRepository;
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
245 // prevents future JIT optimizations from assuming this final field is null.
246 // The following assignments are done directly by the VM without calling this constructor.
247 classLoader = loader;
248 componentType = arrayComponentType;
249 modifiers = mods;
250 protectionDomain = pd;
251 primitive = isPrim;
252 classFileAccessFlags = flags;
253 }
254
255 /**
256 * Converts the object to a string. The string representation is the
257 * string "class" or "interface", followed by a space, and then by the
258 * name of the class in the format returned by {@code getName}.
259 * If this {@code Class} object represents a primitive type,
260 * this method returns the name of the primitive type. If
261 * this {@code Class} object represents void this method returns
262 * "void". If this {@code Class} object represents an array type,
263 * this method returns "class " followed by {@code getName}.
264 *
265 * @return a string representation of this {@code Class} object.
266 */
267 public String toString() {
268 String kind = isInterface() ? "interface " : isPrimitive() ? "" : "class ";
269 return kind.concat(getName());
270 }
271
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.
594 *
595 * @jls 12.2 Loading of Classes and Interfaces
596 * @jls 12.3 Linking of Classes and Interfaces
597 * @since 9
598 */
599 public static Class<?> forName(Module module, String name) {
600 Objects.requireNonNull(module);
601 Objects.requireNonNull(name);
602 if (!ModifiedUtf.isValidLengthInConstantPool(name)) {
603 return null;
604 }
605
606 ClassLoader cl = module.getClassLoader();
607 if (cl != null) {
608 return cl.loadClass(module, name);
609 } else {
610 return BootLoader.loadClass(module, name);
611 }
612 }
613
614 /**
615 * {@return the {@code Class} object associated with the
616 * {@linkplain #isPrimitive() primitive type} of the given name}
617 * If the argument is not the name of a primitive type, {@code
618 * null} is returned.
619 *
620 * @param primitiveName the name of the primitive type to find
621 *
622 * @throws NullPointerException if the argument is {@code null}
623 *
624 * @jls 4.2 Primitive Types and Values
625 * @jls 15.8.2 Class Literals
626 * @since 22
627 */
628 public static Class<?> forPrimitiveName(String primitiveName) {
629 return switch(primitiveName) {
630 // Integral types
631 case "int" -> int.class;
632 case "long" -> long.class;
633 case "short" -> short.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,
4102 * @since 17
4103 */
4104 public boolean isSealed() {
4105 if (isArray() || isPrimitive()) {
4106 return false;
4107 }
4108 return getPermittedSubclasses() != null;
4109 }
4110
4111 private native Class<?>[] getPermittedSubclasses0();
4112
4113 /*
4114 * Return the class's major and minor class file version packed into an int.
4115 * The high order 16 bits contain the class's minor version. The low order
4116 * 16 bits contain the class's major version.
4117 *
4118 * If the class is an array type then the class file version of its element
4119 * type is returned. If the class is a primitive type then the latest class
4120 * file major version is returned and zero is returned for the minor version.
4121 */
4122 int getClassFileVersion() {
4123 Class<?> c = isArray() ? elementType() : this;
4124 return c.getClassFileVersion0();
4125 }
4126
4127 private native int getClassFileVersion0();
4128
4129 /**
4130 * Return the access flags as they were in the class's bytecode, including
4131 * the original setting of ACC_SUPER.
4132 *
4133 * If this {@code Class} object represents a primitive type or
4134 * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
4135 * {@code FINAL}.
4136 * If this {@code Class} object represents an array type, return 0.
4137 */
4138 int getClassFileAccessFlags() {
4139 return classFileAccessFlags;
4140 }
4141
|
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.util.ModifiedUtf;
86 import jdk.internal.vm.annotation.AOTRuntimeSetup;
87 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
88 import jdk.internal.vm.annotation.IntrinsicCandidate;
89 import jdk.internal.vm.annotation.Stable;
90
91 import sun.invoke.util.BytecodeDescriptor;
92 import sun.invoke.util.Wrapper;
93 import sun.reflect.generics.factory.CoreReflectionFactory;
94 import sun.reflect.generics.factory.GenericsFactory;
95 import sun.reflect.generics.repository.ClassRepository;
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, boolean isIdentity, 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.
250 // The following assignments are done directly by the VM without calling this constructor.
251 classLoader = loader;
252 componentType = arrayComponentType;
253 modifiers = mods;
254 protectionDomain = pd;
255 primitive = isPrim;
256 identity = isIdentity;
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 // Modifier.toString() below mis-interprets SYNCHRONIZED, STRICT, and VOLATILE bits
329 modifiers &= ~(Modifier.SYNCHRONIZED | Modifier.STRICT | Modifier.VOLATILE);
330 if (modifiers != 0) {
331 sb.append(Modifier.toString(modifiers));
332 sb.append(' ');
333 }
334
335 // A class cannot be strictfp and sealed/non-sealed so
336 // it is sufficient to check for sealed-ness after all
337 // modifiers are printed.
338 addSealingInfo(modifiers, sb);
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 sb.append(' ');
359 sb.append(getName());
360 }
361
362 TypeVariable<?>[] typeparms = component.getTypeParameters();
363 if (typeparms.length > 0) {
364 sb.append(Arrays.stream(typeparms)
365 .map(Class::typeVarBounds)
366 .collect(Collectors.joining(",", "<", ">")));
367 }
368
369 if (arrayDepth > 0) sb.append("[]".repeat(arrayDepth));
370
371 return sb.toString();
372 }
373 }
374
375 private void addSealingInfo(int modifiers, StringBuilder sb) {
376 // 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 an identity class,
628 * otherwise {@code false}}
629 *
630 * <ul>
631 * <li>
632 * If this {@code Class} object represents an array type this method returns {@code true}.
633 * <li>
634 * If this {@code Class} object represents an interface, a primitive type,
635 * or {@code void} this method returns {@code false}.
636 * <li>
637 * For all other {@code Class} objects, this method returns {@code true} if either
638 * preview features are disabled or {@linkplain Modifier#IDENTITY} is set in the
639 * {@linkplain #getModifiers() class modifiers}.
640 * </ul>
641 * @see AccessFlag#IDENTITY
642 * @since Valhalla
643 */
644 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS, reflective=true)
645 public boolean isIdentity() {
646 return identity;
647 }
648
649 /**
650 * {@return {@code true} if this {@code Class} object represents a value class,
651 * otherwise {@code false}}
652 * <ul>
653 * <li>
654 * If this {@code Class} object represents an array type this method returns {@code false}.
655 * <li>
656 * If this {@code Class} object represents an interface, a primitive type,
657 * or {@code void} this method returns {@code true} only if preview features are enabled.
658 * <li>
659 * For all other {@code Class} objects, this method returns {@code true} only if
660 * preview features are enabled and {@linkplain Modifier#IDENTITY} is not set in the
661 * {@linkplain #getModifiers() class modifiers}.
662 * </ul>
663 * @see AccessFlag#IDENTITY
664 * @since Valhalla
665 */
666 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS, reflective=true)
667 public boolean isValue() {
668 if (!PreviewFeatures.isEnabled()) {
669 return false;
670 }
671 return !isIdentity();
672 }
673
674 /**
675 * {@return the {@code Class} object associated with the
676 * {@linkplain #isPrimitive() primitive type} of the given name}
677 * If the argument is not the name of a primitive type, {@code
678 * null} is returned.
679 *
680 * @param primitiveName the name of the primitive type to find
681 *
682 * @throws NullPointerException if the argument is {@code null}
683 *
684 * @jls 4.2 Primitive Types and Values
685 * @jls 15.8.2 Class Literals
686 * @since 22
687 */
688 public static Class<?> forPrimitiveName(String primitiveName) {
689 return switch(primitiveName) {
690 // Integral types
691 case "int" -> int.class;
692 case "long" -> long.class;
693 case "short" -> short.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,
4176 * @since 17
4177 */
4178 public boolean isSealed() {
4179 if (isArray() || isPrimitive()) {
4180 return false;
4181 }
4182 return getPermittedSubclasses() != null;
4183 }
4184
4185 private native Class<?>[] getPermittedSubclasses0();
4186
4187 /*
4188 * Return the class's major and minor class file version packed into an int.
4189 * The high order 16 bits contain the class's minor version. The low order
4190 * 16 bits contain the class's major version.
4191 *
4192 * If the class is an array type then the class file version of its element
4193 * type is returned. If the class is a primitive type then the latest class
4194 * file major version is returned and zero is returned for the minor version.
4195 */
4196 /* package-private */
4197 int getClassFileVersion() {
4198 Class<?> c = isArray() ? elementType() : this;
4199 return c.getClassFileVersion0();
4200 }
4201
4202 private native int getClassFileVersion0();
4203
4204 /**
4205 * Return the access flags as they were in the class's bytecode, including
4206 * the original setting of ACC_SUPER.
4207 *
4208 * If this {@code Class} object represents a primitive type or
4209 * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
4210 * {@code FINAL}.
4211 * If this {@code Class} object represents an array type, return 0.
4212 */
4213 int getClassFileAccessFlags() {
4214 return classFileAccessFlags;
4215 }
4216
|