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.module.ModuleReader;
34 import java.lang.ref.SoftReference;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.ObjectStreamField;
38 import java.lang.reflect.AnnotatedElement;
39 import java.lang.reflect.AnnotatedType;
40 import java.lang.reflect.AccessFlag;
41 import java.lang.reflect.Array;
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.Proxy;
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.AccessController;
58 import java.security.PrivilegedAction;
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.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.vm.annotation.ForceInline;
83 import jdk.internal.vm.annotation.IntrinsicCandidate;
84 import sun.invoke.util.Wrapper;
85 import sun.reflect.generics.factory.CoreReflectionFactory;
86 import sun.reflect.generics.factory.GenericsFactory;
87 import sun.reflect.generics.repository.ClassRepository;
88 import sun.reflect.generics.repository.MethodRepository;
89 import sun.reflect.generics.repository.ConstructorRepository;
90 import sun.reflect.generics.scope.ClassScope;
91 import sun.security.util.SecurityConstants;
92 import sun.reflect.annotation.*;
93 import sun.reflect.misc.ReflectUtil;
94
95 /**
96 * Instances of the class {@code Class} represent classes and
97 * interfaces in a running Java application. An enum class and a record
98 * class are kinds of class; an annotation interface is a kind of
99 * interface. Every array also belongs to a class that is reflected as
100 * a {@code Class} object that is shared by all arrays with the same
101 * element type and number of dimensions. The primitive Java types
184 * A hidden class or interface is never an array class, but may be
185 * the element type of an array. In all other respects, the fact that
186 * a class or interface is hidden has no bearing on the characteristics
187 * exposed by the methods of class {@code Class}.
188 *
189 * @param <T> the type of the class modeled by this {@code Class}
190 * object. For example, the type of {@code String.class} is {@code
191 * Class<String>}. Use {@code Class<?>} if the class being modeled is
192 * unknown.
193 *
194 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
195 * @since 1.0
196 * @jls 15.8.2 Class Literals
197 */
198 public final class Class<T> implements java.io.Serializable,
199 GenericDeclaration,
200 Type,
201 AnnotatedElement,
202 TypeDescriptor.OfField<Class<?>>,
203 Constable {
204 private static final int ANNOTATION= 0x00002000;
205 private static final int ENUM = 0x00004000;
206 private static final int SYNTHETIC = 0x00001000;
207
208 private static native void registerNatives();
209 static {
210 registerNatives();
211 }
212
213 /*
214 * Private constructor. Only the Java Virtual Machine creates Class objects.
215 * This constructor is not used and prevents the default constructor being
216 * generated.
217 */
218 private Class(ClassLoader loader, Class<?> arrayComponentType) {
219 // Initialize final field for classLoader. The initialization value of non-null
220 // prevents future JIT optimizations from assuming this final field is null.
221 classLoader = loader;
222 componentType = arrayComponentType;
223 }
224
225 /**
226 * Converts the object to a string. The string representation is the
227 * string "class" or "interface", followed by a space, and then by the
228 * name of the class in the format returned by {@code getName}.
229 * If this {@code Class} object represents a primitive type,
230 * this method returns the name of the primitive type. If
231 * this {@code Class} object represents void this method returns
232 * "void". If this {@code Class} object represents an array type,
233 * this method returns "class " followed by {@code getName}.
234 *
235 * @return a string representation of this {@code Class} object.
236 */
237 public String toString() {
238 String kind = isInterface() ? "interface " : isPrimitive() ? "" : "class ";
239 return kind.concat(getName());
240 }
241
242 /**
243 * Returns a string describing this {@code Class}, including
244 * information about modifiers and type parameters.
245 *
246 * The string is formatted as a list of type modifiers, if any,
247 * followed by the kind of type (empty string for primitive types
248 * and {@code class}, {@code enum}, {@code interface},
249 * {@code @interface}, or {@code record} as appropriate), followed
250 * by the type's name, followed by an angle-bracketed
251 * comma-separated list of the type's type parameters, if any,
252 * including informative bounds on the type parameters, if any.
253 *
254 * A space is used to separate modifiers from one another and to
255 * separate any modifiers from the kind of type. The modifiers
256 * occur in canonical order. If there are no type parameters, the
257 * type parameter list is elided.
258 *
259 * For an array type, the string starts with the type name,
272 *
273 * @since 1.8
274 */
275 public String toGenericString() {
276 if (isPrimitive()) {
277 return toString();
278 } else {
279 StringBuilder sb = new StringBuilder();
280 Class<?> component = this;
281 int arrayDepth = 0;
282
283 if (isArray()) {
284 do {
285 arrayDepth++;
286 component = component.getComponentType();
287 } while (component.isArray());
288 sb.append(component.getName());
289 } else {
290 // Class modifiers are a superset of interface modifiers
291 int modifiers = getModifiers() & Modifier.classModifiers();
292 if (modifiers != 0) {
293 sb.append(Modifier.toString(modifiers));
294 sb.append(' ');
295 }
296
297 if (isAnnotation()) {
298 sb.append('@');
299 }
300 if (isInterface()) { // Note: all annotation interfaces are interfaces
301 sb.append("interface");
302 } else {
303 if (isEnum())
304 sb.append("enum");
305 else if (isRecord())
306 sb.append("record");
307 else
308 sb.append("class");
309 }
310 sb.append(' ');
311 sb.append(getName());
312 }
313
314 TypeVariable<?>[] typeparms = component.getTypeParameters();
315 if (typeparms.length > 0) {
316 sb.append(Arrays.stream(typeparms)
317 .map(Class::typeVarBounds)
318 .collect(Collectors.joining(",", "<", ">")));
319 }
482 throws ClassNotFoundException
483 {
484 @SuppressWarnings("removal")
485 SecurityManager sm = System.getSecurityManager();
486 if (sm != null) {
487 // Reflective call to get caller class is only needed if a security manager
488 // is present. Avoid the overhead of making this call otherwise.
489 if (loader == null) {
490 ClassLoader ccl = ClassLoader.getClassLoader(caller);
491 if (ccl != null) {
492 sm.checkPermission(
493 SecurityConstants.GET_CLASSLOADER_PERMISSION);
494 }
495 }
496 }
497 return forName0(name, initialize, loader, caller);
498 }
499
500 /** Called after security check for system loader access checks have been made. */
501 private static native Class<?> forName0(String name, boolean initialize,
502 ClassLoader loader,
503 Class<?> caller)
504 throws ClassNotFoundException;
505
506
507 /**
508 * Returns the {@code Class} with the given <a href="ClassLoader.html#binary-name">
509 * binary name</a> in the given module.
510 *
511 * <p> This method attempts to locate and load the class or interface.
512 * It does not link the class, and does not run the class initializer.
513 * If the class is not found, this method returns {@code null}. </p>
514 *
515 * <p> If the class loader of the given module defines other modules and
516 * the given name is a class defined in a different module, this method
517 * returns {@code null} after the class is loaded. </p>
518 *
519 * <p> This method does not check whether the requested class is
520 * accessible to its caller. </p>
521 *
522 * @apiNote
523 * This method returns {@code null} on failure rather than
572 SecurityManager sm = System.getSecurityManager();
573 if (sm != null) {
574 if (caller != null && caller.getModule() != module) {
575 // if caller is null, Class.forName is the last java frame on the stack.
576 // java.base has all permissions
577 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
578 }
579 PrivilegedAction<ClassLoader> pa = module::getClassLoader;
580 cl = AccessController.doPrivileged(pa);
581 } else {
582 cl = module.getClassLoader();
583 }
584
585 if (cl != null) {
586 return cl.loadClass(module, name);
587 } else {
588 return BootLoader.loadClass(module, name);
589 }
590 }
591
592 /**
593 * Creates a new instance of the class represented by this {@code Class}
594 * object. The class is instantiated as if by a {@code new}
595 * expression with an empty argument list. The class is initialized if it
596 * has not already been initialized.
597 *
598 * @deprecated This method propagates any exception thrown by the
599 * nullary constructor, including a checked exception. Use of
600 * this method effectively bypasses the compile-time exception
601 * checking that would otherwise be performed by the compiler.
602 * The {@link
603 * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
604 * Constructor.newInstance} method avoids this problem by wrapping
605 * any exception thrown by the constructor in a (checked) {@link
606 * java.lang.reflect.InvocationTargetException}.
607 *
608 * <p>The call
609 *
610 * <pre>{@code
611 * clazz.newInstance()
1279 * If this class does not represent an array class, then this method returns
1280 * {@code null}.
1281 */
1282 private Class<?> elementType() {
1283 if (!isArray()) return null;
1284
1285 Class<?> c = this;
1286 while (c.isArray()) {
1287 c = c.getComponentType();
1288 }
1289 return c;
1290 }
1291
1292 /**
1293 * Returns the Java language modifiers for this class or interface, encoded
1294 * in an integer. The modifiers consist of the Java Virtual Machine's
1295 * constants for {@code public}, {@code protected},
1296 * {@code private}, {@code final}, {@code static},
1297 * {@code abstract} and {@code interface}; they should be decoded
1298 * using the methods of class {@code Modifier}.
1299 *
1300 * <p> If the underlying class is an array class:
1301 * <ul>
1302 * <li> its {@code public}, {@code private} and {@code protected}
1303 * modifiers are the same as those of its component type
1304 * <li> its {@code abstract} and {@code final} modifiers are always
1305 * {@code true}
1306 * <li> its interface modifier is always {@code false}, even when
1307 * the component type is an interface
1308 * </ul>
1309 * If this {@code Class} object represents a primitive type or
1310 * void, its {@code public}, {@code abstract}, and {@code final}
1311 * modifiers are always {@code true}.
1312 * For {@code Class} objects representing void, primitive types, and
1313 * arrays, the values of other modifiers are {@code false} other
1314 * than as specified above.
1315 *
1316 * <p> The modifier encodings are defined in section {@jvms 4.1}
1317 * of <cite>The Java Virtual Machine Specification</cite>.
1318 *
1319 * @return the {@code int} representing the modifiers for this class
1320 * @see java.lang.reflect.Modifier
1321 * @see #accessFlags()
1322 * @see <a
1323 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1324 * programming language and JVM modeling in core reflection</a>
1325 * @since 1.1
1326 * @jls 8.1.1 Class Modifiers
1327 * @jls 9.1.1. Interface Modifiers
1328 * @jvms 4.1 The {@code ClassFile} Structure
1329 */
1330 @IntrinsicCandidate
1331 public native int getModifiers();
1332
1333 /**
1334 * {@return an unmodifiable set of the {@linkplain AccessFlag access
1335 * flags} for this class, possibly empty}
1336 *
1337 * <p> If the underlying class is an array class:
1338 * <ul>
1339 * <li> its {@code PUBLIC}, {@code PRIVATE} and {@code PROTECTED}
1340 * access flags are the same as those of its component type
1341 * <li> its {@code ABSTRACT} and {@code FINAL} flags are present
1342 * <li> its {@code INTERFACE} flag is absent, even when the
1343 * component type is an interface
1344 * </ul>
1345 * If this {@code Class} object represents a primitive type or
1346 * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
1347 * {@code FINAL}.
1348 * For {@code Class} objects representing void, primitive types, and
1349 * arrays, access flags are absent other than as specified above.
1350 *
1351 * @see #getModifiers()
1352 * @jvms 4.1 The ClassFile Structure
1353 * @jvms 4.7.6 The InnerClasses Attribute
1354 * @since 20
1355 */
1356 public Set<AccessFlag> accessFlags() {
1357 // Location.CLASS allows SUPER and AccessFlag.MODULE which
1358 // INNER_CLASS forbids. INNER_CLASS allows PRIVATE, PROTECTED,
1359 // and STATIC, which are not allowed on Location.CLASS.
1360 // Use getClassAccessFlagsRaw to expose SUPER status.
1361 var location = (isMemberClass() || isLocalClass() ||
1362 isAnonymousClass() || isArray()) ?
1363 AccessFlag.Location.INNER_CLASS :
1364 AccessFlag.Location.CLASS;
1365 return AccessFlag.maskToAccessFlags((location == AccessFlag.Location.CLASS) ?
1366 getClassAccessFlagsRaw() :
1367 getModifiers(),
1368 location);
1369 }
1370
1371 /**
1372 * Gets the signers of this class.
1373 *
1374 * @return the signers of this class, or null if there are no signers. In
1375 * particular, this method returns null if this {@code Class} object represents
1376 * a primitive type or void.
1377 * @since 1.1
1378 */
1379 public native Object[] getSigners();
1380
1381
1382 /**
1383 * Set the signers of this class.
1384 */
1385 native void setSigners(Object[] signers);
1386
1387
1388 /**
1389 * If this {@code Class} object represents a local or anonymous
1390 * class within a method, returns a {@link
1391 * java.lang.reflect.Method Method} object representing the
1392 * immediately enclosing method of the underlying class. Returns
1393 * {@code null} otherwise.
1394 *
1395 * In particular, this method returns {@code null} if the underlying
1396 * class is a local or anonymous class immediately enclosed by a class or
1397 * interface declaration, instance initializer or static initializer.
1398 *
1399 * @return the immediately enclosing method of the underlying class, if
1400 * that class is a local or anonymous class; otherwise {@code null}.
1401 *
1402 * @throws SecurityException
1403 * If a security manager, <i>s</i>, is present and any of the
1404 * following conditions is met:
1405 *
1406 * <ul>
1407 *
1508 // the immediately enclosing method or constructor's
1509 // descriptor (null iff name is).
1510 String descriptor = (String)enclosingInfo[2];
1511 assert((name != null && descriptor != null) || name == descriptor);
1512 } catch (ClassCastException cce) {
1513 throw new InternalError("Invalid type in enclosing method information", cce);
1514 }
1515 }
1516
1517 EnclosingMethodInfo(Object[] enclosingInfo) {
1518 validate(enclosingInfo);
1519 this.enclosingClass = (Class<?>)enclosingInfo[0];
1520 this.name = (String)enclosingInfo[1];
1521 this.descriptor = (String)enclosingInfo[2];
1522 }
1523
1524 boolean isPartial() {
1525 return enclosingClass == null || name == null || descriptor == null;
1526 }
1527
1528 boolean isConstructor() { return !isPartial() && ConstantDescs.INIT_NAME.equals(name); }
1529
1530 boolean isMethod() { return !isPartial() && !isConstructor() && !ConstantDescs.CLASS_INIT_NAME.equals(name); }
1531
1532 Class<?> getEnclosingClass() { return enclosingClass; }
1533
1534 String getName() { return name; }
1535
1536 String getDescriptor() { return descriptor; }
1537
1538 }
1539
1540 private static Class<?> toClass(Type o) {
1541 if (o instanceof GenericArrayType)
1542 return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
1543 0)
1544 .getClass();
1545 return (Class<?>)o;
1546 }
1547
1548 /**
1549 * If this {@code Class} object represents a local or anonymous
1550 * class within a constructor, returns a {@link
1569 * s.checkPermission} method with
1570 * {@code RuntimePermission("accessDeclaredMembers")}
1571 * denies access to the constructors within the enclosing class
1572 *
1573 * <li> the caller's class loader is not the same as or an
1574 * ancestor of the class loader for the enclosing class and
1575 * invocation of {@link SecurityManager#checkPackageAccess
1576 * s.checkPackageAccess()} denies access to the package
1577 * of the enclosing class
1578 *
1579 * </ul>
1580 * @since 1.5
1581 */
1582 @CallerSensitive
1583 public Constructor<?> getEnclosingConstructor() throws SecurityException {
1584 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1585
1586 if (enclosingInfo == null)
1587 return null;
1588 else {
1589 if (!enclosingInfo.isConstructor())
1590 return null;
1591
1592 ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
1593 getFactory());
1594 Type [] parameterTypes = typeInfo.getParameterTypes();
1595 Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1596
1597 // Convert Types to Classes; returned types *should*
1598 // be class objects since the methodDescriptor's used
1599 // don't have generics information
1600 for(int i = 0; i < parameterClasses.length; i++)
1601 parameterClasses[i] = toClass(parameterTypes[i]);
1602
1603 // Perform access check
1604 final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1605 @SuppressWarnings("removal")
1606 SecurityManager sm = System.getSecurityManager();
1607 if (sm != null) {
1608 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED,
1609 Reflection.getCallerClass(), true);
1749 simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1750 }
1751 return simpleName;
1752 }
1753
1754 /**
1755 * Return an informative string for the name of this class or interface.
1756 *
1757 * @return an informative string for the name of this class or interface
1758 * @since 1.8
1759 */
1760 public String getTypeName() {
1761 if (isArray()) {
1762 try {
1763 Class<?> cl = this;
1764 int dimensions = 0;
1765 do {
1766 dimensions++;
1767 cl = cl.getComponentType();
1768 } while (cl.isArray());
1769 return cl.getName().concat("[]".repeat(dimensions));
1770 } catch (Throwable e) { /*FALLTHRU*/ }
1771 }
1772 return getName();
1773 }
1774
1775 /**
1776 * Returns the canonical name of the underlying class as
1777 * defined by <cite>The Java Language Specification</cite>.
1778 * Returns {@code null} if the underlying class does not have a canonical
1779 * name. Classes without canonical names include:
1780 * <ul>
1781 * <li>a {@linkplain #isLocalClass() local class}
1782 * <li>a {@linkplain #isAnonymousClass() anonymous class}
1783 * <li>a {@linkplain #isHidden() hidden class}
1784 * <li>an array whose component type does not have a canonical name</li>
1785 * </ul>
1786 *
1787 * The canonical name for a primitive class is the keyword for the
1788 * corresponding primitive type ({@code byte}, {@code short},
1789 * {@code char}, {@code int}, and so on).
1790 *
1791 * <p>An array type has a canonical name if and only if its
1792 * component type has a canonical name. When an array type has a
3669 /* includeStatic */ false));
3670 }
3671
3672 return res;
3673 }
3674
3675 // Returns a "root" Constructor object. This Constructor object must NOT
3676 // be propagated to the outside world, but must instead be copied
3677 // via ReflectionFactory.copyConstructor.
3678 private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3679 int which) throws NoSuchMethodException
3680 {
3681 ReflectionFactory fact = getReflectionFactory();
3682 Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3683 for (Constructor<T> constructor : constructors) {
3684 if (arrayContentsEq(parameterTypes,
3685 fact.getExecutableSharedParameterTypes(constructor))) {
3686 return constructor;
3687 }
3688 }
3689 throw new NoSuchMethodException(methodToString("<init>", parameterTypes));
3690 }
3691
3692 //
3693 // Other helpers and base implementation
3694 //
3695
3696 private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3697 if (a1 == null) {
3698 return a2 == null || a2.length == 0;
3699 }
3700
3701 if (a2 == null) {
3702 return a1.length == 0;
3703 }
3704
3705 if (a1.length != a2.length) {
3706 return false;
3707 }
3708
3709 for (int i = 0; i < a1.length; i++) {
3974 }
3975 return directory;
3976 }
3977 private transient volatile Map<String, T> enumConstantDirectory;
3978
3979 /**
3980 * Casts an object to the class or interface represented
3981 * by this {@code Class} object.
3982 *
3983 * @param obj the object to be cast
3984 * @return the object after casting, or null if obj is null
3985 *
3986 * @throws ClassCastException if the object is not
3987 * null and is not assignable to the type T.
3988 *
3989 * @since 1.5
3990 */
3991 @SuppressWarnings("unchecked")
3992 @IntrinsicCandidate
3993 public T cast(Object obj) {
3994 if (obj != null && !isInstance(obj))
3995 throw new ClassCastException(cannotCastMsg(obj));
3996 return (T) obj;
3997 }
3998
3999 private String cannotCastMsg(Object obj) {
4000 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
4001 }
4002
4003 /**
4004 * Casts this {@code Class} object to represent a subclass of the class
4005 * represented by the specified class object. Checks that the cast
4006 * is valid, and throws a {@code ClassCastException} if it is not. If
4007 * this method succeeds, it always returns a reference to this {@code Class} object.
4008 *
4009 * <p>This method is useful when a client needs to "narrow" the type of
4010 * a {@code Class} object to pass it to an API that restricts the
4011 * {@code Class} objects that it is willing to accept. A cast would
4012 * generate a compile-time warning, as the correctness of the cast
4013 * could not be checked at runtime (because generic types are implemented
4269 *
4270 * <p> If this {@code Class} object represents an interface, the return
4271 * value is an array containing objects representing the uses of interface
4272 * types to specify interfaces directly extended by the interface. The
4273 * order of the objects in the array corresponds to the order of the
4274 * interface types used in the 'extends' clause of the declaration of this
4275 * {@code Class} object.
4276 *
4277 * <p> If this {@code Class} object represents a class or interface whose
4278 * declaration does not explicitly indicate any annotated superinterfaces,
4279 * the return value is an array of length 0.
4280 *
4281 * <p> If this {@code Class} object represents either the {@code Object}
4282 * class, an array type, a primitive type, or void, the return value is an
4283 * array of length 0.
4284 *
4285 * @return an array representing the superinterfaces
4286 * @since 1.8
4287 */
4288 public AnnotatedType[] getAnnotatedInterfaces() {
4289 return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
4290 }
4291
4292 private native Class<?> getNestHost0();
4293
4294 /**
4295 * Returns the nest host of the <a href=#nest>nest</a> to which the class
4296 * or interface represented by this {@code Class} object belongs.
4297 * Every class and interface belongs to exactly one nest.
4298 *
4299 * If the nest host of this class or interface has previously
4300 * been determined, then this method returns the nest host.
4301 * If the nest host of this class or interface has
4302 * not previously been determined, then this method determines the nest
4303 * host using the algorithm of JVMS 5.4.4, and returns it.
4304 *
4305 * Often, a class or interface belongs to a nest consisting only of itself,
4306 * in which case this method returns {@code this} to indicate that the class
4307 * or interface is the nest host.
4308 *
4309 * <p>If this {@code Class} object represents a primitive type, an array type,
4484 * {@code void}, then the result is a field descriptor string which
4485 * is a one-letter code corresponding to a primitive type or {@code void}
4486 * ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}).
4487 *
4488 * @apiNote
4489 * This is not a strict inverse of {@link #forName};
4490 * distinct classes which share a common name but have different class loaders
4491 * will have identical descriptor strings.
4492 *
4493 * @return the descriptor string for this {@code Class} object
4494 * @jvms 4.3.2 Field Descriptors
4495 * @since 12
4496 */
4497 @Override
4498 public String descriptorString() {
4499 if (isPrimitive())
4500 return Wrapper.forPrimitiveType(this).basicTypeString();
4501
4502 if (isArray()) {
4503 return "[" + componentType.descriptorString();
4504 } else if (isHidden()) {
4505 String name = getName();
4506 int index = name.indexOf('/');
4507 return new StringBuilder(name.length() + 2)
4508 .append('L')
4509 .append(name.substring(0, index).replace('.', '/'))
4510 .append('.')
4511 .append(name, index + 1, name.length())
4512 .append(';')
4513 .toString();
4514 } else {
4515 String name = getName().replace('.', '/');
4516 return new StringBuilder(name.length() + 2)
4517 .append('L')
4518 .append(name)
4519 .append(';')
4520 .toString();
4521 }
4522 }
4523
4524 /**
4525 * Returns the component type of this {@code Class}, if it describes
4526 * an array type, or {@code null} otherwise.
4527 *
4528 * @implSpec
4529 * Equivalent to {@link Class#getComponentType()}.
4530 *
4531 * @return a {@code Class} describing the component type, or {@code null}
4532 * if this {@code Class} does not describe an array type
4533 * @since 12
4534 */
4535 @Override
4536 public Class<?> componentType() {
4537 return isArray() ? componentType : null;
4675 * @since 17
4676 */
4677 public boolean isSealed() {
4678 if (isArray() || isPrimitive()) {
4679 return false;
4680 }
4681 return getPermittedSubclasses() != null;
4682 }
4683
4684 private native Class<?>[] getPermittedSubclasses0();
4685
4686 /*
4687 * Return the class's major and minor class file version packed into an int.
4688 * The high order 16 bits contain the class's minor version. The low order
4689 * 16 bits contain the class's major version.
4690 *
4691 * If the class is an array type then the class file version of its element
4692 * type is returned. If the class is a primitive type then the latest class
4693 * file major version is returned and zero is returned for the minor version.
4694 */
4695 private int getClassFileVersion() {
4696 Class<?> c = isArray() ? elementType() : this;
4697 return c.getClassFileVersion0();
4698 }
4699
4700 private native int getClassFileVersion0();
4701
4702 /*
4703 * Return the access flags as they were in the class's bytecode, including
4704 * the original setting of ACC_SUPER.
4705 *
4706 * If the class is an array type then the access flags of the element type is
4707 * returned. If the class is a primitive then ACC_ABSTRACT | ACC_FINAL | ACC_PUBLIC.
4708 */
4709 private int getClassAccessFlagsRaw() {
4710 Class<?> c = isArray() ? elementType() : this;
4711 return c.getClassAccessFlagsRaw0();
4712 }
4713
4714 private native int getClassAccessFlagsRaw0();
4715 }
|
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.module.ModuleReader;
34 import java.lang.ref.SoftReference;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.ObjectStreamField;
38 import java.lang.reflect.AnnotatedElement;
39 import java.lang.reflect.AnnotatedType;
40 import java.lang.reflect.AccessFlag;
41 import java.lang.reflect.Array;
42 import java.lang.reflect.ClassFileFormatVersion;
43 import java.lang.reflect.Constructor;
44 import java.lang.reflect.Executable;
45 import java.lang.reflect.Field;
46 import java.lang.reflect.GenericArrayType;
47 import java.lang.reflect.GenericDeclaration;
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.Proxy;
53 import java.lang.reflect.RecordComponent;
54 import java.lang.reflect.Type;
55 import java.lang.reflect.TypeVariable;
56 import java.lang.constant.Constable;
57 import java.net.URL;
58 import java.security.AccessController;
59 import java.security.PrivilegedAction;
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.javac.PreviewFeature;
75 import jdk.internal.loader.BootLoader;
76 import jdk.internal.loader.BuiltinClassLoader;
77 import jdk.internal.misc.Unsafe;
78 import jdk.internal.module.Resources;
79 import jdk.internal.reflect.CallerSensitive;
80 import jdk.internal.reflect.CallerSensitiveAdapter;
81 import jdk.internal.reflect.ConstantPool;
82 import jdk.internal.reflect.Reflection;
83 import jdk.internal.reflect.ReflectionFactory;
84 import jdk.internal.value.PrimitiveClass;
85 import jdk.internal.vm.annotation.ForceInline;
86 import jdk.internal.vm.annotation.IntrinsicCandidate;
87 import sun.invoke.util.Wrapper;
88 import sun.reflect.generics.factory.CoreReflectionFactory;
89 import sun.reflect.generics.factory.GenericsFactory;
90 import sun.reflect.generics.repository.ClassRepository;
91 import sun.reflect.generics.repository.MethodRepository;
92 import sun.reflect.generics.repository.ConstructorRepository;
93 import sun.reflect.generics.scope.ClassScope;
94 import sun.security.util.SecurityConstants;
95 import sun.reflect.annotation.*;
96 import sun.reflect.misc.ReflectUtil;
97
98 /**
99 * Instances of the class {@code Class} represent classes and
100 * interfaces in a running Java application. An enum class and a record
101 * class are kinds of class; an annotation interface is a kind of
102 * interface. Every array also belongs to a class that is reflected as
103 * a {@code Class} object that is shared by all arrays with the same
104 * element type and number of dimensions. The primitive Java types
187 * A hidden class or interface is never an array class, but may be
188 * the element type of an array. In all other respects, the fact that
189 * a class or interface is hidden has no bearing on the characteristics
190 * exposed by the methods of class {@code Class}.
191 *
192 * @param <T> the type of the class modeled by this {@code Class}
193 * object. For example, the type of {@code String.class} is {@code
194 * Class<String>}. Use {@code Class<?>} if the class being modeled is
195 * unknown.
196 *
197 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
198 * @since 1.0
199 * @jls 15.8.2 Class Literals
200 */
201 public final class Class<T> implements java.io.Serializable,
202 GenericDeclaration,
203 Type,
204 AnnotatedElement,
205 TypeDescriptor.OfField<Class<?>>,
206 Constable {
207 private static final int ANNOTATION = 0x00002000;
208 private static final int ENUM = 0x00004000;
209 private static final int SYNTHETIC = 0x00001000;
210
211 private static native void registerNatives();
212 static {
213 registerNatives();
214 }
215
216 /*
217 * Private constructor. Only the Java Virtual Machine creates Class objects.
218 * This constructor is not used and prevents the default constructor being
219 * generated.
220 */
221 private Class(ClassLoader loader, Class<?> arrayComponentType) {
222 // Initialize final field for classLoader. The initialization value of non-null
223 // prevents future JIT optimizations from assuming this final field is null.
224 classLoader = loader;
225 componentType = arrayComponentType;
226 }
227
228 /**
229 * Converts the object to a string. The string representation is the
230 * string "class" or "interface", followed by a space, and then by the
231 * name of the class in the format returned by {@code getName}.
232 * If this {@code Class} object represents a primitive type,
233 * this method returns the name of the primitive type. If
234 * this {@code Class} object represents void this method returns
235 * "void". If this {@code Class} object represents an array type,
236 * this method returns "class " followed by {@code getName}.
237 *
238 * @return a string representation of this {@code Class} object.
239 */
240 public String toString() {
241 String s = getName();
242 if (isPrimitive()) {
243 return s;
244 }
245 // Avoid invokedynamic based String concat, might be not available
246 // Prepend type of class
247 s = (isInterface() ? "interface " : "class ").concat(s);
248 if (isValue()) {
249 // prepend value class type
250 s = (isPrimitiveClass() ? "primitive " : "value ").concat(s);
251 if (isPrimitiveClass() && isPrimaryType()) {
252 // Append .ref
253 s = s.concat(".ref");
254 }
255 }
256 return s;
257 }
258
259 /**
260 * Returns a string describing this {@code Class}, including
261 * information about modifiers and type parameters.
262 *
263 * The string is formatted as a list of type modifiers, if any,
264 * followed by the kind of type (empty string for primitive types
265 * and {@code class}, {@code enum}, {@code interface},
266 * {@code @interface}, or {@code record} as appropriate), followed
267 * by the type's name, followed by an angle-bracketed
268 * comma-separated list of the type's type parameters, if any,
269 * including informative bounds on the type parameters, if any.
270 *
271 * A space is used to separate modifiers from one another and to
272 * separate any modifiers from the kind of type. The modifiers
273 * occur in canonical order. If there are no type parameters, the
274 * type parameter list is elided.
275 *
276 * For an array type, the string starts with the type name,
289 *
290 * @since 1.8
291 */
292 public String toGenericString() {
293 if (isPrimitive()) {
294 return toString();
295 } else {
296 StringBuilder sb = new StringBuilder();
297 Class<?> component = this;
298 int arrayDepth = 0;
299
300 if (isArray()) {
301 do {
302 arrayDepth++;
303 component = component.getComponentType();
304 } while (component.isArray());
305 sb.append(component.getName());
306 } else {
307 // Class modifiers are a superset of interface modifiers
308 int modifiers = getModifiers() & Modifier.classModifiers();
309 // Modifier.toString() below mis-interprets SYNCHRONIZED, STRICT, and VOLATILE bits
310 modifiers &= ~(Modifier.SYNCHRONIZED | Modifier.STRICT | Modifier.VOLATILE);
311 if (modifiers != 0) {
312 sb.append(Modifier.toString(modifiers));
313 sb.append(' ');
314 }
315
316 if (isAnnotation()) {
317 sb.append('@');
318 }
319 if (isValue()) {
320 sb.append(isPrimitiveClass() ? "primitive " : "value ");
321 }
322 if (isInterface()) { // Note: all annotation interfaces are interfaces
323 sb.append("interface");
324 } else {
325 if (isEnum())
326 sb.append("enum");
327 else if (isRecord())
328 sb.append("record");
329 else
330 sb.append("class");
331 }
332 sb.append(' ');
333 sb.append(getName());
334 }
335
336 TypeVariable<?>[] typeparms = component.getTypeParameters();
337 if (typeparms.length > 0) {
338 sb.append(Arrays.stream(typeparms)
339 .map(Class::typeVarBounds)
340 .collect(Collectors.joining(",", "<", ">")));
341 }
504 throws ClassNotFoundException
505 {
506 @SuppressWarnings("removal")
507 SecurityManager sm = System.getSecurityManager();
508 if (sm != null) {
509 // Reflective call to get caller class is only needed if a security manager
510 // is present. Avoid the overhead of making this call otherwise.
511 if (loader == null) {
512 ClassLoader ccl = ClassLoader.getClassLoader(caller);
513 if (ccl != null) {
514 sm.checkPermission(
515 SecurityConstants.GET_CLASSLOADER_PERMISSION);
516 }
517 }
518 }
519 return forName0(name, initialize, loader, caller);
520 }
521
522 /** Called after security check for system loader access checks have been made. */
523 private static native Class<?> forName0(String name, boolean initialize,
524 ClassLoader loader,
525 Class<?> caller)
526 throws ClassNotFoundException;
527
528
529 /**
530 * Returns the {@code Class} with the given <a href="ClassLoader.html#binary-name">
531 * binary name</a> in the given module.
532 *
533 * <p> This method attempts to locate and load the class or interface.
534 * It does not link the class, and does not run the class initializer.
535 * If the class is not found, this method returns {@code null}. </p>
536 *
537 * <p> If the class loader of the given module defines other modules and
538 * the given name is a class defined in a different module, this method
539 * returns {@code null} after the class is loaded. </p>
540 *
541 * <p> This method does not check whether the requested class is
542 * accessible to its caller. </p>
543 *
544 * @apiNote
545 * This method returns {@code null} on failure rather than
594 SecurityManager sm = System.getSecurityManager();
595 if (sm != null) {
596 if (caller != null && caller.getModule() != module) {
597 // if caller is null, Class.forName is the last java frame on the stack.
598 // java.base has all permissions
599 sm.checkPermission(SecurityConstants.GET_CLASSLOADER_PERMISSION);
600 }
601 PrivilegedAction<ClassLoader> pa = module::getClassLoader;
602 cl = AccessController.doPrivileged(pa);
603 } else {
604 cl = module.getClassLoader();
605 }
606
607 if (cl != null) {
608 return cl.loadClass(module, name);
609 } else {
610 return BootLoader.loadClass(module, name);
611 }
612 }
613
614 // set by VM if this class is an exotic type such as primitive class
615 // otherwise, these two fields are null
616 private transient Class<T> primaryType;
617 private transient Class<T> secondaryType;
618
619 /**
620 * Returns {@code true} if this class is a primitive class.
621 * <p>
622 * Each primitive class has a {@linkplain #isPrimaryType() primary type}
623 * representing the <em>primitive reference type</em> and a
624 * {@linkplain #isPrimitiveValueType() secondary type} representing
625 * the <em>primitive value type</em>. The primitive reference type
626 * and primitive value type can be obtained by calling the
627 * {@link #asPrimaryType()} and {@link #asValueType} method
628 * of a primitive class respectively.
629 * <p>
630 * A primitive class is a {@linkplain #isValue() value class}.
631 *
632 * @return {@code true} if this class is a primitive class, otherwise {@code false}
633 * @see #isValue()
634 * @see #asPrimaryType()
635 * @see #asValueType()
636 * @since Valhalla
637 */
638 /* package */ boolean isPrimitiveClass() {
639 return (this.getModifiers() & PrimitiveClass.PRIMITIVE_CLASS) != 0;
640 }
641
642 /**
643 * {@return {@code true} if this {@code Class} object represents an identity
644 * class or interface; otherwise {@code false}}
645 *
646 * If this {@code Class} object represents an array type, then this method
647 * returns {@code true}.
648 * If this {@code Class} object represents a primitive type, or {@code void},
649 * then this method returns {@code false}.
650 *
651 * @since Valhalla
652 */
653 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS)
654 public native boolean isIdentity();
655
656 /**
657 * {@return {@code true} if this {@code Class} object represents a value
658 * class or interface; otherwise {@code false}}
659 *
660 * If this {@code Class} object represents an array type, a primitive type, or
661 * {@code void}, then this method returns {@code false}.
662 *
663 * @since Valhalla
664 */
665 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS)
666 public boolean isValue() {
667 return (this.getModifiers() & Modifier.VALUE) != 0;
668 }
669
670 /**
671 * Returns a {@code Class} object representing the primary type
672 * of this class or interface.
673 * <p>
674 * If this {@code Class} object represents a primitive type or an array type,
675 * then this method returns this class.
676 * <p>
677 * If this {@code Class} object represents a {@linkplain #isPrimitiveClass()
678 * primitive class}, then this method returns the <em>primitive reference type</em>
679 * type of this primitive class.
680 * <p>
681 * Otherwise, this {@code Class} object represents a non-primitive class or interface
682 * and this method returns this class.
683 *
684 * @return the {@code Class} representing the primary type of
685 * this class or interface
686 * @since Valhalla
687 */
688 @IntrinsicCandidate
689 /* package */ Class<?> asPrimaryType() {
690 return isPrimitiveClass() ? primaryType : this;
691 }
692
693 /**
694 * Returns a {@code Class} object representing the <em>primitive value type</em>
695 * of this class if this class is a {@linkplain #isPrimitiveClass() primitive class}.
696 *
697 * @apiNote Alternatively, this method returns null if this class is not
698 * a primitive class rather than throwing UOE.
699 *
700 * @return the {@code Class} representing the {@linkplain #isPrimitiveValueType()
701 * primitive value type} of this class if this class is a primitive class
702 * @throws UnsupportedOperationException if this class or interface
703 * is not a primitive class
704 * @since Valhalla
705 */
706 @IntrinsicCandidate
707 /* package */ Class<?> asValueType() {
708 if (isPrimitiveClass())
709 return secondaryType;
710
711 throw new UnsupportedOperationException(this.getName().concat(" is not a primitive class"));
712 }
713
714 /**
715 * Returns {@code true} if this {@code Class} object represents the primary type
716 * of this class or interface.
717 * <p>
718 * If this {@code Class} object represents a primitive type or an array type,
719 * then this method returns {@code true}.
720 * <p>
721 * If this {@code Class} object represents a {@linkplain #isPrimitiveClass()
722 * primitive}, then this method returns {@code true} if this {@code Class}
723 * object represents a primitive reference type, or returns {@code false}
724 * if this {@code Class} object represents a primitive value type.
725 * <p>
726 * If this {@code Class} object represents a non-primitive class or interface,
727 * then this method returns {@code true}.
728 *
729 * @return {@code true} if this {@code Class} object represents
730 * the primary type of this class or interface
731 * @since Valhalla
732 */
733 /* package */ boolean isPrimaryType() {
734 if (isPrimitiveClass()) {
735 return this == primaryType;
736 }
737 return true;
738 }
739
740 /**
741 * Returns {@code true} if this {@code Class} object represents
742 * a {@linkplain #isPrimitiveClass() primitive} value type.
743 *
744 * @return {@code true} if this {@code Class} object represents
745 * the value type of a primitive class
746 * @since Valhalla
747 */
748 /* package */ boolean isPrimitiveValueType() {
749 return isPrimitiveClass() && this == secondaryType;
750 }
751
752 /**
753 * Creates a new instance of the class represented by this {@code Class}
754 * object. The class is instantiated as if by a {@code new}
755 * expression with an empty argument list. The class is initialized if it
756 * has not already been initialized.
757 *
758 * @deprecated This method propagates any exception thrown by the
759 * nullary constructor, including a checked exception. Use of
760 * this method effectively bypasses the compile-time exception
761 * checking that would otherwise be performed by the compiler.
762 * The {@link
763 * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
764 * Constructor.newInstance} method avoids this problem by wrapping
765 * any exception thrown by the constructor in a (checked) {@link
766 * java.lang.reflect.InvocationTargetException}.
767 *
768 * <p>The call
769 *
770 * <pre>{@code
771 * clazz.newInstance()
1439 * If this class does not represent an array class, then this method returns
1440 * {@code null}.
1441 */
1442 private Class<?> elementType() {
1443 if (!isArray()) return null;
1444
1445 Class<?> c = this;
1446 while (c.isArray()) {
1447 c = c.getComponentType();
1448 }
1449 return c;
1450 }
1451
1452 /**
1453 * Returns the Java language modifiers for this class or interface, encoded
1454 * in an integer. The modifiers consist of the Java Virtual Machine's
1455 * constants for {@code public}, {@code protected},
1456 * {@code private}, {@code final}, {@code static},
1457 * {@code abstract} and {@code interface}; they should be decoded
1458 * using the methods of class {@code Modifier}.
1459 * The modifiers also include the Java Virtual Machine's constants for
1460 * {@code identity class} and {@code value class}.
1461 *
1462 * <p> If the underlying class is an array class:
1463 * <ul>
1464 * <li> its {@code public}, {@code private} and {@code protected}
1465 * modifiers are the same as those of its component type
1466 * <li> its {@code abstract} and {@code final} modifiers are always
1467 * {@code true}
1468 * <li> its interface modifier is always {@code false}, even when
1469 * the component type is an interface
1470 * </ul>
1471 * If this {@code Class} object represents a primitive type or
1472 * void, its {@code public}, {@code abstract}, and {@code final}
1473 * modifiers are always {@code true}.
1474 * For {@code Class} objects representing void, primitive types, and
1475 * arrays, the values of other modifiers are {@code false} other
1476 * than as specified above.
1477 *
1478 * <p> The modifier encodings are defined in section {@jvms 4.1}
1479 * of <cite>The Java Virtual Machine Specification</cite>.
1480 *
1481 * @return the {@code int} representing the modifiers for this class
1482 * @see java.lang.reflect.Modifier
1483 * @see #accessFlags()
1484 * @see <a
1485 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1486 * programming language and JVM modeling in core reflection</a>
1487 * @since 1.1
1488 * @jls 8.1.1 Class Modifiers
1489 * @jls 9.1.1. Interface Modifiers
1490 * @jvms 4.1 The {@code ClassFile} Structure
1491 */
1492 @IntrinsicCandidate
1493 public native int getModifiers();
1494
1495 /**
1496 * {@return an unmodifiable set of the {@linkplain AccessFlag access
1497 * flags} for this class, possibly empty}
1498 * The {@code AccessFlags} may depend on the class file format version of the class.
1499 *
1500 * <p> If the underlying class is an array class:
1501 * <ul>
1502 * <li> its {@code PUBLIC}, {@code PRIVATE} and {@code PROTECTED}
1503 * access flags are the same as those of its component type
1504 * <li> its {@code ABSTRACT} and {@code FINAL} flags are present
1505 * <li> its {@code INTERFACE} flag is absent, even when the
1506 * component type is an interface
1507 * </ul>
1508 * If this {@code Class} object represents a primitive type or
1509 * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
1510 * {@code FINAL}.
1511 * For {@code Class} objects representing void, primitive types, and
1512 * arrays, access flags are absent other than as specified above.
1513 *
1514 * @see #getModifiers()
1515 * @jvms 4.1 The ClassFile Structure
1516 * @jvms 4.7.6 The InnerClasses Attribute
1517 * @since 20
1518 */
1519 public Set<AccessFlag> accessFlags() {
1520 // Location.CLASS allows SUPER and AccessFlag.MODULE which
1521 // INNER_CLASS forbids. INNER_CLASS allows PRIVATE, PROTECTED,
1522 // and STATIC, which are not allowed on Location.CLASS.
1523 // Use getClassAccessFlagsRaw to expose SUPER status.
1524 var location = (isMemberClass() || isLocalClass() ||
1525 isAnonymousClass() || isArray()) ?
1526 AccessFlag.Location.INNER_CLASS :
1527 AccessFlag.Location.CLASS;
1528 int accessFlags = (location == AccessFlag.Location.CLASS) ?
1529 getClassAccessFlagsRaw() : getModifiers();
1530 var cffv = ClassFileFormatVersion.fromMajor(getClassFileVersion() & 0xffff);
1531 if (cffv.compareTo(ClassFileFormatVersion.latest()) >= 0) {
1532 // Ignore unspecified (0x800) access flag for current version
1533 accessFlags &= ~0x0800;
1534 }
1535 return AccessFlag.maskToAccessFlags(accessFlags, location, cffv);
1536 }
1537
1538 /**
1539 * Gets the signers of this class.
1540 *
1541 * @return the signers of this class, or null if there are no signers. In
1542 * particular, this method returns null if this {@code Class} object represents
1543 * a primitive type or void.
1544 * @since 1.1
1545 */
1546 public native Object[] getSigners();
1547
1548 /**
1549 * Set the signers of this class.
1550 */
1551 native void setSigners(Object[] signers);
1552
1553 /**
1554 * If this {@code Class} object represents a local or anonymous
1555 * class within a method, returns a {@link
1556 * java.lang.reflect.Method Method} object representing the
1557 * immediately enclosing method of the underlying class. Returns
1558 * {@code null} otherwise.
1559 *
1560 * In particular, this method returns {@code null} if the underlying
1561 * class is a local or anonymous class immediately enclosed by a class or
1562 * interface declaration, instance initializer or static initializer.
1563 *
1564 * @return the immediately enclosing method of the underlying class, if
1565 * that class is a local or anonymous class; otherwise {@code null}.
1566 *
1567 * @throws SecurityException
1568 * If a security manager, <i>s</i>, is present and any of the
1569 * following conditions is met:
1570 *
1571 * <ul>
1572 *
1673 // the immediately enclosing method or constructor's
1674 // descriptor (null iff name is).
1675 String descriptor = (String)enclosingInfo[2];
1676 assert((name != null && descriptor != null) || name == descriptor);
1677 } catch (ClassCastException cce) {
1678 throw new InternalError("Invalid type in enclosing method information", cce);
1679 }
1680 }
1681
1682 EnclosingMethodInfo(Object[] enclosingInfo) {
1683 validate(enclosingInfo);
1684 this.enclosingClass = (Class<?>)enclosingInfo[0];
1685 this.name = (String)enclosingInfo[1];
1686 this.descriptor = (String)enclosingInfo[2];
1687 }
1688
1689 boolean isPartial() {
1690 return enclosingClass == null || name == null || descriptor == null;
1691 }
1692
1693 boolean isObjectConstructor() { return !isPartial() && ConstantDescs.INIT_NAME.equals(name); }
1694
1695 boolean isValueFactoryMethod() { return !isPartial() && ConstantDescs.VNEW_NAME.equals(name); }
1696
1697 boolean isMethod() { return !isPartial() && !isObjectConstructor()
1698 && !isValueFactoryMethod()
1699 && !ConstantDescs.CLASS_INIT_NAME.equals(name); }
1700
1701 Class<?> getEnclosingClass() { return enclosingClass; }
1702
1703 String getName() { return name; }
1704
1705 String getDescriptor() { return descriptor; }
1706
1707 }
1708
1709 private static Class<?> toClass(Type o) {
1710 if (o instanceof GenericArrayType)
1711 return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
1712 0)
1713 .getClass();
1714 return (Class<?>)o;
1715 }
1716
1717 /**
1718 * If this {@code Class} object represents a local or anonymous
1719 * class within a constructor, returns a {@link
1738 * s.checkPermission} method with
1739 * {@code RuntimePermission("accessDeclaredMembers")}
1740 * denies access to the constructors within the enclosing class
1741 *
1742 * <li> the caller's class loader is not the same as or an
1743 * ancestor of the class loader for the enclosing class and
1744 * invocation of {@link SecurityManager#checkPackageAccess
1745 * s.checkPackageAccess()} denies access to the package
1746 * of the enclosing class
1747 *
1748 * </ul>
1749 * @since 1.5
1750 */
1751 @CallerSensitive
1752 public Constructor<?> getEnclosingConstructor() throws SecurityException {
1753 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1754
1755 if (enclosingInfo == null)
1756 return null;
1757 else {
1758 if (!enclosingInfo.isObjectConstructor() && !enclosingInfo.isValueFactoryMethod())
1759 return null;
1760
1761 ConstructorRepository typeInfo = ConstructorRepository.make(enclosingInfo.getDescriptor(),
1762 getFactory());
1763 Type [] parameterTypes = typeInfo.getParameterTypes();
1764 Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
1765
1766 // Convert Types to Classes; returned types *should*
1767 // be class objects since the methodDescriptor's used
1768 // don't have generics information
1769 for(int i = 0; i < parameterClasses.length; i++)
1770 parameterClasses[i] = toClass(parameterTypes[i]);
1771
1772 // Perform access check
1773 final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1774 @SuppressWarnings("removal")
1775 SecurityManager sm = System.getSecurityManager();
1776 if (sm != null) {
1777 enclosingCandidate.checkMemberAccess(sm, Member.DECLARED,
1778 Reflection.getCallerClass(), true);
1918 simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1919 }
1920 return simpleName;
1921 }
1922
1923 /**
1924 * Return an informative string for the name of this class or interface.
1925 *
1926 * @return an informative string for the name of this class or interface
1927 * @since 1.8
1928 */
1929 public String getTypeName() {
1930 if (isArray()) {
1931 try {
1932 Class<?> cl = this;
1933 int dimensions = 0;
1934 do {
1935 dimensions++;
1936 cl = cl.getComponentType();
1937 } while (cl.isArray());
1938 return cl.getTypeName().concat("[]".repeat(dimensions));
1939 } catch (Throwable e) { /*FALLTHRU*/ }
1940 }
1941 if (isPrimitiveClass()) {
1942 // TODO: null-default
1943 return isPrimaryType() ? getName().concat(".ref") : getName();
1944 } else {
1945 return getName();
1946 }
1947 }
1948
1949 /**
1950 * Returns the canonical name of the underlying class as
1951 * defined by <cite>The Java Language Specification</cite>.
1952 * Returns {@code null} if the underlying class does not have a canonical
1953 * name. Classes without canonical names include:
1954 * <ul>
1955 * <li>a {@linkplain #isLocalClass() local class}
1956 * <li>a {@linkplain #isAnonymousClass() anonymous class}
1957 * <li>a {@linkplain #isHidden() hidden class}
1958 * <li>an array whose component type does not have a canonical name</li>
1959 * </ul>
1960 *
1961 * The canonical name for a primitive class is the keyword for the
1962 * corresponding primitive type ({@code byte}, {@code short},
1963 * {@code char}, {@code int}, and so on).
1964 *
1965 * <p>An array type has a canonical name if and only if its
1966 * component type has a canonical name. When an array type has a
3843 /* includeStatic */ false));
3844 }
3845
3846 return res;
3847 }
3848
3849 // Returns a "root" Constructor object. This Constructor object must NOT
3850 // be propagated to the outside world, but must instead be copied
3851 // via ReflectionFactory.copyConstructor.
3852 private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3853 int which) throws NoSuchMethodException
3854 {
3855 ReflectionFactory fact = getReflectionFactory();
3856 Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3857 for (Constructor<T> constructor : constructors) {
3858 if (arrayContentsEq(parameterTypes,
3859 fact.getExecutableSharedParameterTypes(constructor))) {
3860 return constructor;
3861 }
3862 }
3863 throw new NoSuchMethodException(methodToString(isValue() ? "<vnew>" : "<init>", parameterTypes));
3864 }
3865
3866 //
3867 // Other helpers and base implementation
3868 //
3869
3870 private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3871 if (a1 == null) {
3872 return a2 == null || a2.length == 0;
3873 }
3874
3875 if (a2 == null) {
3876 return a1.length == 0;
3877 }
3878
3879 if (a1.length != a2.length) {
3880 return false;
3881 }
3882
3883 for (int i = 0; i < a1.length; i++) {
4148 }
4149 return directory;
4150 }
4151 private transient volatile Map<String, T> enumConstantDirectory;
4152
4153 /**
4154 * Casts an object to the class or interface represented
4155 * by this {@code Class} object.
4156 *
4157 * @param obj the object to be cast
4158 * @return the object after casting, or null if obj is null
4159 *
4160 * @throws ClassCastException if the object is not
4161 * null and is not assignable to the type T.
4162 *
4163 * @since 1.5
4164 */
4165 @SuppressWarnings("unchecked")
4166 @IntrinsicCandidate
4167 public T cast(Object obj) {
4168 if (isPrimitiveValueType() && obj == null)
4169 throw new NullPointerException(getName() + " is a primitive value type");
4170
4171 if (obj != null && !isInstance(obj))
4172 throw new ClassCastException(cannotCastMsg(obj));
4173 return (T) obj;
4174 }
4175
4176 private String cannotCastMsg(Object obj) {
4177 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
4178 }
4179
4180 /**
4181 * Casts this {@code Class} object to represent a subclass of the class
4182 * represented by the specified class object. Checks that the cast
4183 * is valid, and throws a {@code ClassCastException} if it is not. If
4184 * this method succeeds, it always returns a reference to this {@code Class} object.
4185 *
4186 * <p>This method is useful when a client needs to "narrow" the type of
4187 * a {@code Class} object to pass it to an API that restricts the
4188 * {@code Class} objects that it is willing to accept. A cast would
4189 * generate a compile-time warning, as the correctness of the cast
4190 * could not be checked at runtime (because generic types are implemented
4446 *
4447 * <p> If this {@code Class} object represents an interface, the return
4448 * value is an array containing objects representing the uses of interface
4449 * types to specify interfaces directly extended by the interface. The
4450 * order of the objects in the array corresponds to the order of the
4451 * interface types used in the 'extends' clause of the declaration of this
4452 * {@code Class} object.
4453 *
4454 * <p> If this {@code Class} object represents a class or interface whose
4455 * declaration does not explicitly indicate any annotated superinterfaces,
4456 * the return value is an array of length 0.
4457 *
4458 * <p> If this {@code Class} object represents either the {@code Object}
4459 * class, an array type, a primitive type, or void, the return value is an
4460 * array of length 0.
4461 *
4462 * @return an array representing the superinterfaces
4463 * @since 1.8
4464 */
4465 public AnnotatedType[] getAnnotatedInterfaces() {
4466 return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
4467 }
4468
4469 private native Class<?> getNestHost0();
4470
4471 /**
4472 * Returns the nest host of the <a href=#nest>nest</a> to which the class
4473 * or interface represented by this {@code Class} object belongs.
4474 * Every class and interface belongs to exactly one nest.
4475 *
4476 * If the nest host of this class or interface has previously
4477 * been determined, then this method returns the nest host.
4478 * If the nest host of this class or interface has
4479 * not previously been determined, then this method determines the nest
4480 * host using the algorithm of JVMS 5.4.4, and returns it.
4481 *
4482 * Often, a class or interface belongs to a nest consisting only of itself,
4483 * in which case this method returns {@code this} to indicate that the class
4484 * or interface is the nest host.
4485 *
4486 * <p>If this {@code Class} object represents a primitive type, an array type,
4661 * {@code void}, then the result is a field descriptor string which
4662 * is a one-letter code corresponding to a primitive type or {@code void}
4663 * ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}).
4664 *
4665 * @apiNote
4666 * This is not a strict inverse of {@link #forName};
4667 * distinct classes which share a common name but have different class loaders
4668 * will have identical descriptor strings.
4669 *
4670 * @return the descriptor string for this {@code Class} object
4671 * @jvms 4.3.2 Field Descriptors
4672 * @since 12
4673 */
4674 @Override
4675 public String descriptorString() {
4676 if (isPrimitive())
4677 return Wrapper.forPrimitiveType(this).basicTypeString();
4678
4679 if (isArray()) {
4680 return "[" + componentType.descriptorString();
4681 }
4682 char typeDesc = isPrimitiveValueType() ? 'Q' : 'L';
4683 if (isHidden()) {
4684 String name = getName();
4685 int index = name.indexOf('/');
4686 return new StringBuilder(name.length() + 2)
4687 .append(typeDesc)
4688 .append(name.substring(0, index).replace('.', '/'))
4689 .append('.')
4690 .append(name, index + 1, name.length())
4691 .append(';')
4692 .toString();
4693 } else {
4694 String name = getName().replace('.', '/');
4695 return new StringBuilder(name.length() + 2)
4696 .append(typeDesc)
4697 .append(name)
4698 .append(';')
4699 .toString();
4700 }
4701 }
4702
4703 /**
4704 * Returns the component type of this {@code Class}, if it describes
4705 * an array type, or {@code null} otherwise.
4706 *
4707 * @implSpec
4708 * Equivalent to {@link Class#getComponentType()}.
4709 *
4710 * @return a {@code Class} describing the component type, or {@code null}
4711 * if this {@code Class} does not describe an array type
4712 * @since 12
4713 */
4714 @Override
4715 public Class<?> componentType() {
4716 return isArray() ? componentType : null;
4854 * @since 17
4855 */
4856 public boolean isSealed() {
4857 if (isArray() || isPrimitive()) {
4858 return false;
4859 }
4860 return getPermittedSubclasses() != null;
4861 }
4862
4863 private native Class<?>[] getPermittedSubclasses0();
4864
4865 /*
4866 * Return the class's major and minor class file version packed into an int.
4867 * The high order 16 bits contain the class's minor version. The low order
4868 * 16 bits contain the class's major version.
4869 *
4870 * If the class is an array type then the class file version of its element
4871 * type is returned. If the class is a primitive type then the latest class
4872 * file major version is returned and zero is returned for the minor version.
4873 */
4874 /* package-private */
4875 int getClassFileVersion() {
4876 Class<?> c = isArray() ? elementType() : this;
4877 return c.getClassFileVersion0();
4878 }
4879
4880 private native int getClassFileVersion0();
4881
4882 /*
4883 * Return the access flags as they were in the class's bytecode, including
4884 * the original setting of ACC_SUPER.
4885 *
4886 * If the class is an array type then the access flags of the element type is
4887 * returned. If the class is a primitive then ACC_ABSTRACT | ACC_FINAL | ACC_PUBLIC.
4888 */
4889 private int getClassAccessFlagsRaw() {
4890 Class<?> c = isArray() ? elementType() : this;
4891 return c.getClassAccessFlagsRaw0();
4892 }
4893
4894 private native int getClassAccessFlagsRaw0();
4895 }
|