1 /*
2 * Copyright (c) 1994, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package java.lang;
27
28 import java.lang.annotation.Annotation;
29 import java.lang.constant.ClassDesc;
30 import java.lang.constant.ConstantDescs;
31 import java.lang.invoke.TypeDescriptor;
32 import java.lang.invoke.MethodHandles;
33 import java.lang.ref.SoftReference;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.io.ObjectStreamField;
37 import java.lang.reflect.AnnotatedElement;
38 import java.lang.reflect.AnnotatedType;
39 import java.lang.reflect.AccessFlag;
40 import java.lang.reflect.Array;
41 import java.lang.reflect.Constructor;
42 import java.lang.reflect.Executable;
43 import java.lang.reflect.Field;
44 import java.lang.reflect.GenericArrayType;
45 import java.lang.reflect.GenericDeclaration;
46 import java.lang.reflect.GenericSignatureFormatError;
47 import java.lang.reflect.InvocationTargetException;
48 import java.lang.reflect.Member;
49 import java.lang.reflect.Method;
50 import java.lang.reflect.Modifier;
51 import java.lang.reflect.RecordComponent;
52 import java.lang.reflect.Type;
53 import java.lang.reflect.TypeVariable;
54 import java.lang.constant.Constable;
55 import java.net.URL;
56 import java.security.AllPermission;
57 import java.security.Permissions;
58 import java.security.ProtectionDomain;
59 import java.util.ArrayList;
60 import java.util.Arrays;
61 import java.util.Collection;
62 import java.util.HashMap;
63 import java.util.LinkedHashMap;
64 import java.util.LinkedHashSet;
65 import java.util.List;
66 import java.util.Map;
67 import java.util.Objects;
68 import java.util.Optional;
69 import java.util.Set;
70 import java.util.stream.Collectors;
71
72 import jdk.internal.constant.ConstantUtils;
73 import jdk.internal.loader.BootLoader;
74 import jdk.internal.loader.BuiltinClassLoader;
75 import jdk.internal.misc.Unsafe;
76 import jdk.internal.module.Resources;
77 import jdk.internal.reflect.CallerSensitive;
78 import jdk.internal.reflect.CallerSensitiveAdapter;
79 import jdk.internal.reflect.ConstantPool;
80 import jdk.internal.reflect.Reflection;
81 import jdk.internal.reflect.ReflectionFactory;
82 import jdk.internal.util.ModifiedUtf;
83 import jdk.internal.vm.annotation.AOTRuntimeSetup;
84 import jdk.internal.vm.annotation.AOTSafeClassInitializer;
85 import jdk.internal.vm.annotation.IntrinsicCandidate;
86 import jdk.internal.vm.annotation.Stable;
87
88 import sun.invoke.util.BytecodeDescriptor;
89 import sun.invoke.util.Wrapper;
90 import sun.reflect.generics.factory.CoreReflectionFactory;
91 import sun.reflect.generics.factory.GenericsFactory;
92 import sun.reflect.generics.repository.ClassRepository;
93 import sun.reflect.generics.scope.ClassScope;
94 import sun.reflect.annotation.*;
95
96 /**
97 * Instances of the class {@code Class} represent classes and
98 * interfaces in a running Java application. An enum class and a record
99 * class are kinds of class; an annotation interface is a kind of
100 * interface. Every array also belongs to a class that is reflected as
101 * a {@code Class} object that is shared by all arrays with the same
102 * element type and number of dimensions. The primitive Java types
103 * ({@code boolean}, {@code byte}, {@code char}, {@code short}, {@code
104 * int}, {@code long}, {@code float}, and {@code double}), and the
105 * keyword {@code void} are also represented as {@code Class} objects.
106 *
107 * <p> {@code Class} has no public constructor. Instead a {@code Class}
108 * object is constructed automatically by the Java Virtual Machine when
109 * a class is derived from the bytes of a {@code class} file through
110 * the invocation of one of the following methods:
111 * <ul>
112 * <li> {@link ClassLoader#defineClass(String, byte[], int, int) ClassLoader::defineClass}
113 * <li> {@link java.lang.invoke.MethodHandles.Lookup#defineClass(byte[])
114 * java.lang.invoke.MethodHandles.Lookup::defineClass}
115 * <li> {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
116 * java.lang.invoke.MethodHandles.Lookup::defineHiddenClass}
117 * </ul>
118 *
119 * <p> The methods of class {@code Class} expose many characteristics of a
120 * class or interface. Most characteristics are derived from the {@code class}
121 * file that the class loader passed to the Java Virtual Machine or
122 * from the {@code class} file passed to {@code Lookup::defineClass}
123 * or {@code Lookup::defineHiddenClass}.
124 * A few characteristics are determined by the class loading environment
125 * at run time, such as the module returned by {@link #getModule() getModule()}.
126 *
127 * <p> The following example uses a {@code Class} object to print the
128 * class name of an object:
129 *
130 * {@snippet lang="java" :
131 * void printClassName(Object obj) {
132 * System.out.println("The class of " + obj +
133 * " is " + obj.getClass().getName());
134 * }}
135 *
136 * It is also possible to get the {@code Class} object for a named
137 * class or interface (or for {@code void}) using a <dfn>class literal</dfn>
138 * (JLS {@jls 15.8.2}).
139 * For example:
140 *
141 * {@snippet lang="java" :
142 * System.out.println("The name of class Foo is: " + Foo.class.getName()); // @highlight substring="Foo.class"
143 * }
144 *
145 * <p> Some methods of class {@code Class} expose whether the declaration of
146 * a class or interface in Java source code was <em>enclosed</em> within
147 * another declaration. Other methods describe how a class or interface
148 * is situated in a <dfn>{@index "nest"}</dfn>. A nest is a set of
149 * classes and interfaces, in the same run-time package, that
150 * allow mutual access to their {@code private} members.
151 * The classes and interfaces are known as <dfn>{@index "nestmates"}</dfn>
152 * (JVMS {@jvms 4.7.29}).
153 * One nestmate acts as the
154 * <dfn>nest host</dfn> (JVMS {@jvms 4.7.28}), and enumerates the other nestmates which
155 * belong to the nest; each of them in turn records it as the nest host.
156 * The classes and interfaces which belong to a nest, including its host, are
157 * determined when
158 * {@code class} files are generated, for example, a Java compiler
159 * will typically record a top-level class as the host of a nest where the
160 * other members are the classes and interfaces whose declarations are
161 * enclosed within the top-level class declaration.
162 *
163 * <p> Unless otherwise specified, methods in this class throw a
164 * {@link NullPointerException} when they are called with {@code null}
165 * or an array that contains {@code null} as an argument.
166 *
167 * <h2><a id=hiddenClasses>Hidden Classes</a></h2>
168 * A class or interface created by the invocation of
169 * {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
170 * Lookup::defineHiddenClass} is a {@linkplain Class#isHidden() <dfn>hidden</dfn>}
171 * class or interface.
172 * All kinds of class, including enum classes and record classes, may be
173 * hidden classes; all kinds of interface, including annotation interfaces,
174 * may be hidden interfaces.
175 *
176 * The {@linkplain #getName() name of a hidden class or interface} is
177 * not a {@linkplain ClassLoader##binary-name binary name},
178 * which means the following:
179 * <ul>
180 * <li>A hidden class or interface cannot be referenced by the constant pools
181 * of other classes and interfaces.
182 * <li>A hidden class or interface cannot be described in
183 * {@linkplain java.lang.constant.ConstantDesc <em>nominal form</em>} by
184 * {@link #describeConstable() Class::describeConstable},
185 * {@link ClassDesc#of(String) ClassDesc::of}, or
186 * {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor}.
187 * <li>A hidden class or interface cannot be discovered by {@link #forName Class::forName}
188 * or {@link ClassLoader#loadClass(String, boolean) ClassLoader::loadClass}.
189 * </ul>
190 *
191 * A hidden class or interface is never an array class, but may be
192 * the element type of an array. In all other respects, the fact that
193 * a class or interface is hidden has no bearing on the characteristics
194 * exposed by the methods of class {@code Class}.
195 *
196 * <h2><a id=implicitClasses>Implicitly Declared Classes</a></h2>
197 *
198 * Conventionally, a Java compiler, starting from a source file for an
199 * implicitly declared class, say {@code HelloWorld.java}, creates a
200 * similarly-named {@code class} file, {@code HelloWorld.class}, where
201 * the class stored in that {@code class} file is named {@code
202 * "HelloWorld"}, matching the base names of the source and {@code
203 * class} files.
204 *
205 * For the {@code Class} object of an implicitly declared class {@code
206 * HelloWorld}, the methods to get the {@linkplain #getName name} and
207 * {@linkplain #getTypeName type name} return results
208 * equal to {@code "HelloWorld"}. The {@linkplain #getSimpleName
209 * simple name} of such an implicitly declared class is {@code "HelloWorld"} and
210 * the {@linkplain #getCanonicalName canonical name} is {@code "HelloWorld"}.
211 *
212 * @param <T> the type of the class modeled by this {@code Class}
213 * object. For example, the type of {@code String.class} is {@code
214 * Class<String>}. Use {@code Class<?>} if the class being modeled is
215 * unknown.
216 *
217 * @see java.lang.ClassLoader#defineClass(byte[], int, int)
218 * @since 1.0
219 */
220 @AOTSafeClassInitializer
221 public final class Class<T> implements java.io.Serializable,
222 GenericDeclaration,
223 Type,
224 AnnotatedElement,
225 TypeDescriptor.OfField<Class<?>>,
226 Constable {
227 private static final int ANNOTATION = 0x00002000;
228 private static final int ENUM = 0x00004000;
229 private static final int SYNTHETIC = 0x00001000;
230
231 private static native void registerNatives();
232 static {
233 runtimeSetup();
234 }
235
236 /// No significant static final fields; [#resetArchivedStates()] handles
237 /// prevents storing [#reflectionFactory] into AOT image.
238 @AOTRuntimeSetup
239 private static void runtimeSetup() {
240 registerNatives();
241 }
242
243 /*
244 * Private constructor. Only the Java Virtual Machine creates Class objects.
245 * This constructor is not used and prevents the default constructor being
246 * generated.
247 */
248 private Class(ClassLoader loader, Class<?> arrayComponentType, char mods, ProtectionDomain pd, boolean isPrim, char flags) {
249 // Initialize final field for classLoader. The initialization value of non-null
250 // prevents future JIT optimizations from assuming this final field is null.
251 // The following assignments are done directly by the VM without calling this constructor.
252 classLoader = loader;
253 componentType = arrayComponentType;
254 modifiers = mods;
255 protectionDomain = pd;
256 primitive = isPrim;
257 classFileAccessFlags = flags;
258 }
259
260 /**
261 * Converts the object to a string. The string representation is the
262 * string "class" or "interface", followed by a space, and then by the
263 * name of the class in the format returned by {@code getName}.
264 * If this {@code Class} object represents a primitive type,
265 * this method returns the name of the primitive type. If
266 * this {@code Class} object represents void this method returns
267 * "void". If this {@code Class} object represents an array type,
268 * this method returns "class " followed by {@code getName}.
269 *
270 * @return a string representation of this {@code Class} object.
271 */
272 public String toString() {
273 String kind = isInterface() ? "interface " : isPrimitive() ? "" : "class ";
274 return kind.concat(getName());
275 }
276
277 /**
278 * Returns a string describing this {@code Class}, including
279 * information about modifiers, {@link #isSealed() sealed}/{@code
280 * non-sealed} status, and type parameters.
281 *
282 * The string is formatted as a list of type modifiers, if any,
283 * followed by the kind of type (empty string for primitive types
284 * and {@code class}, {@code enum}, {@code interface},
285 * {@code @interface}, or {@code record} as appropriate), followed
286 * by the type's name, followed by an angle-bracketed
287 * comma-separated list of the type's type parameters, if any,
288 * including informative bounds on the type parameters, if any.
289 *
290 * A space is used to separate modifiers from one another and to
291 * separate any modifiers from the kind of type. The modifiers
292 * occur in canonical order. If there are no type parameters, the
293 * type parameter list is elided.
294 *
295 * For an array type, the string starts with the type name,
296 * followed by an angle-bracketed comma-separated list of the
297 * type's type parameters, if any, followed by a sequence of
298 * {@code []} characters, one set of brackets per dimension of
299 * the array.
300 *
301 * <p>Note that since information about the runtime representation
302 * of a type is being generated, modifiers not present on the
303 * originating source code or illegal on the originating source
304 * code may be present.
305 *
306 * @return a string describing this {@code Class}, including
307 * information about modifiers and type parameters
308 *
309 * @since 1.8
310 */
311 public String toGenericString() {
312 if (isPrimitive()) {
313 return toString();
314 } else {
315 StringBuilder sb = new StringBuilder();
316 Class<?> component = this;
317 int arrayDepth = 0;
318
319 if (isArray()) {
320 do {
321 arrayDepth++;
322 component = component.getComponentType();
323 } while (component.isArray());
324 sb.append(component.getName());
325 } else {
326 // Class modifiers are a superset of interface modifiers
327 int modifiers = getModifiers() & Modifier.classModifiers();
328 if (modifiers != 0) {
329 sb.append(Modifier.toString(modifiers));
330 sb.append(' ');
331 }
332
333 // A class cannot be strictfp and sealed/non-sealed so
334 // it is sufficient to check for sealed-ness after all
335 // modifiers are printed.
336 addSealingInfo(modifiers, sb);
337
338 if (isAnnotation()) {
339 sb.append('@');
340 }
341 if (isInterface()) { // Note: all annotation interfaces are interfaces
342 sb.append("interface");
343 } else {
344 if (isEnum())
345 sb.append("enum");
346 else if (isRecord())
347 sb.append("record");
348 else
349 sb.append("class");
350 }
351 sb.append(' ');
352 sb.append(getName());
353 }
354
355 TypeVariable<?>[] typeparms = component.getTypeParameters();
356 if (typeparms.length > 0) {
357 sb.append(Arrays.stream(typeparms)
358 .map(Class::typeVarBounds)
359 .collect(Collectors.joining(",", "<", ">")));
360 }
361
362 if (arrayDepth > 0) sb.append("[]".repeat(arrayDepth));
363
364 return sb.toString();
365 }
366 }
367
368 private void addSealingInfo(int modifiers, StringBuilder sb) {
369 // A class can be final XOR sealed XOR non-sealed.
370 if (Modifier.isFinal(modifiers)) {
371 return; // no-op
372 } else {
373 if (isSealed()) {
374 sb.append("sealed ");
375 return;
376 } else {
377 // Check for sealed ancestor, which implies this class
378 // is non-sealed.
379 if (hasSealedAncestor(this)) {
380 sb.append("non-sealed ");
381 }
382 }
383 }
384 }
385
386 private boolean hasSealedAncestor(Class<?> clazz) {
387 // From JLS 8.1.1.2:
388 // "It is a compile-time error if a class has a sealed direct
389 // superclass or a sealed direct superinterface, and is not
390 // declared final, sealed, or non-sealed either explicitly or
391 // implicitly.
392 // Thus, an effect of the sealed keyword is to force all
393 // direct subclasses to explicitly declare whether they are
394 // final, sealed, or non-sealed. This avoids accidentally
395 // exposing a sealed class hierarchy to unwanted subclassing."
396
397 // Therefore, will just check direct superclass and
398 // superinterfaces.
399 var superclass = clazz.getSuperclass();
400 if (superclass != null && superclass.isSealed()) {
401 return true;
402 }
403 for (var superinterface : clazz.getInterfaces()) {
404 if (superinterface.isSealed()) {
405 return true;
406 }
407 }
408 return false;
409 }
410
411 static String typeVarBounds(TypeVariable<?> typeVar) {
412 Type[] bounds = typeVar.getBounds();
413 if (bounds.length == 1 && bounds[0].equals(Object.class)) {
414 return typeVar.getName();
415 } else {
416 return typeVar.getName() + " extends " +
417 Arrays.stream(bounds)
418 .map(Type::getTypeName)
419 .collect(Collectors.joining(" & "));
420 }
421 }
422
423 /**
424 * Returns the {@code Class} object associated with the class or
425 * interface with the given string name. Invoking this method is
426 * equivalent to:
427 *
428 * {@snippet lang="java" :
429 * Class.forName(className, true, currentLoader)
430 * }
431 *
432 * where {@code currentLoader} denotes the defining class loader of
433 * the current class.
434 *
435 * <p> For example, the following code fragment returns the
436 * runtime {@code Class} object for the class named
437 * {@code java.lang.Thread}:
438 *
439 * {@snippet lang="java" :
440 * Class<?> t = Class.forName("java.lang.Thread");
441 * }
442 * <p>
443 * A call to {@code forName("X")} causes the class named
444 * {@code X} to be initialized.
445 *
446 * <p>
447 * In cases where this method is called from a context where there is no
448 * caller frame on the stack (e.g. when called directly from a JNI
449 * attached thread), the system class loader is used.
450 *
451 * @param className the {@linkplain ClassLoader##binary-name binary name}
452 * of the class or the string representing an array type
453 * @return the {@code Class} object for the class with the
454 * specified name.
455 * @throws LinkageError if the linkage fails
456 * @throws ExceptionInInitializerError if the initialization provoked
457 * by this method fails
458 * @throws ClassNotFoundException if the class cannot be located
459 *
460 * @jls 12.2 Loading of Classes and Interfaces
461 * @jls 12.3 Linking of Classes and Interfaces
462 * @jls 12.4 Initialization of Classes and Interfaces
463 */
464 @CallerSensitive
465 public static Class<?> forName(String className)
466 throws ClassNotFoundException {
467 Class<?> caller = Reflection.getCallerClass();
468 return forName(className, caller);
469 }
470
471 // Caller-sensitive adapter method for reflective invocation
472 @CallerSensitiveAdapter
473 private static Class<?> forName(String className, Class<?> caller)
474 throws ClassNotFoundException {
475 validateClassNameLength(className);
476 ClassLoader loader = (caller == null) ? ClassLoader.getSystemClassLoader()
477 : ClassLoader.getClassLoader(caller);
478 return forName0(className, true, loader);
479 }
480
481 /**
482 * Returns the {@code Class} object associated with the class or
483 * interface with the given string name, using the given class loader.
484 * Given the {@linkplain ClassLoader##binary-name binary name} for a class or interface,
485 * this method attempts to locate and load the class or interface. The specified
486 * class loader is used to load the class or interface. If the parameter
487 * {@code loader} is {@code null}, the class is loaded through the bootstrap
488 * class loader. The class is initialized only if the
489 * {@code initialize} parameter is {@code true} and if it has
490 * not been initialized earlier.
491 *
492 * <p> This method cannot be used to obtain any of the {@code Class} objects
493 * representing primitive types or void, hidden classes or interfaces,
494 * or array classes whose element type is a hidden class or interface.
495 * If {@code name} denotes a primitive type or void, for example {@code I},
496 * an attempt will be made to locate a user-defined class in the unnamed package
497 * whose name is {@code I} instead.
498 * To obtain a {@code Class} object for a named primitive type
499 * such as {@code int} or {@code long} use {@link
500 * #forPrimitiveName(String)}.
501 *
502 * <p> To obtain the {@code Class} object associated with an array class,
503 * the name consists of one or more {@code '['} representing the depth
504 * of the array nesting, followed by the element type as encoded in
505 * {@linkplain ##nameFormat the table} specified in {@code Class.getName()}.
506 *
507 * <p> Examples:
508 * {@snippet lang="java" :
509 * Class<?> threadClass = Class.forName("java.lang.Thread", false, currentLoader);
510 * Class<?> stringArrayClass = Class.forName("[Ljava.lang.String;", false, currentLoader);
511 * Class<?> intArrayClass = Class.forName("[[[I", false, currentLoader); // Class of int[][][]
512 * Class<?> nestedClass = Class.forName("java.lang.Character$UnicodeBlock", false, currentLoader);
513 * Class<?> fooClass = Class.forName("Foo", true, currentLoader);
514 * }
515 *
516 * <p> A call to {@code getName()} on the {@code Class} object returned
517 * from {@code forName(}<i>N</i>{@code )} returns <i>N</i>.
518 *
519 * <p> A call to {@code forName("[L}<i>N</i>{@code ;")} causes the element type
520 * named <i>N</i> to be loaded but not initialized regardless of the value
521 * of the {@code initialize} parameter.
522 *
523 * @apiNote
524 * This method throws errors related to loading, linking or initializing
525 * as specified in Sections {@jls 12.2}, {@jls 12.3}, and {@jls 12.4} of
526 * <cite>The Java Language Specification</cite>.
527 * In addition, this method does not check whether the requested class
528 * is accessible to its caller.
529 *
530 * @param name the {@linkplain ClassLoader##binary-name binary name}
531 * of the class or the string representing an array class
532 *
533 * @param initialize if {@code true} the class will be initialized
534 * (which implies linking). See Section {@jls
535 * 12.4} of <cite>The Java Language
536 * Specification</cite>.
537 * @param loader class loader from which the class must be loaded,
538 * may be {@code null}
539 * @return class object representing the desired class
540 *
541 * @throws LinkageError if the linkage fails
542 * @throws ExceptionInInitializerError if the initialization provoked
543 * by this method fails
544 * @throws ClassNotFoundException if the class cannot be located by
545 * the specified class loader
546 *
547 * @see java.lang.Class#forName(String)
548 * @see java.lang.ClassLoader
549 *
550 * @jls 12.2 Loading of Classes and Interfaces
551 * @jls 12.3 Linking of Classes and Interfaces
552 * @jls 12.4 Initialization of Classes and Interfaces
553 * @jls 13.1 The Form of a Binary
554 * @since 1.2
555 */
556 public static Class<?> forName(String name, boolean initialize, ClassLoader loader)
557 throws ClassNotFoundException
558 {
559 validateClassNameLength(name);
560 return forName0(name, initialize, loader);
561 }
562
563 /** Called after security check for system loader access checks have been made. */
564 private static native Class<?> forName0(String name, boolean initialize,
565 ClassLoader loader)
566 throws ClassNotFoundException;
567
568
569 /**
570 * Returns the {@code Class} with the given {@linkplain ClassLoader##binary-name
571 * binary name} in the given module.
572 *
573 * <p> This method attempts to locate and load the class or interface.
574 * It does not link the class, and does not run the class initializer.
575 * If the class is not found, this method returns {@code null}. </p>
576 *
577 * <p> If the class loader of the given module defines other modules and
578 * the given name is a class defined in a different module, this method
579 * returns {@code null} after the class is loaded. </p>
580 *
581 * <p> This method does not check whether the requested class is
582 * accessible to its caller. </p>
583 *
584 * @apiNote
585 * This method does not support loading of array types, unlike
586 * {@link #forName(String, boolean, ClassLoader)}. The class name must be
587 * a binary name. This method returns {@code null} on failure rather than
588 * throwing a {@link ClassNotFoundException}, as is done by
589 * the {@link #forName(String, boolean, ClassLoader)} method.
590 *
591 * @param module A module
592 * @param name The {@linkplain ClassLoader##binary-name binary name}
593 * of the class
594 * @return {@code Class} object of the given name defined in the given module;
595 * {@code null} if not found.
596 *
597 * @throws LinkageError if the linkage fails
598 *
599 * @jls 12.2 Loading of Classes and Interfaces
600 * @jls 12.3 Linking of Classes and Interfaces
601 * @since 9
602 */
603 public static Class<?> forName(Module module, String name) {
604 Objects.requireNonNull(module);
605 Objects.requireNonNull(name);
606 if (!ModifiedUtf.isValidLengthInConstantPool(name)) {
607 return null;
608 }
609
610 ClassLoader cl = module.getClassLoader();
611 if (cl != null) {
612 return cl.loadClass(module, name);
613 } else {
614 return BootLoader.loadClass(module, name);
615 }
616 }
617
618 /**
619 * {@return the {@code Class} object associated with the
620 * {@linkplain #isPrimitive() primitive type} of the given name}
621 * If the argument is not the name of a primitive type, {@code
622 * null} is returned.
623 *
624 * @param primitiveName the name of the primitive type to find
625 *
626 * @jls 4.2 Primitive Types and Values
627 * @jls 15.8.2 Class Literals
628 * @since 22
629 */
630 public static Class<?> forPrimitiveName(String primitiveName) {
631 return switch(primitiveName) {
632 // Integral types
633 case "int" -> int.class;
634 case "long" -> long.class;
635 case "short" -> short.class;
636 case "char" -> char.class;
637 case "byte" -> byte.class;
638
639 // Floating-point types
640 case "float" -> float.class;
641 case "double" -> double.class;
642
643 // Other types
644 case "boolean" -> boolean.class;
645 case "void" -> void.class;
646
647 default -> null;
648 };
649 }
650
651 /**
652 * Creates a new instance of the class represented by this {@code Class}
653 * object. The class is instantiated as if by a {@code new}
654 * expression with an empty argument list. The class is initialized if it
655 * has not already been initialized.
656 *
657 * @deprecated This method propagates any exception thrown by the
658 * nullary constructor, including a checked exception. Use of
659 * this method effectively bypasses the compile-time exception
660 * checking that would otherwise be performed by the compiler.
661 * The {@link
662 * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
663 * Constructor.newInstance} method avoids this problem by wrapping
664 * any exception thrown by the constructor in a (checked) {@link
665 * java.lang.reflect.InvocationTargetException}.
666 *
667 * <p>The call
668 *
669 * {@snippet lang="java" :
670 * clazz.newInstance()
671 * }
672 *
673 * can be replaced by
674 *
675 * {@snippet lang="java" :
676 * clazz.getDeclaredConstructor().newInstance()
677 * }
678 *
679 * The latter sequence of calls is inferred to be able to throw
680 * the additional exception types {@link
681 * InvocationTargetException} and {@link
682 * NoSuchMethodException}. Both of these exception types are
683 * subclasses of {@link ReflectiveOperationException}.
684 *
685 * @return a newly allocated instance of the class represented by this
686 * object.
687 * @throws IllegalAccessException if the class or its nullary
688 * constructor is not accessible.
689 * @throws InstantiationException
690 * if this {@code Class} represents an abstract class,
691 * an interface, an array class, a primitive type, or void;
692 * or if the class has no nullary constructor;
693 * or if the instantiation fails for some other reason.
694 * @throws ExceptionInInitializerError if the initialization
695 * provoked by this method fails.
696 */
697 @CallerSensitive
698 @Deprecated(since="9")
699 public T newInstance()
700 throws InstantiationException, IllegalAccessException
701 {
702 // Constructor lookup
703 Constructor<T> tmpConstructor = cachedConstructor;
704 if (tmpConstructor == null) {
705 if (this == Class.class) {
706 throw new IllegalAccessException(
707 "Can not call newInstance() on the Class for java.lang.Class"
708 );
709 }
710 try {
711 Class<?>[] empty = {};
712 final Constructor<T> c = getReflectionFactory().copyConstructor(
713 getConstructor0(empty, Member.DECLARED));
714 // Disable accessibility checks on the constructor
715 // access check is done with the true caller
716 c.setAccessible(true);
717 cachedConstructor = tmpConstructor = c;
718 } catch (NoSuchMethodException e) {
719 throw (InstantiationException)
720 new InstantiationException(getName()).initCause(e);
721 }
722 }
723
724 try {
725 Class<?> caller = Reflection.getCallerClass();
726 return getReflectionFactory().newInstance(tmpConstructor, null, caller);
727 } catch (InvocationTargetException e) {
728 Unsafe.getUnsafe().throwException(e.getTargetException());
729 // Not reached
730 return null;
731 }
732 }
733
734 private transient volatile Constructor<T> cachedConstructor;
735
736 /**
737 * Determines if the specified {@code Object} is assignment-compatible
738 * with the object represented by this {@code Class}. This method is
739 * the dynamic equivalent of the Java language {@code instanceof}
740 * operator. The method returns {@code true} if the specified
741 * {@code Object} argument is non-null and can be cast to the
742 * reference type represented by this {@code Class} object without
743 * raising a {@code ClassCastException.} It returns {@code false}
744 * otherwise.
745 *
746 * <p> Specifically, if this {@code Class} object represents a
747 * declared class, this method returns {@code true} if the specified
748 * {@code Object} argument is an instance of the represented class (or
749 * of any of its subclasses); it returns {@code false} otherwise. If
750 * this {@code Class} object represents an array class, this method
751 * returns {@code true} if the specified {@code Object} argument
752 * can be converted to an object of the array class by an identity
753 * conversion or by a widening reference conversion; it returns
754 * {@code false} otherwise. If this {@code Class} object
755 * represents an interface, this method returns {@code true} if the
756 * class or any superclass of the specified {@code Object} argument
757 * implements this interface; it returns {@code false} otherwise. If
758 * this {@code Class} object represents a primitive type, this method
759 * returns {@code false}.
760 *
761 * @param obj the object to check, may be {@code null}
762 * @return true if {@code obj} is an instance of this class
763 *
764 * @since 1.1
765 */
766 @IntrinsicCandidate
767 public native boolean isInstance(Object obj);
768
769
770 /**
771 * Determines if the class or interface represented by this
772 * {@code Class} object is either the same as, or is a superclass or
773 * superinterface of, the class or interface represented by the specified
774 * {@code Class} parameter. It returns {@code true} if so;
775 * otherwise it returns {@code false}. If this {@code Class}
776 * object represents a primitive type, this method returns
777 * {@code true} if the specified {@code Class} parameter is
778 * exactly this {@code Class} object; otherwise it returns
779 * {@code false}.
780 *
781 * <p> Specifically, this method tests whether the type represented by the
782 * specified {@code Class} parameter can be converted to the type
783 * represented by this {@code Class} object via an identity conversion
784 * or via a widening reference conversion. See <cite>The Java Language
785 * Specification</cite>, sections {@jls 5.1.1} and {@jls 5.1.4},
786 * for details.
787 *
788 * @param cls the {@code Class} object to be checked
789 * @return the {@code boolean} value indicating whether objects of the
790 * type {@code cls} can be assigned to objects of this class
791 * @since 1.1
792 */
793 @IntrinsicCandidate
794 public native boolean isAssignableFrom(Class<?> cls);
795
796
797 /**
798 * Determines if this {@code Class} object represents an
799 * interface type.
800 *
801 * @return {@code true} if this {@code Class} object represents an interface;
802 * {@code false} otherwise.
803 */
804 public boolean isInterface() {
805 return Modifier.isInterface(modifiers);
806 }
807
808
809 /**
810 * Determines if this {@code Class} object represents an array class.
811 *
812 * @return {@code true} if this {@code Class} object represents an array class;
813 * {@code false} otherwise.
814 * @since 1.1
815 */
816 public boolean isArray() {
817 return componentType != null;
818 }
819
820
821 /**
822 * Determines if this {@code Class} object represents a primitive
823 * type or void.
824 *
825 * <p> There are nine predefined {@code Class} objects to
826 * represent the eight primitive types and void. These are
827 * created by the Java Virtual Machine, and have the same
828 * {@linkplain #getName() names} as the primitive types that they
829 * represent, namely {@code boolean}, {@code byte}, {@code char},
830 * {@code short}, {@code int}, {@code long}, {@code float}, and
831 * {@code double}.
832 *
833 * <p>No other class objects are considered primitive.
834 *
835 * @apiNote
836 * A {@code Class} object represented by a primitive type can be
837 * accessed via the {@code TYPE} public static final variables
838 * defined in the primitive wrapper classes such as {@link
839 * java.lang.Integer#TYPE Integer.TYPE}. In the Java programming
840 * language, the objects may be referred to by a class literal
841 * expression such as {@code int.class}. The {@code Class} object
842 * for void can be expressed as {@code void.class} or {@link
843 * java.lang.Void#TYPE Void.TYPE}.
844 *
845 * @return true if and only if this class represents a primitive type
846 *
847 * @see java.lang.Boolean#TYPE
848 * @see java.lang.Character#TYPE
849 * @see java.lang.Byte#TYPE
850 * @see java.lang.Short#TYPE
851 * @see java.lang.Integer#TYPE
852 * @see java.lang.Long#TYPE
853 * @see java.lang.Float#TYPE
854 * @see java.lang.Double#TYPE
855 * @see java.lang.Void#TYPE
856 * @since 1.1
857 * @jls 15.8.2 Class Literals
858 */
859 public boolean isPrimitive() {
860 return primitive;
861 }
862
863 /**
864 * Returns true if this {@code Class} object represents an annotation
865 * interface. Note that if this method returns true, {@link #isInterface()}
866 * would also return true, as all annotation interfaces are also interfaces.
867 *
868 * @return {@code true} if this {@code Class} object represents an annotation
869 * interface; {@code false} otherwise
870 * @since 1.5
871 */
872 public boolean isAnnotation() {
873 return (getModifiers() & ANNOTATION) != 0;
874 }
875
876 /**
877 *{@return {@code true} if and only if this class has the synthetic modifier
878 * bit set}
879 *
880 * @jls 13.1 The Form of a Binary
881 * @jvms 4.1 The {@code ClassFile} Structure
882 * @see <a
883 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
884 * programming language and JVM modeling in core reflection</a>
885 * @since 1.5
886 */
887 public boolean isSynthetic() {
888 return (getModifiers() & SYNTHETIC) != 0;
889 }
890
891 /**
892 * Returns the name of the entity (class, interface, array class,
893 * primitive type, or void) represented by this {@code Class} object.
894 *
895 * <p> If this {@code Class} object represents a class or interface,
896 * not an array class, then:
897 * <ul>
898 * <li> If the class or interface is not {@linkplain #isHidden() hidden},
899 * then the {@linkplain ClassLoader##binary-name binary name}
900 * of the class or interface is returned.
901 * <li> If the class or interface is hidden, then the result is a string
902 * of the form: {@code N + '/' + <suffix>}
903 * where {@code N} is the {@linkplain ClassLoader##binary-name binary name}
904 * indicated by the {@code class} file passed to
905 * {@link java.lang.invoke.MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
906 * Lookup::defineHiddenClass}, and {@code <suffix>} is an unqualified name.
907 * </ul>
908 *
909 * <p> If this {@code Class} object represents an array class, then
910 * the result is a string consisting of one or more '{@code [}' characters
911 * representing the depth of the array nesting, followed by the element
912 * type as encoded using the following table:
913 *
914 * <blockquote><table class="striped" id="nameFormat">
915 * <caption style="display:none">Element types and encodings</caption>
916 * <thead>
917 * <tr><th scope="col"> Element Type <th scope="col"> Encoding
918 * </thead>
919 * <tbody style="text-align:left">
920 * <tr><th scope="row"> {@code boolean} <td style="text-align:center"> {@code Z}
921 * <tr><th scope="row"> {@code byte} <td style="text-align:center"> {@code B}
922 * <tr><th scope="row"> {@code char} <td style="text-align:center"> {@code C}
923 * <tr><th scope="row"> class or interface with {@linkplain ClassLoader##binary-name binary name} <i>N</i>
924 * <td style="text-align:center"> {@code L}<em>N</em>{@code ;}
925 * <tr><th scope="row"> {@code double} <td style="text-align:center"> {@code D}
926 * <tr><th scope="row"> {@code float} <td style="text-align:center"> {@code F}
927 * <tr><th scope="row"> {@code int} <td style="text-align:center"> {@code I}
928 * <tr><th scope="row"> {@code long} <td style="text-align:center"> {@code J}
929 * <tr><th scope="row"> {@code short} <td style="text-align:center"> {@code S}
930 * </tbody>
931 * </table></blockquote>
932 *
933 * <p> If this {@code Class} object represents a primitive type or {@code void},
934 * then the result is a string with the same spelling as the Java language
935 * keyword which corresponds to the primitive type or {@code void}.
936 *
937 * <p> Examples:
938 * <blockquote><pre>
939 * String.class.getName()
940 * returns "java.lang.String"
941 * Character.UnicodeBlock.class.getName()
942 * returns "java.lang.Character$UnicodeBlock"
943 * byte.class.getName()
944 * returns "byte"
945 * (new Object[3]).getClass().getName()
946 * returns "[Ljava.lang.Object;"
947 * (new int[3][4][5][6][7][8][9]).getClass().getName()
948 * returns "[[[[[[[I"
949 * </pre></blockquote>
950 *
951 * @apiNote
952 * Distinct class objects can have the same name but different class loaders.
953 *
954 * @return the name of the class, interface, or other entity
955 * represented by this {@code Class} object.
956 * @jls 13.1 The Form of a Binary
957 */
958 public String getName() {
959 String name = this.name;
960 return name != null ? name : initClassName();
961 }
962
963 // Cache the name to reduce the number of calls into the VM.
964 // This field would be set by VM itself during initClassName call.
965 private transient String name;
966 private native String initClassName();
967
968 /**
969 * Returns the class loader for the class. Some implementations may use
970 * null to represent the bootstrap class loader. This method will return
971 * null in such implementations if this class was loaded by the bootstrap
972 * class loader.
973 *
974 * <p>If this {@code Class} object
975 * represents a primitive type or void, null is returned.
976 *
977 * @return the class loader that loaded the class or interface
978 * represented by this {@code Class} object.
979 * @see java.lang.ClassLoader
980 */
981 public ClassLoader getClassLoader() {
982 return classLoader;
983 }
984
985 // Package-private to allow ClassLoader access
986 ClassLoader getClassLoader0() { return classLoader; }
987
988 /**
989 * Returns the module that this class or interface is a member of.
990 *
991 * If this class represents an array type then this method returns the
992 * {@code Module} for the element type. If this class represents a
993 * primitive type or void, then the {@code Module} object for the
994 * {@code java.base} module is returned.
995 *
996 * If this class is in an unnamed module then the {@linkplain
997 * ClassLoader#getUnnamedModule() unnamed} {@code Module} of the class
998 * loader for this class is returned.
999 *
1000 * @return the module that this class or interface is a member of
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
1042 */
1043 @SuppressWarnings("unchecked")
1044 public TypeVariable<Class<T>>[] getTypeParameters() {
1045 ClassRepository info = getGenericInfo();
1046 if (info != null)
1047 return (TypeVariable<Class<T>>[])info.getTypeParameters();
1048 else
1049 return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];
1050 }
1051
1052
1053 /**
1054 * Returns the {@code Class} representing the direct superclass of the
1055 * entity (class, interface, primitive type or void) represented by
1056 * this {@code Class}. If this {@code Class} represents either the
1057 * {@code Object} class, an interface, a primitive type, or void, then
1058 * null is returned. If this {@code Class} object represents an array class
1059 * then the {@code Class} object representing the {@code Object} class is
1060 * returned.
1061 *
1062 * @return the direct superclass of the class represented by this {@code Class} object
1063 */
1064 @IntrinsicCandidate
1065 public native Class<? super T> getSuperclass();
1066
1067
1068 /**
1069 * Returns the {@code Type} representing the direct superclass of
1070 * the entity (class, interface, primitive type or void) represented by
1071 * this {@code Class} object.
1072 *
1073 * <p>If the superclass is a parameterized type, the {@code Type}
1074 * object returned must accurately reflect the actual type
1075 * arguments used in the source code. The parameterized type
1076 * representing the superclass is created if it had not been
1077 * created before. See the declaration of {@link
1078 * java.lang.reflect.ParameterizedType ParameterizedType} for the
1079 * semantics of the creation process for parameterized types. If
1080 * this {@code Class} object represents either the {@code Object}
1081 * class, an interface, a primitive type, or void, then null is
1082 * returned. If this {@code Class} object represents an array class
1083 * then the {@code Class} object representing the {@code Object} class is
1084 * returned.
1085 *
1086 * @throws java.lang.reflect.GenericSignatureFormatError if the generic
1087 * class signature does not conform to the format specified in
1088 * section {@jvms 4.7.9} of <cite>The Java Virtual
1089 * Machine Specification</cite>
1090 * @throws TypeNotPresentException if the generic superclass
1091 * refers to a non-existent type declaration
1092 * @throws java.lang.reflect.MalformedParameterizedTypeException if the
1093 * generic superclass refers to a parameterized type that cannot be
1094 * instantiated for any reason
1095 * @return the direct superclass of the class represented by this {@code Class} object
1096 * @since 1.5
1097 */
1098 public Type getGenericSuperclass() {
1099 ClassRepository info = getGenericInfo();
1100 if (info == null) {
1101 return getSuperclass();
1102 }
1103
1104 // Historical irregularity:
1105 // Generic signature marks interfaces with superclass = Object
1106 // but this API returns null for interfaces
1107 if (isInterface()) {
1108 return null;
1109 }
1110
1111 return info.getSuperclass();
1112 }
1113
1114 /**
1115 * Gets the package of this class.
1116 *
1117 * <p>If this class represents an array type, a primitive type or void,
1118 * this method returns {@code null}.
1119 *
1120 * @return the package of this class.
1121 */
1122 public Package getPackage() {
1123 if (isPrimitive() || isArray()) {
1124 return null;
1125 }
1126 ClassLoader cl = classLoader;
1127 return cl != null ? cl.definePackage(this)
1128 : BootLoader.definePackage(this);
1129 }
1130
1131 /**
1132 * Returns the fully qualified package name.
1133 *
1134 * <p> If this class is a top level class, then this method returns the fully
1135 * qualified name of the package that the class is a member of, or the
1136 * empty string if the class is in an unnamed package.
1137 *
1138 * <p> If this class is a member class, then this method is equivalent to
1139 * invoking {@code getPackageName()} on the {@linkplain #getEnclosingClass
1140 * enclosing class}.
1141 *
1142 * <p> If this class is a {@linkplain #isLocalClass local class} or an {@linkplain
1143 * #isAnonymousClass() anonymous class}, then this method is equivalent to
1144 * invoking {@code getPackageName()} on the {@linkplain #getDeclaringClass
1145 * declaring class} of the {@linkplain #getEnclosingMethod enclosing method} or
1146 * {@linkplain #getEnclosingConstructor enclosing constructor}.
1147 *
1148 * <p> If this class represents an array type then this method returns the
1149 * package name of the element type. If this class represents a primitive
1150 * type or void then the package name "{@code java.lang}" is returned.
1151 *
1152 * @return the fully qualified package name
1153 *
1154 * @since 9
1155 * @jls 6.7 Fully Qualified Names and Canonical Names
1156 */
1157 public String getPackageName() {
1158 String pn = this.packageName;
1159 if (pn == null) {
1160 Class<?> c = isArray() ? elementType() : this;
1161 if (c.isPrimitive()) {
1162 pn = "java.lang";
1163 } else {
1164 String cn = c.getName();
1165 int dot = cn.lastIndexOf('.');
1166 pn = (dot != -1) ? cn.substring(0, dot).intern() : "";
1167 }
1168 this.packageName = pn;
1169 }
1170 return pn;
1171 }
1172
1173 // cached package name
1174 private transient String packageName;
1175
1176 /**
1177 * Returns the interfaces directly implemented by the class or interface
1178 * represented by this {@code Class} object.
1179 *
1180 * <p>If this {@code Class} object represents a class, the return value is an array
1181 * containing objects representing all interfaces directly implemented by
1182 * the class. The order of the interface objects in the array corresponds
1183 * to the order of the interface names in the {@code implements} clause of
1184 * the declaration of the class represented by this {@code Class} object. For example,
1185 * given the declaration:
1186 * <blockquote>
1187 * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
1188 * </blockquote>
1189 * suppose the value of {@code s} is an instance of
1190 * {@code Shimmer}; the value of the expression:
1191 * <blockquote>
1192 * {@code s.getClass().getInterfaces()[0]}
1193 * </blockquote>
1194 * is the {@code Class} object that represents interface
1195 * {@code FloorWax}; and the value of:
1196 * <blockquote>
1197 * {@code s.getClass().getInterfaces()[1]}
1198 * </blockquote>
1199 * is the {@code Class} object that represents interface
1200 * {@code DessertTopping}.
1201 *
1202 * <p>If this {@code Class} object represents an interface, the array contains objects
1203 * representing all interfaces directly extended by the interface. The
1204 * order of the interface objects in the array corresponds to the order of
1205 * the interface names in the {@code extends} clause of the declaration of
1206 * the interface represented by this {@code Class} object.
1207 *
1208 * <p>If this {@code Class} object represents a class or interface that implements no
1209 * interfaces, the method returns an array of length 0.
1210 *
1211 * <p>If this {@code Class} object represents a primitive type or void, the method
1212 * returns an array of length 0.
1213 *
1214 * <p>If this {@code Class} object represents an array type, the
1215 * interfaces {@code Cloneable} and {@code java.io.Serializable} are
1216 * returned in that order.
1217 *
1218 * @return an array of interfaces directly implemented by this class
1219 */
1220 public Class<?>[] getInterfaces() {
1221 // defensively copy before handing over to user code
1222 return getInterfaces(true);
1223 }
1224
1225 private Class<?>[] getInterfaces(boolean cloneArray) {
1226 ReflectionData<T> rd = reflectionData();
1227 Class<?>[] interfaces = rd.interfaces;
1228 if (interfaces == null) {
1229 interfaces = getInterfaces0();
1230 rd.interfaces = interfaces;
1231 }
1232 // defensively copy if requested
1233 return cloneArray ? interfaces.clone() : interfaces;
1234 }
1235
1236 private native Class<?>[] getInterfaces0();
1237
1238 /**
1239 * Returns the {@code Type}s representing the interfaces
1240 * directly implemented by the class or interface represented by
1241 * this {@code Class} object.
1242 *
1243 * <p>If a superinterface is a parameterized type, the
1244 * {@code Type} object returned for it must accurately reflect
1245 * the actual type arguments used in the source code. The
1246 * parameterized type representing each superinterface is created
1247 * if it had not been created before. See the declaration of
1248 * {@link java.lang.reflect.ParameterizedType ParameterizedType}
1249 * for the semantics of the creation process for parameterized
1250 * types.
1251 *
1252 * <p>If this {@code Class} object represents a class, the return value is an array
1253 * containing objects representing all interfaces directly implemented by
1254 * the class. The order of the interface objects in the array corresponds
1255 * to the order of the interface names in the {@code implements} clause of
1256 * the declaration of the class represented by this {@code Class} object.
1257 *
1258 * <p>If this {@code Class} object represents an interface, the array contains objects
1259 * representing all interfaces directly extended by the interface. The
1260 * order of the interface objects in the array corresponds to the order of
1261 * the interface names in the {@code extends} clause of the declaration of
1262 * the interface represented by this {@code Class} object.
1263 *
1264 * <p>If this {@code Class} object represents a class or interface that implements no
1265 * interfaces, the method returns an array of length 0.
1266 *
1267 * <p>If this {@code Class} object represents a primitive type or void, the method
1268 * returns an array of length 0.
1269 *
1270 * <p>If this {@code Class} object represents an array type, the
1271 * interfaces {@code Cloneable} and {@code java.io.Serializable} are
1272 * returned in that order.
1273 *
1274 * @throws java.lang.reflect.GenericSignatureFormatError
1275 * if the generic class signature does not conform to the
1276 * format specified in section {@jvms 4.7.9} of <cite>The
1277 * Java Virtual Machine Specification</cite>
1278 * @throws TypeNotPresentException if any of the generic
1279 * superinterfaces refers to a non-existent type declaration
1280 * @throws java.lang.reflect.MalformedParameterizedTypeException
1281 * if any of the generic superinterfaces refer to a parameterized
1282 * type that cannot be instantiated for any reason
1283 * @return an array of interfaces directly implemented by this class
1284 * @since 1.5
1285 */
1286 public Type[] getGenericInterfaces() {
1287 ClassRepository info = getGenericInfo();
1288 return (info == null) ? getInterfaces() : info.getSuperInterfaces();
1289 }
1290
1291
1292 /**
1293 * Returns the {@code Class} representing the component type of an
1294 * array. If this class does not represent an array class this method
1295 * returns null.
1296 *
1297 * @return the {@code Class} representing the component type of this
1298 * class if this class is an array
1299 * @see java.lang.reflect.Array
1300 * @since 1.1
1301 */
1302 public Class<?> getComponentType() {
1303 return componentType;
1304 }
1305
1306 // The componentType field's null value is the sole indication that the class
1307 // is an array - see isArray().
1308 private transient final Class<?> componentType;
1309
1310 /*
1311 * Returns the {@code Class} representing the element type of an array class.
1312 * If this class does not represent an array class, then this method returns
1313 * {@code null}.
1314 */
1315 private Class<?> elementType() {
1316 if (!isArray()) return null;
1317
1318 Class<?> c = this;
1319 while (c.isArray()) {
1320 c = c.getComponentType();
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 // Arrays need to use PRIVATE/PROTECTED from its component modifiers.
1394 var location = (isMemberClass() || isLocalClass() ||
1395 isAnonymousClass() || isArray()) ?
1396 AccessFlag.Location.INNER_CLASS :
1397 AccessFlag.Location.CLASS;
1398 return getReflectionFactory().parseAccessFlags((location == AccessFlag.Location.CLASS) ?
1399 getClassFileAccessFlags() : getModifiers(), location, this);
1400 }
1401
1402 /**
1403 * Gets the signers of this class.
1404 *
1405 * @return the signers of this class, or null if there are no signers. In
1406 * particular, this method returns null if this {@code Class} object represents
1407 * a primitive type or void.
1408 * @since 1.1
1409 */
1410 public Object[] getSigners() {
1411 var signers = this.signers;
1412 return signers == null ? null : signers.clone();
1413 }
1414
1415 /**
1416 * Set the signers of this class.
1417 */
1418 void setSigners(Object[] signers) {
1419 if (!isPrimitive() && !isArray()) {
1420 this.signers = signers;
1421 }
1422 }
1423
1424 /**
1425 * If this {@code Class} object represents a local or anonymous
1426 * class within a method, returns a {@link
1427 * java.lang.reflect.Method Method} object representing the
1428 * immediately enclosing method of the underlying class. Returns
1429 * {@code null} otherwise.
1430 *
1431 * In particular, this method returns {@code null} if the underlying
1432 * class is a local or anonymous class immediately enclosed by a class or
1433 * interface declaration, instance initializer or static initializer.
1434 *
1435 * @return the immediately enclosing method of the underlying class, if
1436 * that class is a local or anonymous class; otherwise {@code null}.
1437 *
1438 * @since 1.5
1439 */
1440 public Method getEnclosingMethod() {
1441 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1442
1443 if (enclosingInfo == null)
1444 return null;
1445 else {
1446 if (!enclosingInfo.isMethod())
1447 return null;
1448
1449 List<Class<?>> types = BytecodeDescriptor.parseMethod(enclosingInfo.getDescriptor(), getClassLoader());
1450 Class<?> returnType = types.removeLast();
1451 Class<?>[] parameterClasses = types.toArray(EMPTY_CLASS_ARRAY);
1452
1453 final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1454 Method[] candidates = enclosingCandidate.privateGetDeclaredMethods(false);
1455
1456 /*
1457 * Loop over all declared methods; match method name,
1458 * number of and type of parameters, *and* return
1459 * type. Matching return type is also necessary
1460 * because of covariant returns, etc.
1461 */
1462 ReflectionFactory fact = getReflectionFactory();
1463 for (Method m : candidates) {
1464 if (m.getName().equals(enclosingInfo.getName()) &&
1465 arrayContentsEq(parameterClasses,
1466 fact.getExecutableSharedParameterTypes(m))) {
1467 // finally, check return type
1468 if (m.getReturnType().equals(returnType)) {
1469 return fact.copyMethod(m);
1470 }
1471 }
1472 }
1473
1474 throw new InternalError("Enclosing method not found");
1475 }
1476 }
1477
1478 private native Object[] getEnclosingMethod0();
1479
1480 private EnclosingMethodInfo getEnclosingMethodInfo() {
1481 Object[] enclosingInfo = getEnclosingMethod0();
1482 if (enclosingInfo == null)
1483 return null;
1484 else {
1485 return new EnclosingMethodInfo(enclosingInfo);
1486 }
1487 }
1488
1489 private static final class EnclosingMethodInfo {
1490 private final Class<?> enclosingClass;
1491 private final String name;
1492 private final String descriptor;
1493
1494 static void validate(Object[] enclosingInfo) {
1495 if (enclosingInfo.length != 3)
1496 throw new InternalError("Malformed enclosing method information");
1497 try {
1498 // The array is expected to have three elements:
1499
1500 // the immediately enclosing class
1501 Class<?> enclosingClass = (Class<?>)enclosingInfo[0];
1502 assert(enclosingClass != null);
1503
1504 // the immediately enclosing method or constructor's
1505 // name (can be null).
1506 String name = (String)enclosingInfo[1];
1507
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() {
1537 // hotspot validates this descriptor to be either a field or method
1538 // descriptor as the "type" in a NameAndType in verification.
1539 // So this can still be a field descriptor
1540 if (descriptor.isEmpty() || descriptor.charAt(0) != '(') {
1541 throw new GenericSignatureFormatError("Bad method signature: " + descriptor);
1542 }
1543 return descriptor;
1544 }
1545 }
1546
1547 private static Class<?> toClass(Type o) {
1548 if (o instanceof GenericArrayType gat)
1549 return toClass(gat.getGenericComponentType()).arrayType();
1550 return (Class<?>)o;
1551 }
1552
1553 /**
1554 * If this {@code Class} object represents a local or anonymous
1555 * class within a constructor, returns a {@link
1556 * java.lang.reflect.Constructor Constructor} object representing
1557 * the immediately enclosing constructor of the underlying
1558 * class. Returns {@code null} otherwise. In particular, this
1559 * method returns {@code null} if the underlying class is a local
1560 * or anonymous class immediately enclosed by a class or
1561 * interface declaration, instance initializer or static initializer.
1562 *
1563 * @return the immediately enclosing constructor of the underlying class, if
1564 * that class is a local or anonymous class; otherwise {@code null}.
1565 *
1566 * @since 1.5
1567 */
1568 public Constructor<?> getEnclosingConstructor() {
1569 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1570
1571 if (enclosingInfo == null)
1572 return null;
1573 else {
1574 if (!enclosingInfo.isConstructor())
1575 return null;
1576
1577 List<Class<?>> types = BytecodeDescriptor.parseMethod(enclosingInfo.getDescriptor(), getClassLoader());
1578 types.removeLast();
1579 Class<?>[] parameterClasses = types.toArray(EMPTY_CLASS_ARRAY);
1580
1581 final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1582 Constructor<?>[] candidates = enclosingCandidate
1583 .privateGetDeclaredConstructors(false);
1584 /*
1585 * Loop over all declared constructors; match number
1586 * of and type of parameters.
1587 */
1588 ReflectionFactory fact = getReflectionFactory();
1589 for (Constructor<?> c : candidates) {
1590 if (arrayContentsEq(parameterClasses,
1591 fact.getExecutableSharedParameterTypes(c))) {
1592 return fact.copyConstructor(c);
1593 }
1594 }
1595
1596 throw new InternalError("Enclosing constructor not found");
1597 }
1598 }
1599
1600
1601 /**
1602 * If the class or interface represented by this {@code Class} object
1603 * is a member of another class, returns the {@code Class} object
1604 * representing the class in which it was declared. This method returns
1605 * null if this class or interface is not a member of any other class. If
1606 * this {@code Class} object represents an array class, a primitive
1607 * type, or void, then this method returns null.
1608 *
1609 * @return the declaring class for this class
1610 * @since 1.1
1611 */
1612 public Class<?> getDeclaringClass() {
1613 return getDeclaringClass0();
1614 }
1615
1616 private native Class<?> getDeclaringClass0();
1617
1618
1619 /**
1620 * Returns the immediately enclosing class of the underlying
1621 * class. If the underlying class is a top level class this
1622 * method returns {@code null}.
1623 * @return the immediately enclosing class of the underlying class
1624 * @since 1.5
1625 */
1626 public Class<?> getEnclosingClass() {
1627 // There are five kinds of classes (or interfaces):
1628 // a) Top level classes
1629 // b) Nested classes (static member classes)
1630 // c) Inner classes (non-static member classes)
1631 // d) Local classes (named classes declared within a method)
1632 // e) Anonymous classes
1633
1634
1635 // JVM Spec 4.7.7: A class must have an EnclosingMethod
1636 // attribute if and only if it is a local class or an
1637 // anonymous class.
1638 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1639 Class<?> enclosingCandidate;
1640
1641 if (enclosingInfo == null) {
1642 // This is a top level or a nested class or an inner class (a, b, or c)
1643 enclosingCandidate = getDeclaringClass0();
1644 } else {
1645 Class<?> enclosingClass = enclosingInfo.getEnclosingClass();
1646 // This is a local class or an anonymous class (d or e)
1647 if (enclosingClass == this || enclosingClass == null)
1648 throw new InternalError("Malformed enclosing method information");
1649 else
1650 enclosingCandidate = enclosingClass;
1651 }
1652 return enclosingCandidate;
1653 }
1654
1655 /**
1656 * Returns the simple name of the underlying class as given in the
1657 * source code. An empty string is returned if the underlying class is
1658 * {@linkplain #isAnonymousClass() anonymous}.
1659 * A {@linkplain #isSynthetic() synthetic class}, one not present
1660 * in source code, can have a non-empty name including special
1661 * characters, such as "{@code $}".
1662 *
1663 * <p>The simple name of an {@linkplain #isArray() array class} is the simple name of the
1664 * component type with "[]" appended. In particular the simple
1665 * name of an array class whose component type is anonymous is "[]".
1666 *
1667 * @return the simple name of the underlying class
1668 * @since 1.5
1669 */
1670 public String getSimpleName() {
1671 ReflectionData<T> rd = reflectionData();
1672 String simpleName = rd.simpleName;
1673 if (simpleName == null) {
1674 rd.simpleName = simpleName = getSimpleName0();
1675 }
1676 return simpleName;
1677 }
1678
1679 private String getSimpleName0() {
1680 if (isArray()) {
1681 return getComponentType().getSimpleName().concat("[]");
1682 }
1683 String simpleName = getSimpleBinaryName();
1684 if (simpleName == null) { // top level class
1685 simpleName = getName();
1686 simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1687 }
1688 return simpleName;
1689 }
1690
1691 /**
1692 * Return an informative string for the name of this class or interface.
1693 *
1694 * @return an informative string for the name of this class or interface
1695 * @since 1.8
1696 */
1697 public String getTypeName() {
1698 if (isArray()) {
1699 try {
1700 Class<?> cl = this;
1701 int dimensions = 0;
1702 do {
1703 dimensions++;
1704 cl = cl.getComponentType();
1705 } while (cl.isArray());
1706 return cl.getName().concat("[]".repeat(dimensions));
1707 } catch (Throwable e) { /*FALLTHRU*/ }
1708 }
1709 return getName();
1710 }
1711
1712 /**
1713 * Returns the canonical name of the underlying class as
1714 * defined by <cite>The Java Language Specification</cite>.
1715 * Returns {@code null} if the underlying class does not have a canonical
1716 * name. Classes without canonical names include:
1717 * <ul>
1718 * <li>a {@linkplain #isLocalClass() local class}
1719 * <li>a {@linkplain #isAnonymousClass() anonymous class}
1720 * <li>a {@linkplain #isHidden() hidden class}
1721 * <li>an array whose component type does not have a canonical name</li>
1722 * </ul>
1723 *
1724 * The canonical name for a primitive class is the keyword for the
1725 * corresponding primitive type ({@code byte}, {@code short},
1726 * {@code char}, {@code int}, and so on).
1727 *
1728 * <p>An array type has a canonical name if and only if its
1729 * component type has a canonical name. When an array type has a
1730 * canonical name, it is equal to the canonical name of the
1731 * component type followed by "{@code []}".
1732 *
1733 * @return the canonical name of the underlying class if it exists, and
1734 * {@code null} otherwise.
1735 * @jls 6.7 Fully Qualified Names and Canonical Names
1736 * @since 1.5
1737 */
1738 public String getCanonicalName() {
1739 ReflectionData<T> rd = reflectionData();
1740 String canonicalName = rd.canonicalName;
1741 if (canonicalName == null) {
1742 rd.canonicalName = canonicalName = getCanonicalName0();
1743 }
1744 return canonicalName == ReflectionData.NULL_SENTINEL? null : canonicalName;
1745 }
1746
1747 private String getCanonicalName0() {
1748 if (isArray()) {
1749 String canonicalName = getComponentType().getCanonicalName();
1750 if (canonicalName != null)
1751 return canonicalName.concat("[]");
1752 else
1753 return ReflectionData.NULL_SENTINEL;
1754 }
1755 if (isHidden() || isLocalOrAnonymousClass())
1756 return ReflectionData.NULL_SENTINEL;
1757 Class<?> enclosingClass = getEnclosingClass();
1758 if (enclosingClass == null) { // top level class
1759 return getName();
1760 } else {
1761 String enclosingName = enclosingClass.getCanonicalName();
1762 if (enclosingName == null)
1763 return ReflectionData.NULL_SENTINEL;
1764 String simpleName = getSimpleName();
1765 return new StringBuilder(enclosingName.length() + simpleName.length() + 1)
1766 .append(enclosingName)
1767 .append('.')
1768 .append(simpleName)
1769 .toString();
1770 }
1771 }
1772
1773 /**
1774 * Returns {@code true} if and only if the underlying class
1775 * is an anonymous class.
1776 *
1777 * @apiNote
1778 * An anonymous class is not a {@linkplain #isHidden() hidden class}.
1779 *
1780 * @return {@code true} if and only if this class is an anonymous class.
1781 * @since 1.5
1782 * @jls 15.9.5 Anonymous Class Declarations
1783 */
1784 public boolean isAnonymousClass() {
1785 return !isArray() && isLocalOrAnonymousClass() &&
1786 getSimpleBinaryName0() == null;
1787 }
1788
1789 /**
1790 * Returns {@code true} if and only if the underlying class
1791 * is a local class.
1792 *
1793 * @return {@code true} if and only if this class is a local class.
1794 * @since 1.5
1795 * @jls 14.3 Local Class and Interface Declarations
1796 */
1797 public boolean isLocalClass() {
1798 return isLocalOrAnonymousClass() &&
1799 (isArray() || getSimpleBinaryName0() != null);
1800 }
1801
1802 /**
1803 * Returns {@code true} if and only if the underlying class
1804 * is a member class.
1805 *
1806 * @return {@code true} if and only if this class is a member class.
1807 * @since 1.5
1808 * @jls 8.5 Member Class and Interface Declarations
1809 */
1810 public boolean isMemberClass() {
1811 return !isLocalOrAnonymousClass() && getDeclaringClass0() != null;
1812 }
1813
1814 /**
1815 * Returns the "simple binary name" of the underlying class, i.e.,
1816 * the binary name without the leading enclosing class name.
1817 * Returns {@code null} if the underlying class is a top level
1818 * class.
1819 */
1820 private String getSimpleBinaryName() {
1821 if (isTopLevelClass())
1822 return null;
1823 String name = getSimpleBinaryName0();
1824 if (name == null) // anonymous class
1825 return "";
1826 return name;
1827 }
1828
1829 private native String getSimpleBinaryName0();
1830
1831 /**
1832 * Returns {@code true} if this is a top level class. Returns {@code false}
1833 * otherwise.
1834 */
1835 private boolean isTopLevelClass() {
1836 return !isLocalOrAnonymousClass() && getDeclaringClass0() == null;
1837 }
1838
1839 /**
1840 * Returns {@code true} if this is a local class or an anonymous
1841 * class. Returns {@code false} otherwise.
1842 */
1843 private boolean isLocalOrAnonymousClass() {
1844 // JVM Spec 4.7.7: A class must have an EnclosingMethod
1845 // attribute if and only if it is a local class or an
1846 // anonymous class.
1847 return hasEnclosingMethodInfo();
1848 }
1849
1850 private boolean hasEnclosingMethodInfo() {
1851 Object[] enclosingInfo = getEnclosingMethod0();
1852 if (enclosingInfo != null) {
1853 EnclosingMethodInfo.validate(enclosingInfo);
1854 return true;
1855 }
1856 return false;
1857 }
1858
1859 /**
1860 * Returns an array containing {@code Class} objects representing all
1861 * the public classes and interfaces that are members of the class
1862 * represented by this {@code Class} object. This includes public
1863 * class and interface members inherited from superclasses and public class
1864 * and interface members declared by the class. This method returns an
1865 * array of length 0 if this {@code Class} object has no public member
1866 * classes or interfaces. This method also returns an array of length 0 if
1867 * this {@code Class} object represents a primitive type, an array
1868 * class, or void.
1869 *
1870 * @return the array of {@code Class} objects representing the public
1871 * members of this class
1872 * @since 1.1
1873 */
1874 public Class<?>[] getClasses() {
1875 List<Class<?>> list = new ArrayList<>();
1876 Class<?> currentClass = Class.this;
1877 while (currentClass != null) {
1878 for (Class<?> m : currentClass.getDeclaredClasses()) {
1879 if (Modifier.isPublic(m.getModifiers())) {
1880 list.add(m);
1881 }
1882 }
1883 currentClass = currentClass.getSuperclass();
1884 }
1885 return list.toArray(EMPTY_CLASS_ARRAY);
1886 }
1887
1888
1889 /**
1890 * Returns an array containing {@code Field} objects reflecting all
1891 * the accessible public fields of the class or interface represented by
1892 * this {@code Class} object.
1893 *
1894 * <p> If this {@code Class} object represents a class or interface with
1895 * no accessible public fields, then this method returns an array of length
1896 * 0.
1897 *
1898 * <p> If this {@code Class} object represents a class, then this method
1899 * returns the public fields of the class and of all its superclasses and
1900 * superinterfaces.
1901 *
1902 * <p> If this {@code Class} object represents an interface, then this
1903 * method returns the fields of the interface and of all its
1904 * superinterfaces.
1905 *
1906 * <p> If this {@code Class} object represents an array type, a primitive
1907 * type, or void, then this method returns an array of length 0.
1908 *
1909 * <p> The elements in the returned array are not sorted and are not in any
1910 * particular order.
1911 *
1912 * @return the array of {@code Field} objects representing the
1913 * public fields
1914 *
1915 * @since 1.1
1916 * @jls 8.2 Class Members
1917 * @jls 8.3 Field Declarations
1918 */
1919 public Field[] getFields() {
1920 return copyFields(privateGetPublicFields());
1921 }
1922
1923
1924 /**
1925 * Returns an array containing {@code Method} objects reflecting all the
1926 * public methods of the class or interface represented by this {@code
1927 * Class} object, including those declared by the class or interface and
1928 * those inherited from superclasses and superinterfaces.
1929 *
1930 * <p> If this {@code Class} object represents an array type, then the
1931 * returned array has a {@code Method} object for each of the public
1932 * methods inherited by the array type from {@code Object}. It does not
1933 * contain a {@code Method} object for {@code clone()}.
1934 *
1935 * <p> If this {@code Class} object represents an interface then the
1936 * returned array does not contain any implicitly declared methods from
1937 * {@code Object}. Therefore, if no methods are explicitly declared in
1938 * this interface or any of its superinterfaces then the returned array
1939 * has length 0. (Note that a {@code Class} object which represents a class
1940 * always has public methods, inherited from {@code Object}.)
1941 *
1942 * <p> The returned array never contains methods with names {@value
1943 * ConstantDescs#INIT_NAME} or {@value ConstantDescs#CLASS_INIT_NAME}.
1944 *
1945 * <p> The elements in the returned array are not sorted and are not in any
1946 * particular order.
1947 *
1948 * <p> Generally, the result is computed as with the following 4 step algorithm.
1949 * Let C be the class or interface represented by this {@code Class} object:
1950 * <ol>
1951 * <li> A union of methods is composed of:
1952 * <ol type="a">
1953 * <li> C's declared public instance and static methods as returned by
1954 * {@link #getDeclaredMethods()} and filtered to include only public
1955 * methods.</li>
1956 * <li> If C is a class other than {@code Object}, then include the result
1957 * of invoking this algorithm recursively on the superclass of C.</li>
1958 * <li> Include the results of invoking this algorithm recursively on all
1959 * direct superinterfaces of C, but include only instance methods.</li>
1960 * </ol></li>
1961 * <li> Union from step 1 is partitioned into subsets of methods with same
1962 * signature (name, parameter types) and return type.</li>
1963 * <li> Within each such subset only the most specific methods are selected.
1964 * Let method M be a method from a set of methods with same signature
1965 * and return type. M is most specific if there is no such method
1966 * N != M from the same set, such that N is more specific than M.
1967 * N is more specific than M if:
1968 * <ol type="a">
1969 * <li> N is declared by a class and M is declared by an interface; or</li>
1970 * <li> N and M are both declared by classes or both by interfaces and
1971 * N's declaring type is the same as or a subtype of M's declaring type
1972 * (clearly, if M's and N's declaring types are the same type, then
1973 * M and N are the same method).</li>
1974 * </ol></li>
1975 * <li> The result of this algorithm is the union of all selected methods from
1976 * step 3.</li>
1977 * </ol>
1978 *
1979 * @apiNote There may be more than one method with a particular name
1980 * and parameter types in a class because while the Java language forbids a
1981 * class to declare multiple methods with the same signature but different
1982 * return types, the Java virtual machine does not. This
1983 * increased flexibility in the virtual machine can be used to
1984 * implement various language features. For example, covariant
1985 * returns can be implemented with {@linkplain
1986 * java.lang.reflect.Method#isBridge bridge methods}; the bridge
1987 * method and the overriding method would have the same
1988 * signature but different return types.
1989 *
1990 * @return the array of {@code Method} objects representing the
1991 * public methods of this class
1992 *
1993 * @jls 8.2 Class Members
1994 * @jls 8.4 Method Declarations
1995 * @since 1.1
1996 */
1997 public Method[] getMethods() {
1998 return copyMethods(privateGetPublicMethods());
1999 }
2000
2001
2002 /**
2003 * Returns an array containing {@code Constructor} objects reflecting
2004 * all the public constructors of the class represented by this
2005 * {@code Class} object. An array of length 0 is returned if the
2006 * class has no public constructors, or if the class is an array class, or
2007 * if the class reflects a primitive type or void.
2008 *
2009 * @apiNote
2010 * While this method returns an array of {@code
2011 * Constructor<T>} objects (that is an array of constructors from
2012 * this class), the return type of this method is {@code
2013 * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
2014 * might be expected. This less informative return type is
2015 * necessary since after being returned from this method, the
2016 * array could be modified to hold {@code Constructor} objects for
2017 * different classes, which would violate the type guarantees of
2018 * {@code Constructor<T>[]}.
2019 *
2020 * @return the array of {@code Constructor} objects representing the
2021 * public constructors of this class
2022 *
2023 * @see #getDeclaredConstructors()
2024 * @since 1.1
2025 */
2026 public Constructor<?>[] getConstructors() {
2027 return copyConstructors(privateGetDeclaredConstructors(true));
2028 }
2029
2030
2031 /**
2032 * Returns a {@code Field} object that reflects the specified public member
2033 * field of the class or interface represented by this {@code Class}
2034 * object. The {@code name} parameter is a {@code String} specifying the
2035 * simple name of the desired field.
2036 *
2037 * <p> The field to be reflected is determined by the algorithm that
2038 * follows. Let C be the class or interface represented by this {@code Class} object:
2039 *
2040 * <OL>
2041 * <LI> If C declares a public field with the name specified, that is the
2042 * field to be reflected.</LI>
2043 * <LI> If no field was found in step 1 above, this algorithm is applied
2044 * recursively to each direct superinterface of C. The direct
2045 * superinterfaces are searched in the order they were declared.</LI>
2046 * <LI> If no field was found in steps 1 and 2 above, and C has a
2047 * superclass S, then this algorithm is invoked recursively upon S.
2048 * If C has no superclass, then a {@code NoSuchFieldException}
2049 * is thrown.</LI>
2050 * </OL>
2051 *
2052 * <p> If this {@code Class} object represents an array type, then this
2053 * method does not find the {@code length} field of the array type.
2054 *
2055 * @param name the field name
2056 * @return the {@code Field} object of this class specified by
2057 * {@code name}
2058 * @throws NoSuchFieldException if a field with the specified name is
2059 * not found.
2060 *
2061 * @since 1.1
2062 * @jls 8.2 Class Members
2063 * @jls 8.3 Field Declarations
2064 */
2065 public Field getField(String name) throws NoSuchFieldException {
2066 Objects.requireNonNull(name);
2067 Field field = getField0(name);
2068 if (field == null) {
2069 throw new NoSuchFieldException(name);
2070 }
2071 return getReflectionFactory().copyField(field);
2072 }
2073
2074
2075 /**
2076 * Returns a {@code Method} object that reflects the specified public
2077 * member method of the class or interface represented by this
2078 * {@code Class} object. The {@code name} parameter is a
2079 * {@code String} specifying the simple name of the desired method. The
2080 * {@code parameterTypes} parameter is an array of {@code Class}
2081 * objects that identify the method's formal parameter types, in declared
2082 * order. If {@code parameterTypes} is {@code null}, it is
2083 * treated as if it were an empty array.
2084 *
2085 * <p> If this {@code Class} object represents an array type, then this
2086 * method finds any public method inherited by the array type from
2087 * {@code Object} except method {@code clone()}.
2088 *
2089 * <p> If this {@code Class} object represents an interface then this
2090 * method does not find any implicitly declared method from
2091 * {@code Object}. Therefore, if no methods are explicitly declared in
2092 * this interface or any of its superinterfaces, then this method does not
2093 * find any method.
2094 *
2095 * <p> This method does not find any method with name {@value
2096 * ConstantDescs#INIT_NAME} or {@value ConstantDescs#CLASS_INIT_NAME}.
2097 *
2098 * <p> Generally, the method to be reflected is determined by the 4 step
2099 * algorithm that follows.
2100 * Let C be the class or interface represented by this {@code Class} object:
2101 * <ol>
2102 * <li> A union of methods is composed of:
2103 * <ol type="a">
2104 * <li> C's declared public instance and static methods as returned by
2105 * {@link #getDeclaredMethods()} and filtered to include only public
2106 * methods that match given {@code name} and {@code parameterTypes}</li>
2107 * <li> If C is a class other than {@code Object}, then include the result
2108 * of invoking this algorithm recursively on the superclass of C.</li>
2109 * <li> Include the results of invoking this algorithm recursively on all
2110 * direct superinterfaces of C, but include only instance methods.</li>
2111 * </ol></li>
2112 * <li> This union is partitioned into subsets of methods with same
2113 * return type (the selection of methods from step 1 also guarantees that
2114 * they have the same method name and parameter types).</li>
2115 * <li> Within each such subset only the most specific methods are selected.
2116 * Let method M be a method from a set of methods with same VM
2117 * signature (return type, name, parameter types).
2118 * M is most specific if there is no such method N != M from the same
2119 * set, such that N is more specific than M. N is more specific than M
2120 * if:
2121 * <ol type="a">
2122 * <li> N is declared by a class and M is declared by an interface; or</li>
2123 * <li> N and M are both declared by classes or both by interfaces and
2124 * N's declaring type is the same as or a subtype of M's declaring type
2125 * (clearly, if M's and N's declaring types are the same type, then
2126 * M and N are the same method).</li>
2127 * </ol></li>
2128 * <li> The result of this algorithm is chosen arbitrarily from the methods
2129 * with most specific return type among all selected methods from step 3.
2130 * Let R be a return type of a method M from the set of all selected methods
2131 * from step 3. M is a method with most specific return type if there is
2132 * no such method N != M from the same set, having return type S != R,
2133 * such that S is a subtype of R as determined by
2134 * R.class.{@link #isAssignableFrom}(S.class).
2135 * </ol>
2136 *
2137 * @apiNote There may be more than one method with matching name and
2138 * parameter types in a class because while the Java language forbids a
2139 * class to declare multiple methods with the same signature but different
2140 * return types, the Java virtual machine does not. This
2141 * increased flexibility in the virtual machine can be used to
2142 * implement various language features. For example, covariant
2143 * returns can be implemented with {@linkplain
2144 * java.lang.reflect.Method#isBridge bridge methods}; the bridge
2145 * method and the overriding method would have the same
2146 * signature but different return types. This method would return the
2147 * overriding method as it would have a more specific return type.
2148 *
2149 * @param name the name of the method
2150 * @param parameterTypes the list of parameters, may be {@code null}
2151 * @return the {@code Method} object that matches the specified
2152 * {@code name} and {@code parameterTypes}
2153 * @throws NoSuchMethodException if a matching method is not found,
2154 * if {@code parameterTypes} contains {@code null},
2155 * or if the name is {@value ConstantDescs#INIT_NAME} or
2156 * {@value ConstantDescs#CLASS_INIT_NAME}
2157 *
2158 * @jls 8.2 Class Members
2159 * @jls 8.4 Method Declarations
2160 * @since 1.1
2161 */
2162 public Method getMethod(String name, Class<?>... parameterTypes)
2163 throws NoSuchMethodException {
2164 Objects.requireNonNull(name);
2165 Method method = getMethod0(name, parameterTypes);
2166 if (method == null) {
2167 throw new NoSuchMethodException(methodToString(name, parameterTypes));
2168 }
2169 return getReflectionFactory().copyMethod(method);
2170 }
2171
2172 /**
2173 * Returns a {@code Constructor} object that reflects the specified
2174 * public constructor of the class represented by this {@code Class}
2175 * object. The {@code parameterTypes} parameter is an array of
2176 * {@code Class} objects that identify the constructor's formal
2177 * parameter types, in declared order.
2178 *
2179 * If this {@code Class} object represents an inner class
2180 * declared in a non-static context, the formal parameter types
2181 * include the explicit enclosing instance as the first parameter.
2182 *
2183 * <p> The constructor to reflect is the public constructor of the class
2184 * represented by this {@code Class} object whose formal parameter
2185 * types match those specified by {@code parameterTypes}.
2186 *
2187 * @param parameterTypes the parameter array, may be {@code null}
2188 * @return the {@code Constructor} object of the public constructor that
2189 * matches the specified {@code parameterTypes}
2190 * @throws NoSuchMethodException if a matching constructor is not found,
2191 * if this {@code Class} object represents an interface, a primitive
2192 * type, an array class, or void, or if {@code parameterTypes}
2193 * contains {@code null}
2194 *
2195 * @see #getDeclaredConstructor(Class[])
2196 * @since 1.1
2197 */
2198 public Constructor<T> getConstructor(Class<?>... parameterTypes)
2199 throws NoSuchMethodException {
2200 return getReflectionFactory().copyConstructor(
2201 getConstructor0(parameterTypes, Member.PUBLIC));
2202 }
2203
2204
2205 /**
2206 * Returns an array of {@code Class} objects reflecting all the
2207 * classes and interfaces declared as members of the class represented by
2208 * this {@code Class} object. This includes public, protected, default
2209 * (package) access, and private classes and interfaces declared by the
2210 * class, but excludes inherited classes and interfaces. This method
2211 * returns an array of length 0 if the class declares no classes or
2212 * interfaces as members, or if this {@code Class} object represents a
2213 * primitive type, an array class, or void.
2214 *
2215 * @return the array of {@code Class} objects representing all the
2216 * declared members of this class
2217 *
2218 * @since 1.1
2219 * @jls 8.5 Member Class and Interface Declarations
2220 */
2221 public Class<?>[] getDeclaredClasses() {
2222 return getDeclaredClasses0();
2223 }
2224
2225
2226 /**
2227 * Returns an array of {@code Field} objects reflecting all the fields
2228 * declared by the class or interface represented by this
2229 * {@code Class} object. This includes public, protected, default
2230 * (package) access, and private fields, but excludes inherited fields.
2231 *
2232 * <p> If this {@code Class} object represents a class or interface with no
2233 * declared fields, then this method returns an array of length 0.
2234 *
2235 * <p> If this {@code Class} object represents an array type, a primitive
2236 * type, or void, then this method returns an array of length 0.
2237 *
2238 * <p> The elements in the returned array are not sorted and are not in any
2239 * particular order.
2240 *
2241 * @return the array of {@code Field} objects representing all the
2242 * declared fields of this class
2243 *
2244 * @since 1.1
2245 * @jls 8.2 Class Members
2246 * @jls 8.3 Field Declarations
2247 */
2248 public Field[] getDeclaredFields() {
2249 return copyFields(privateGetDeclaredFields(false));
2250 }
2251
2252 /**
2253 * Returns an array of {@code RecordComponent} objects representing all the
2254 * record components of this record class, or {@code null} if this class is
2255 * not a record class.
2256 *
2257 * <p> The components are returned in the same order that they are declared
2258 * in the record header. The array is empty if this record class has no
2259 * components. If the class is not a record class, that is {@link
2260 * #isRecord()} returns {@code false}, then this method returns {@code null}.
2261 * Conversely, if {@link #isRecord()} returns {@code true}, then this method
2262 * returns a non-null value.
2263 *
2264 * @apiNote
2265 * <p> The following method can be used to find the record canonical constructor:
2266 *
2267 * {@snippet lang="java" :
2268 * static <T extends Record> Constructor<T> getCanonicalConstructor(Class<T> cls)
2269 * throws NoSuchMethodException {
2270 * Class<?>[] paramTypes =
2271 * Arrays.stream(cls.getRecordComponents())
2272 * .map(RecordComponent::getType)
2273 * .toArray(Class<?>[]::new);
2274 * return cls.getDeclaredConstructor(paramTypes);
2275 * }}
2276 *
2277 * @return An array of {@code RecordComponent} objects representing all the
2278 * record components of this record class, or {@code null} if this
2279 * class is not a record class
2280 *
2281 * @jls 8.10 Record Classes
2282 * @since 16
2283 */
2284 public RecordComponent[] getRecordComponents() {
2285 if (!isRecord()) {
2286 return null;
2287 }
2288 return getRecordComponents0();
2289 }
2290
2291 /**
2292 * Returns an array containing {@code Method} objects reflecting all the
2293 * declared methods of the class or interface represented by this {@code
2294 * Class} object, including public, protected, default (package)
2295 * access, and private methods, but excluding inherited methods.
2296 * The declared methods may include methods <em>not</em> in the
2297 * source of the class or interface, including {@linkplain
2298 * Method#isBridge bridge methods} and other {@linkplain
2299 * Executable#isSynthetic synthetic} methods added by compilers.
2300 *
2301 * <p> If this {@code Class} object represents a class or interface that
2302 * has multiple declared methods with the same name and parameter types,
2303 * but different return types, then the returned array has a {@code Method}
2304 * object for each such method.
2305 *
2306 * <p> If this {@code Class} object represents a class or interface that
2307 * has a class initialization method {@value ConstantDescs#CLASS_INIT_NAME},
2308 * then the returned array does <em>not</em> have a corresponding {@code
2309 * Method} object.
2310 *
2311 * <p> If this {@code Class} object represents a class or interface with no
2312 * declared methods, then the returned array has length 0.
2313 *
2314 * <p> If this {@code Class} object represents an array type, a primitive
2315 * type, or void, then the returned array has length 0.
2316 *
2317 * <p> The elements in the returned array are not sorted and are not in any
2318 * particular order.
2319 *
2320 * @return the array of {@code Method} objects representing all the
2321 * declared methods of this class
2322 *
2323 * @jls 8.2 Class Members
2324 * @jls 8.4 Method Declarations
2325 * @see <a
2326 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
2327 * programming language and JVM modeling in core reflection</a>
2328 * @since 1.1
2329 */
2330 public Method[] getDeclaredMethods() {
2331 return copyMethods(privateGetDeclaredMethods(false));
2332 }
2333
2334 /**
2335 * Returns an array of {@code Constructor} objects reflecting all the
2336 * constructors implicitly or explicitly declared by the class represented by this
2337 * {@code Class} object. These are public, protected, default
2338 * (package) access, and private constructors. The elements in the array
2339 * returned are not sorted and are not in any particular order. If the
2340 * class has a default constructor (JLS {@jls 8.8.9}), it is included in the returned array.
2341 * If a record class has a canonical constructor (JLS {@jls
2342 * 8.10.4.1}, {@jls 8.10.4.2}), it is included in the returned array.
2343 *
2344 * This method returns an array of length 0 if this {@code Class}
2345 * object represents an interface, a primitive type, an array class, or
2346 * void.
2347 *
2348 * @return the array of {@code Constructor} objects representing all the
2349 * declared constructors of this class
2350 *
2351 * @since 1.1
2352 * @see #getConstructors()
2353 * @jls 8.8 Constructor Declarations
2354 */
2355 public Constructor<?>[] getDeclaredConstructors() {
2356 return copyConstructors(privateGetDeclaredConstructors(false));
2357 }
2358
2359
2360 /**
2361 * Returns a {@code Field} object that reflects the specified declared
2362 * field of the class or interface represented by this {@code Class}
2363 * object. The {@code name} parameter is a {@code String} that specifies
2364 * the simple name of the desired field.
2365 *
2366 * <p> If this {@code Class} object represents an array type, then this
2367 * method does not find the {@code length} field of the array type.
2368 *
2369 * @param name the name of the field
2370 * @return the {@code Field} object for the specified field in this
2371 * class
2372 * @throws NoSuchFieldException if a field with the specified name is
2373 * not found.
2374 *
2375 * @since 1.1
2376 * @jls 8.2 Class Members
2377 * @jls 8.3 Field Declarations
2378 */
2379 public Field getDeclaredField(String name) throws NoSuchFieldException {
2380 Objects.requireNonNull(name);
2381 Field field = searchFields(privateGetDeclaredFields(false), name);
2382 if (field == null) {
2383 throw new NoSuchFieldException(name);
2384 }
2385 return getReflectionFactory().copyField(field);
2386 }
2387
2388
2389 /**
2390 * Returns a {@code Method} object that reflects the specified
2391 * declared method of the class or interface represented by this
2392 * {@code Class} object. The {@code name} parameter is a
2393 * {@code String} that specifies the simple name of the desired
2394 * method, and the {@code parameterTypes} parameter is an array of
2395 * {@code Class} objects that identify the method's formal parameter
2396 * types, in declared order. If more than one method with the same
2397 * parameter types is declared in a class, and one of these methods has a
2398 * return type that is more specific than any of the others, that method is
2399 * returned; otherwise one of the methods is chosen arbitrarily. If the
2400 * name is {@value ConstantDescs#INIT_NAME} or {@value
2401 * ConstantDescs#CLASS_INIT_NAME} a {@code NoSuchMethodException}
2402 * is raised.
2403 *
2404 * <p> If this {@code Class} object represents an array type, then this
2405 * method does not find the {@code clone()} method.
2406 *
2407 * @param name the name of the method
2408 * @param parameterTypes the parameter array, may be {@code null}
2409 * @return the {@code Method} object for the method of this class
2410 * matching the specified name and parameters
2411 * @throws NoSuchMethodException if a matching method is not found,
2412 * if {@code parameterTypes} contains {@code null},
2413 * or if the name is {@value ConstantDescs#INIT_NAME} or
2414 * {@value ConstantDescs#CLASS_INIT_NAME}
2415 *
2416 * @jls 8.2 Class Members
2417 * @jls 8.4 Method Declarations
2418 * @since 1.1
2419 */
2420 public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2421 throws NoSuchMethodException {
2422 Objects.requireNonNull(name);
2423 Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
2424 if (method == null) {
2425 throw new NoSuchMethodException(methodToString(name, parameterTypes));
2426 }
2427 return getReflectionFactory().copyMethod(method);
2428 }
2429
2430 /**
2431 * Returns the list of {@code Method} objects for the declared public
2432 * methods of this class or interface that have the specified method name
2433 * and parameter types.
2434 *
2435 * @param name the name of the method
2436 * @param parameterTypes the parameter array
2437 * @return the list of {@code Method} objects for the public methods of
2438 * this class matching the specified name and parameters
2439 */
2440 List<Method> getDeclaredPublicMethods(String name, Class<?>... parameterTypes) {
2441 Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);
2442 ReflectionFactory factory = getReflectionFactory();
2443 List<Method> result = new ArrayList<>();
2444 for (Method method : methods) {
2445 if (method.getName().equals(name)
2446 && Arrays.equals(
2447 factory.getExecutableSharedParameterTypes(method),
2448 parameterTypes)) {
2449 result.add(factory.copyMethod(method));
2450 }
2451 }
2452 return result;
2453 }
2454
2455 /**
2456 * Returns the most specific {@code Method} object of this class, super class or
2457 * interface that have the specified method name and parameter types.
2458 *
2459 * @param publicOnly true if only public methods are examined, otherwise all methods
2460 * @param name the name of the method
2461 * @param parameterTypes the parameter array
2462 * @return the {@code Method} object for the method found from this class matching
2463 * the specified name and parameters, or null if not found
2464 */
2465 Method findMethod(boolean publicOnly, String name, Class<?>... parameterTypes) {
2466 PublicMethods.MethodList res = getMethodsRecursive(name, parameterTypes, true, publicOnly);
2467 return res == null ? null : getReflectionFactory().copyMethod(res.getMostSpecific());
2468 }
2469
2470 /**
2471 * Returns a {@code Constructor} object that reflects the specified
2472 * constructor of the class represented by this
2473 * {@code Class} object. The {@code parameterTypes} parameter is
2474 * an array of {@code Class} objects that identify the constructor's
2475 * formal parameter types, in declared order.
2476 *
2477 * If this {@code Class} object represents an inner class
2478 * declared in a non-static context, the formal parameter types
2479 * include the explicit enclosing instance as the first parameter.
2480 *
2481 * @param parameterTypes the parameter array, may be {@code null}
2482 * @return The {@code Constructor} object for the constructor with the
2483 * specified parameter list
2484 * @throws NoSuchMethodException if a matching constructor is not found,
2485 * if this {@code Class} object represents an interface, a
2486 * primitive type, an array class, or void, or if
2487 * {@code parameterTypes} contains {@code null}
2488 *
2489 * @see #getConstructor(Class[])
2490 * @since 1.1
2491 */
2492 public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
2493 throws NoSuchMethodException {
2494 return getReflectionFactory().copyConstructor(
2495 getConstructor0(parameterTypes, Member.DECLARED));
2496 }
2497
2498 /**
2499 * Finds a resource with a given name.
2500 *
2501 * <p> If this class is in a named {@link Module Module} then this method
2502 * will attempt to find the resource in the module. This is done by
2503 * delegating to the module's class loader {@link
2504 * ClassLoader#findResource(String,String) findResource(String,String)}
2505 * method, invoking it with the module name and the absolute name of the
2506 * resource. Resources in named modules are subject to the rules for
2507 * encapsulation specified in the {@code Module} {@link
2508 * Module#getResourceAsStream getResourceAsStream} method and so this
2509 * method returns {@code null} when the resource is a
2510 * non-"{@code .class}" resource in a package that is not open to the
2511 * caller's module.
2512 *
2513 * <p> Otherwise, if this class is not in a named module then the rules for
2514 * searching resources associated with a given class are implemented by the
2515 * defining {@linkplain ClassLoader class loader} of the class. This method
2516 * delegates to this {@code Class} object's class loader.
2517 * If this {@code Class} object was loaded by the bootstrap class loader,
2518 * the method delegates to {@link ClassLoader#getSystemResourceAsStream}.
2519 *
2520 * <p> Before delegation, an absolute resource name is constructed from the
2521 * given resource name using this algorithm:
2522 *
2523 * <ul>
2524 *
2525 * <li> If the {@code name} begins with a {@code '/'}
2526 * (<code>'\u002f'</code>), then the absolute name of the resource is the
2527 * portion of the {@code name} following the {@code '/'}.
2528 *
2529 * <li> Otherwise, the absolute name is of the following form:
2530 *
2531 * <blockquote>
2532 * {@code modified_package_name/name}
2533 * </blockquote>
2534 *
2535 * <p> Where the {@code modified_package_name} is the package name of this
2536 * object with {@code '/'} substituted for {@code '.'}
2537 * (<code>'\u002e'</code>).
2538 *
2539 * </ul>
2540 *
2541 * @param name name of the desired resource
2542 * @return A {@link java.io.InputStream} object; {@code null} if no
2543 * resource with this name is found, or the resource is in a package
2544 * that is not {@linkplain Module#isOpen(String, Module) open} to at
2545 * least the caller module.
2546 *
2547 * @see Module#getResourceAsStream(String)
2548 * @since 1.1
2549 */
2550 @CallerSensitive
2551 public InputStream getResourceAsStream(String name) {
2552 name = resolveName(name);
2553
2554 Module thisModule = getModule();
2555 if (thisModule.isNamed()) {
2556 // check if resource can be located by caller
2557 if (Resources.canEncapsulate(name)
2558 && !isOpenToCaller(name, Reflection.getCallerClass())) {
2559 return null;
2560 }
2561
2562 // resource not encapsulated or in package open to caller
2563 String mn = thisModule.getName();
2564 ClassLoader cl = classLoader;
2565 try {
2566
2567 // special-case built-in class loaders to avoid the
2568 // need for a URL connection
2569 if (cl == null) {
2570 return BootLoader.findResourceAsStream(mn, name);
2571 } else if (cl instanceof BuiltinClassLoader bcl) {
2572 return bcl.findResourceAsStream(mn, name);
2573 } else {
2574 URL url = cl.findResource(mn, name);
2575 return (url != null) ? url.openStream() : null;
2576 }
2577
2578 } catch (IOException | SecurityException e) {
2579 return null;
2580 }
2581 }
2582
2583 // unnamed module
2584 ClassLoader cl = classLoader;
2585 if (cl == null) {
2586 return ClassLoader.getSystemResourceAsStream(name);
2587 } else {
2588 return cl.getResourceAsStream(name);
2589 }
2590 }
2591
2592 /**
2593 * Finds a resource with a given name.
2594 *
2595 * <p> If this class is in a named {@link Module Module} then this method
2596 * will attempt to find the resource in the module. This is done by
2597 * delegating to the module's class loader {@link
2598 * ClassLoader#findResource(String,String) findResource(String,String)}
2599 * method, invoking it with the module name and the absolute name of the
2600 * resource. Resources in named modules are subject to the rules for
2601 * encapsulation specified in the {@code Module} {@link
2602 * Module#getResourceAsStream getResourceAsStream} method and so this
2603 * method returns {@code null} when the resource is a
2604 * non-"{@code .class}" resource in a package that is not open to the
2605 * caller's module.
2606 *
2607 * <p> Otherwise, if this class is not in a named module then the rules for
2608 * searching resources associated with a given class are implemented by the
2609 * defining {@linkplain ClassLoader class loader} of the class. This method
2610 * delegates to this {@code Class} object's class loader.
2611 * If this {@code Class} object was loaded by the bootstrap class loader,
2612 * the method delegates to {@link ClassLoader#getSystemResource}.
2613 *
2614 * <p> Before delegation, an absolute resource name is constructed from the
2615 * given resource name using this algorithm:
2616 *
2617 * <ul>
2618 *
2619 * <li> If the {@code name} begins with a {@code '/'}
2620 * (<code>'\u002f'</code>), then the absolute name of the resource is the
2621 * portion of the {@code name} following the {@code '/'}.
2622 *
2623 * <li> Otherwise, the absolute name is of the following form:
2624 *
2625 * <blockquote>
2626 * {@code modified_package_name/name}
2627 * </blockquote>
2628 *
2629 * <p> Where the {@code modified_package_name} is the package name of this
2630 * object with {@code '/'} substituted for {@code '.'}
2631 * (<code>'\u002e'</code>).
2632 *
2633 * </ul>
2634 *
2635 * @param name name of the desired resource
2636 * @return A {@link java.net.URL} object; {@code null} if no resource with
2637 * this name is found, the resource cannot be located by a URL, or the
2638 * resource is in a package that is not
2639 * {@linkplain Module#isOpen(String, Module) open} to at least the caller
2640 * module.
2641 * @since 1.1
2642 */
2643 @CallerSensitive
2644 public URL getResource(String name) {
2645 name = resolveName(name);
2646
2647 Module thisModule = getModule();
2648 if (thisModule.isNamed()) {
2649 // check if resource can be located by caller
2650 if (Resources.canEncapsulate(name)
2651 && !isOpenToCaller(name, Reflection.getCallerClass())) {
2652 return null;
2653 }
2654
2655 // resource not encapsulated or in package open to caller
2656 String mn = thisModule.getName();
2657 ClassLoader cl = classLoader;
2658 try {
2659 if (cl == null) {
2660 return BootLoader.findResource(mn, name);
2661 } else {
2662 return cl.findResource(mn, name);
2663 }
2664 } catch (IOException ioe) {
2665 return null;
2666 }
2667 }
2668
2669 // unnamed module
2670 ClassLoader cl = classLoader;
2671 if (cl == null) {
2672 return ClassLoader.getSystemResource(name);
2673 } else {
2674 return cl.getResource(name);
2675 }
2676 }
2677
2678 /**
2679 * Returns true if a resource with the given name can be located by the
2680 * given caller. All resources in a module can be located by code in
2681 * the module. For other callers, then the package needs to be open to
2682 * the caller.
2683 */
2684 private boolean isOpenToCaller(String name, Class<?> caller) {
2685 // assert getModule().isNamed();
2686 Module thisModule = getModule();
2687 Module callerModule = (caller != null) ? caller.getModule() : null;
2688 if (callerModule != thisModule) {
2689 String pn = Resources.toPackageName(name);
2690 if (thisModule.getDescriptor().packages().contains(pn)) {
2691 if (callerModule == null) {
2692 // no caller, return true if the package is open to all modules
2693 return thisModule.isOpen(pn);
2694 }
2695 if (!thisModule.isOpen(pn, callerModule)) {
2696 // package not open to caller
2697 return false;
2698 }
2699 }
2700 }
2701 return true;
2702 }
2703
2704 private transient final ProtectionDomain protectionDomain;
2705
2706 /** Holder for the protection domain returned when the internal domain is null */
2707 private static class Holder {
2708 private static final ProtectionDomain allPermDomain;
2709 static {
2710 Permissions perms = new Permissions();
2711 perms.add(new AllPermission());
2712 allPermDomain = new ProtectionDomain(null, perms);
2713 }
2714 }
2715
2716 /**
2717 * Returns the {@code ProtectionDomain} of this class.
2718 *
2719 * @return the ProtectionDomain of this class
2720 *
2721 * @see java.security.ProtectionDomain
2722 * @since 1.2
2723 */
2724 public ProtectionDomain getProtectionDomain() {
2725 if (protectionDomain == null) {
2726 return Holder.allPermDomain;
2727 } else {
2728 return protectionDomain;
2729 }
2730 }
2731
2732 /*
2733 * Returns the Class object for the named primitive type. Type parameter T
2734 * avoids redundant casts for trusted code.
2735 */
2736 static native <T> Class<T> getPrimitiveClass(String name);
2737
2738 /**
2739 * Add a package name prefix if the name is not absolute. Remove leading "/"
2740 * if name is absolute
2741 */
2742 private String resolveName(String name) {
2743 if (!name.startsWith("/")) {
2744 String baseName = getPackageName();
2745 if (!baseName.isEmpty()) {
2746 int len = baseName.length() + 1 + name.length();
2747 StringBuilder sb = new StringBuilder(len);
2748 name = sb.append(baseName.replace('.', '/'))
2749 .append('/')
2750 .append(name)
2751 .toString();
2752 }
2753 } else {
2754 name = name.substring(1);
2755 }
2756 return name;
2757 }
2758
2759 /**
2760 * Atomic operations support.
2761 */
2762 private static class Atomic {
2763 // initialize Unsafe machinery here, since we need to call Class.class instance method
2764 // and have to avoid calling it in the static initializer of the Class class...
2765 private static final Unsafe unsafe = Unsafe.getUnsafe();
2766 // offset of Class.reflectionData instance field
2767 private static final long reflectionDataOffset
2768 = unsafe.objectFieldOffset(Class.class, "reflectionData");
2769 // offset of Class.annotationType instance field
2770 private static final long annotationTypeOffset
2771 = unsafe.objectFieldOffset(Class.class, "annotationType");
2772 // offset of Class.annotationData instance field
2773 private static final long annotationDataOffset
2774 = unsafe.objectFieldOffset(Class.class, "annotationData");
2775
2776 static <T> boolean casReflectionData(Class<?> clazz,
2777 SoftReference<ReflectionData<T>> oldData,
2778 SoftReference<ReflectionData<T>> newData) {
2779 return unsafe.compareAndSetReference(clazz, reflectionDataOffset, oldData, newData);
2780 }
2781
2782 static boolean casAnnotationType(Class<?> clazz,
2783 AnnotationType oldType,
2784 AnnotationType newType) {
2785 return unsafe.compareAndSetReference(clazz, annotationTypeOffset, oldType, newType);
2786 }
2787
2788 static boolean casAnnotationData(Class<?> clazz,
2789 AnnotationData oldData,
2790 AnnotationData newData) {
2791 return unsafe.compareAndSetReference(clazz, annotationDataOffset, oldData, newData);
2792 }
2793 }
2794
2795 /**
2796 * Reflection support.
2797 */
2798
2799 // Reflection data caches various derived names and reflective members. Cached
2800 // values may be invalidated when JVM TI RedefineClasses() is called
2801 private static class ReflectionData<T> {
2802 volatile Field[] declaredFields;
2803 volatile Field[] publicFields;
2804 volatile Method[] declaredMethods;
2805 volatile Method[] publicMethods;
2806 volatile Constructor<T>[] declaredConstructors;
2807 volatile Constructor<T>[] publicConstructors;
2808 // Intermediate results for getFields and getMethods
2809 volatile Field[] declaredPublicFields;
2810 volatile Method[] declaredPublicMethods;
2811 volatile Class<?>[] interfaces;
2812
2813 // Cached names
2814 String simpleName;
2815 String canonicalName;
2816 static final String NULL_SENTINEL = new String();
2817
2818 // Value of classRedefinedCount when we created this ReflectionData instance
2819 final int redefinedCount;
2820
2821 ReflectionData(int redefinedCount) {
2822 this.redefinedCount = redefinedCount;
2823 }
2824 }
2825
2826 private transient volatile SoftReference<ReflectionData<T>> reflectionData;
2827
2828 // Incremented by the VM on each call to JVM TI RedefineClasses()
2829 // that redefines this class or a superclass.
2830 private transient volatile int classRedefinedCount;
2831
2832 // Lazily create and cache ReflectionData
2833 private ReflectionData<T> reflectionData() {
2834 SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
2835 int classRedefinedCount = this.classRedefinedCount;
2836 ReflectionData<T> rd;
2837 if (reflectionData != null &&
2838 (rd = reflectionData.get()) != null &&
2839 rd.redefinedCount == classRedefinedCount) {
2840 return rd;
2841 }
2842 // else no SoftReference or cleared SoftReference or stale ReflectionData
2843 // -> create and replace new instance
2844 return newReflectionData(reflectionData, classRedefinedCount);
2845 }
2846
2847 private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
2848 int classRedefinedCount) {
2849 while (true) {
2850 ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
2851 // try to CAS it...
2852 if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
2853 return rd;
2854 }
2855 // else retry
2856 oldReflectionData = this.reflectionData;
2857 classRedefinedCount = this.classRedefinedCount;
2858 if (oldReflectionData != null &&
2859 (rd = oldReflectionData.get()) != null &&
2860 rd.redefinedCount == classRedefinedCount) {
2861 return rd;
2862 }
2863 }
2864 }
2865
2866 // Generic signature handling
2867 private native String getGenericSignature0();
2868
2869 // Generic info repository; lazily initialized
2870 private transient volatile ClassRepository genericInfo;
2871
2872 // accessor for factory
2873 private GenericsFactory getFactory() {
2874 // create scope and factory
2875 return CoreReflectionFactory.make(this, ClassScope.make(this));
2876 }
2877
2878 // accessor for generic info repository;
2879 // generic info is lazily initialized
2880 private ClassRepository getGenericInfo() {
2881 ClassRepository genericInfo = this.genericInfo;
2882 if (genericInfo == null) {
2883 String signature = getGenericSignature0();
2884 if (signature == null) {
2885 genericInfo = ClassRepository.NONE;
2886 } else {
2887 genericInfo = ClassRepository.make(signature, getFactory());
2888 }
2889 this.genericInfo = genericInfo;
2890 }
2891 return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
2892 }
2893
2894 // Annotations handling
2895 native byte[] getRawAnnotations();
2896 // Since 1.8
2897 native byte[] getRawTypeAnnotations();
2898 static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
2899 return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
2900 }
2901
2902 native ConstantPool getConstantPool();
2903
2904 //
2905 //
2906 // java.lang.reflect.Field handling
2907 //
2908 //
2909
2910 // Returns an array of "root" fields. These Field objects must NOT
2911 // be propagated to the outside world, but must instead be copied
2912 // via ReflectionFactory.copyField.
2913 private Field[] privateGetDeclaredFields(boolean publicOnly) {
2914 Field[] res;
2915 ReflectionData<T> rd = reflectionData();
2916 res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
2917 if (res != null) return res;
2918 // No cached value available; request value from VM
2919 res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
2920 if (publicOnly) {
2921 rd.declaredPublicFields = res;
2922 } else {
2923 rd.declaredFields = res;
2924 }
2925 return res;
2926 }
2927
2928 // Returns an array of "root" fields. These Field objects must NOT
2929 // be propagated to the outside world, but must instead be copied
2930 // via ReflectionFactory.copyField.
2931 private Field[] privateGetPublicFields() {
2932 Field[] res;
2933 ReflectionData<T> rd = reflectionData();
2934 res = rd.publicFields;
2935 if (res != null) return res;
2936
2937 // Use a linked hash set to ensure order is preserved and
2938 // fields from common super interfaces are not duplicated
2939 LinkedHashSet<Field> fields = new LinkedHashSet<>();
2940
2941 // Local fields
2942 addAll(fields, privateGetDeclaredFields(true));
2943
2944 // Direct superinterfaces, recursively
2945 for (Class<?> si : getInterfaces(/* cloneArray */ false)) {
2946 addAll(fields, si.privateGetPublicFields());
2947 }
2948
2949 // Direct superclass, recursively
2950 Class<?> sc = getSuperclass();
2951 if (sc != null) {
2952 addAll(fields, sc.privateGetPublicFields());
2953 }
2954
2955 res = fields.toArray(new Field[0]);
2956 rd.publicFields = res;
2957 return res;
2958 }
2959
2960 private static void addAll(Collection<Field> c, Field[] o) {
2961 for (Field f : o) {
2962 c.add(f);
2963 }
2964 }
2965
2966
2967 //
2968 //
2969 // java.lang.reflect.Constructor handling
2970 //
2971 //
2972
2973 // Returns an array of "root" constructors. These Constructor
2974 // objects must NOT be propagated to the outside world, but must
2975 // instead be copied via ReflectionFactory.copyConstructor.
2976 private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
2977 Constructor<T>[] res;
2978 ReflectionData<T> rd = reflectionData();
2979 res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
2980 if (res != null) return res;
2981 // No cached value available; request value from VM
2982 if (isInterface()) {
2983 @SuppressWarnings("unchecked")
2984 Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
2985 res = temporaryRes;
2986 } else {
2987 res = getDeclaredConstructors0(publicOnly);
2988 }
2989 if (publicOnly) {
2990 rd.publicConstructors = res;
2991 } else {
2992 rd.declaredConstructors = res;
2993 }
2994 return res;
2995 }
2996
2997 //
2998 //
2999 // java.lang.reflect.Method handling
3000 //
3001 //
3002
3003 // Returns an array of "root" methods. These Method objects must NOT
3004 // be propagated to the outside world, but must instead be copied
3005 // via ReflectionFactory.copyMethod.
3006 private Method[] privateGetDeclaredMethods(boolean publicOnly) {
3007 Method[] res;
3008 ReflectionData<T> rd = reflectionData();
3009 res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
3010 if (res != null) return res;
3011 // No cached value available; request value from VM
3012 res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
3013 if (publicOnly) {
3014 rd.declaredPublicMethods = res;
3015 } else {
3016 rd.declaredMethods = res;
3017 }
3018 return res;
3019 }
3020
3021 // Returns an array of "root" methods. These Method objects must NOT
3022 // be propagated to the outside world, but must instead be copied
3023 // via ReflectionFactory.copyMethod.
3024 private Method[] privateGetPublicMethods() {
3025 Method[] res;
3026 ReflectionData<T> rd = reflectionData();
3027 res = rd.publicMethods;
3028 if (res != null) return res;
3029
3030 // No cached value available; compute value recursively.
3031 // Start by fetching public declared methods...
3032 PublicMethods pms = new PublicMethods();
3033 for (Method m : privateGetDeclaredMethods(/* publicOnly */ true)) {
3034 pms.merge(m);
3035 }
3036 // ...then recur over superclass methods...
3037 Class<?> sc = getSuperclass();
3038 if (sc != null) {
3039 for (Method m : sc.privateGetPublicMethods()) {
3040 pms.merge(m);
3041 }
3042 }
3043 // ...and finally over direct superinterfaces.
3044 for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
3045 for (Method m : intf.privateGetPublicMethods()) {
3046 // static interface methods are not inherited
3047 if (!Modifier.isStatic(m.getModifiers())) {
3048 pms.merge(m);
3049 }
3050 }
3051 }
3052
3053 res = pms.toArray();
3054 rd.publicMethods = res;
3055 return res;
3056 }
3057
3058
3059 //
3060 // Helpers for fetchers of one field, method, or constructor
3061 //
3062
3063 // This method does not copy the returned Field object!
3064 private static Field searchFields(Field[] fields, String name) {
3065 for (Field field : fields) {
3066 if (field.getName().equals(name)) {
3067 return field;
3068 }
3069 }
3070 return null;
3071 }
3072
3073 // Returns a "root" Field object. This Field object must NOT
3074 // be propagated to the outside world, but must instead be copied
3075 // via ReflectionFactory.copyField.
3076 private Field getField0(String name) {
3077 // Note: the intent is that the search algorithm this routine
3078 // uses be equivalent to the ordering imposed by
3079 // privateGetPublicFields(). It fetches only the declared
3080 // public fields for each class, however, to reduce the number
3081 // of Field objects which have to be created for the common
3082 // case where the field being requested is declared in the
3083 // class which is being queried.
3084 Field res;
3085 // Search declared public fields
3086 if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
3087 return res;
3088 }
3089 // Direct superinterfaces, recursively
3090 Class<?>[] interfaces = getInterfaces(/* cloneArray */ false);
3091 for (Class<?> c : interfaces) {
3092 if ((res = c.getField0(name)) != null) {
3093 return res;
3094 }
3095 }
3096 // Direct superclass, recursively
3097 if (!isInterface()) {
3098 Class<?> c = getSuperclass();
3099 if (c != null) {
3100 if ((res = c.getField0(name)) != null) {
3101 return res;
3102 }
3103 }
3104 }
3105 return null;
3106 }
3107
3108 // This method does not copy the returned Method object!
3109 private static Method searchMethods(Method[] methods,
3110 String name,
3111 Class<?>[] parameterTypes)
3112 {
3113 ReflectionFactory fact = getReflectionFactory();
3114 Method res = null;
3115 for (Method m : methods) {
3116 if (m.getName().equals(name)
3117 && arrayContentsEq(parameterTypes,
3118 fact.getExecutableSharedParameterTypes(m))
3119 && (res == null
3120 || (res.getReturnType() != m.getReturnType()
3121 && res.getReturnType().isAssignableFrom(m.getReturnType()))))
3122 res = m;
3123 }
3124 return res;
3125 }
3126
3127 private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
3128
3129 // Returns a "root" Method object. This Method object must NOT
3130 // be propagated to the outside world, but must instead be copied
3131 // via ReflectionFactory.copyMethod.
3132 private Method getMethod0(String name, Class<?>[] parameterTypes) {
3133 PublicMethods.MethodList res = getMethodsRecursive(
3134 name,
3135 parameterTypes == null ? EMPTY_CLASS_ARRAY : parameterTypes,
3136 /* includeStatic */ true, /* publicOnly */ true);
3137 return res == null ? null : res.getMostSpecific();
3138 }
3139
3140 // Returns a list of "root" Method objects. These Method objects must NOT
3141 // be propagated to the outside world, but must instead be copied
3142 // via ReflectionFactory.copyMethod.
3143 private PublicMethods.MethodList getMethodsRecursive(String name,
3144 Class<?>[] parameterTypes,
3145 boolean includeStatic,
3146 boolean publicOnly) {
3147 // 1st check declared methods
3148 Method[] methods = privateGetDeclaredMethods(publicOnly);
3149 PublicMethods.MethodList res = PublicMethods.MethodList
3150 .filter(methods, name, parameterTypes, includeStatic);
3151 // if there is at least one match among declared methods, we need not
3152 // search any further as such match surely overrides matching methods
3153 // declared in superclass(es) or interface(s).
3154 if (res != null) {
3155 return res;
3156 }
3157
3158 // if there was no match among declared methods,
3159 // we must consult the superclass (if any) recursively...
3160 Class<?> sc = getSuperclass();
3161 if (sc != null) {
3162 res = sc.getMethodsRecursive(name, parameterTypes, includeStatic, publicOnly);
3163 }
3164
3165 // ...and coalesce the superclass methods with methods obtained
3166 // from directly implemented interfaces excluding static methods...
3167 for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
3168 res = PublicMethods.MethodList.merge(
3169 res, intf.getMethodsRecursive(name, parameterTypes, /* includeStatic */ false, publicOnly));
3170 }
3171
3172 return res;
3173 }
3174
3175 // Returns a "root" Constructor object. This Constructor object must NOT
3176 // be propagated to the outside world, but must instead be copied
3177 // via ReflectionFactory.copyConstructor.
3178 private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3179 int which) throws NoSuchMethodException
3180 {
3181 ReflectionFactory fact = getReflectionFactory();
3182 Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3183 for (Constructor<T> constructor : constructors) {
3184 if (arrayContentsEq(parameterTypes,
3185 fact.getExecutableSharedParameterTypes(constructor))) {
3186 return constructor;
3187 }
3188 }
3189 throw new NoSuchMethodException(methodToString("<init>", parameterTypes));
3190 }
3191
3192 //
3193 // Other helpers and base implementation
3194 //
3195
3196 private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3197 if (a1 == null) {
3198 return a2 == null || a2.length == 0;
3199 }
3200
3201 if (a2 == null) {
3202 return a1.length == 0;
3203 }
3204
3205 if (a1.length != a2.length) {
3206 return false;
3207 }
3208
3209 for (int i = 0; i < a1.length; i++) {
3210 if (a1[i] != a2[i]) {
3211 return false;
3212 }
3213 }
3214
3215 return true;
3216 }
3217
3218 private static Field[] copyFields(Field[] arg) {
3219 Field[] out = new Field[arg.length];
3220 ReflectionFactory fact = getReflectionFactory();
3221 for (int i = 0; i < arg.length; i++) {
3222 out[i] = fact.copyField(arg[i]);
3223 }
3224 return out;
3225 }
3226
3227 private static Method[] copyMethods(Method[] arg) {
3228 Method[] out = new Method[arg.length];
3229 ReflectionFactory fact = getReflectionFactory();
3230 for (int i = 0; i < arg.length; i++) {
3231 out[i] = fact.copyMethod(arg[i]);
3232 }
3233 return out;
3234 }
3235
3236 private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
3237 Constructor<U>[] out = arg.clone();
3238 ReflectionFactory fact = getReflectionFactory();
3239 for (int i = 0; i < out.length; i++) {
3240 out[i] = fact.copyConstructor(out[i]);
3241 }
3242 return out;
3243 }
3244
3245 private native Field[] getDeclaredFields0(boolean publicOnly);
3246 private native Method[] getDeclaredMethods0(boolean publicOnly);
3247 private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3248 private native Class<?>[] getDeclaredClasses0();
3249
3250 /*
3251 * Returns an array containing the components of the Record attribute,
3252 * or null if the attribute is not present.
3253 *
3254 * Note that this method returns non-null array on a class with
3255 * the Record attribute even if this class is not a record.
3256 */
3257 private native RecordComponent[] getRecordComponents0();
3258 private native boolean isRecord0();
3259
3260 /**
3261 * Helper method to get the method name from arguments.
3262 */
3263 private String methodToString(String name, Class<?>[] argTypes) {
3264 return getName() + '.' + name +
3265 ((argTypes == null || argTypes.length == 0) ?
3266 "()" :
3267 Arrays.stream(argTypes)
3268 .map(c -> c == null ? "null" : c.getName())
3269 .collect(Collectors.joining(",", "(", ")")));
3270 }
3271
3272 /** use serialVersionUID from JDK 1.1 for interoperability */
3273 @java.io.Serial
3274 private static final long serialVersionUID = 3206093459760846163L;
3275
3276
3277 /**
3278 * Class Class is special cased within the Serialization Stream Protocol.
3279 *
3280 * A Class instance is written initially into an ObjectOutputStream in the
3281 * following format:
3282 * <pre>
3283 * {@code TC_CLASS} ClassDescriptor
3284 * A ClassDescriptor is a special cased serialization of
3285 * a {@code java.io.ObjectStreamClass} instance.
3286 * </pre>
3287 * A new handle is generated for the initial time the class descriptor
3288 * is written into the stream. Future references to the class descriptor
3289 * are written as references to the initial class descriptor instance.
3290 *
3291 * @see java.io.ObjectStreamClass
3292 */
3293 @java.io.Serial
3294 private static final ObjectStreamField[] serialPersistentFields =
3295 new ObjectStreamField[0];
3296
3297
3298 /**
3299 * Returns the assertion status that would be assigned to this
3300 * class if it were to be initialized at the time this method is invoked.
3301 * If this class has had its assertion status set, the most recent
3302 * setting will be returned; otherwise, if any package default assertion
3303 * status pertains to this class, the most recent setting for the most
3304 * specific pertinent package default assertion status is returned;
3305 * otherwise, if this class is not a system class (i.e., it has a
3306 * class loader) its class loader's default assertion status is returned;
3307 * otherwise, the system class default assertion status is returned.
3308 *
3309 * @apiNote
3310 * Few programmers will have any need for this method; it is provided
3311 * for the benefit of the JDK itself. (It allows a class to determine at
3312 * the time that it is initialized whether assertions should be enabled.)
3313 * Note that this method is not guaranteed to return the actual
3314 * assertion status that was (or will be) associated with the specified
3315 * class when it was (or will be) initialized.
3316 *
3317 * @return the desired assertion status of the specified class.
3318 * @see java.lang.ClassLoader#setClassAssertionStatus
3319 * @see java.lang.ClassLoader#setPackageAssertionStatus
3320 * @see java.lang.ClassLoader#setDefaultAssertionStatus
3321 * @since 1.4
3322 */
3323 public boolean desiredAssertionStatus() {
3324 ClassLoader loader = classLoader;
3325 // If the loader is null this is a system class, so ask the VM
3326 if (loader == null)
3327 return desiredAssertionStatus0(this);
3328
3329 // If the classloader has been initialized with the assertion
3330 // directives, ask it. Otherwise, ask the VM.
3331 synchronized(loader.assertionLock) {
3332 if (loader.classAssertionStatus != null) {
3333 return loader.desiredAssertionStatus(getName());
3334 }
3335 }
3336 return desiredAssertionStatus0(this);
3337 }
3338
3339 // Retrieves the desired assertion status of this class from the VM
3340 private static native boolean desiredAssertionStatus0(Class<?> clazz);
3341
3342 /**
3343 * Returns true if and only if this class was declared as an enum in the
3344 * source code.
3345 *
3346 * Note that {@link java.lang.Enum} is not itself an enum class.
3347 *
3348 * Also note that if an enum constant is declared with a class body,
3349 * the class of that enum constant object is an anonymous class
3350 * and <em>not</em> the class of the declaring enum class. The
3351 * {@link Enum#getDeclaringClass} method of an enum constant can
3352 * be used to get the class of the enum class declaring the
3353 * constant.
3354 *
3355 * @return true if and only if this class was declared as an enum in the
3356 * source code
3357 * @since 1.5
3358 * @jls 8.9.1 Enum Constants
3359 */
3360 public boolean isEnum() {
3361 // An enum must both directly extend java.lang.Enum and have
3362 // the ENUM bit set; classes for specialized enum constants
3363 // don't do the former.
3364 return (this.getModifiers() & ENUM) != 0 &&
3365 this.getSuperclass() == java.lang.Enum.class;
3366 }
3367
3368 /**
3369 * Returns {@code true} if and only if this class is a record class.
3370 *
3371 * <p> The {@linkplain #getSuperclass() direct superclass} of a record
3372 * class is {@code java.lang.Record}. A record class is {@linkplain
3373 * Modifier#FINAL final}. A record class has (possibly zero) record
3374 * components; {@link #getRecordComponents()} returns a non-null but
3375 * possibly empty value for a record.
3376 *
3377 * <p> Note that class {@link Record} is not a record class and thus
3378 * invoking this method on class {@code Record} returns {@code false}.
3379 *
3380 * @return true if and only if this class is a record class, otherwise false
3381 * @jls 8.10 Record Classes
3382 * @since 16
3383 */
3384 public boolean isRecord() {
3385 // this superclass and final modifier check is not strictly necessary
3386 // they are intrinsified and serve as a fast-path check
3387 return getSuperclass() == java.lang.Record.class &&
3388 (this.getModifiers() & Modifier.FINAL) != 0 &&
3389 isRecord0();
3390 }
3391
3392 // Fetches the factory for reflective objects
3393 private static ReflectionFactory getReflectionFactory() {
3394 var factory = reflectionFactory;
3395 if (factory != null) {
3396 return factory;
3397 }
3398 return reflectionFactory = ReflectionFactory.getReflectionFactory();
3399 }
3400 private static ReflectionFactory reflectionFactory;
3401
3402 /**
3403 * When CDS is enabled, the Class class may be aot-initialized. However,
3404 * we can't archive reflectionFactory, so we reset it to null, so it
3405 * will be allocated again at runtime.
3406 */
3407 private static void resetArchivedStates() {
3408 reflectionFactory = null;
3409 }
3410
3411 /**
3412 * Returns the elements of this enum class or null if this
3413 * Class object does not represent an enum class.
3414 *
3415 * @return an array containing the values comprising the enum class
3416 * represented by this {@code Class} object in the order they're
3417 * declared, or null if this {@code Class} object does not
3418 * represent an enum class
3419 * @since 1.5
3420 * @jls 8.9.1 Enum Constants
3421 */
3422 public T[] getEnumConstants() {
3423 T[] values = getEnumConstantsShared();
3424 return (values != null) ? values.clone() : null;
3425 }
3426
3427 /**
3428 * Returns the elements of this enum class or null if this
3429 * Class object does not represent an enum class;
3430 * identical to getEnumConstants except that the result is
3431 * uncloned, cached, and shared by all callers.
3432 */
3433 T[] getEnumConstantsShared() {
3434 T[] constants = enumConstants;
3435 if (constants == null) {
3436 if (!isEnum()) return null;
3437 try {
3438 final Method values = getMethod("values");
3439 values.setAccessible(true);
3440 @SuppressWarnings("unchecked")
3441 T[] temporaryConstants = (T[])values.invoke(null);
3442 enumConstants = constants = temporaryConstants;
3443 }
3444 // These can happen when users concoct enum-like classes
3445 // that don't comply with the enum spec.
3446 catch (InvocationTargetException | NoSuchMethodException |
3447 IllegalAccessException | NullPointerException |
3448 ClassCastException ex) { return null; }
3449 }
3450 return constants;
3451 }
3452 private transient volatile T[] enumConstants;
3453
3454 /**
3455 * Returns a map from simple name to enum constant. This package-private
3456 * method is used internally by Enum to implement
3457 * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}
3458 * efficiently. Note that the map is returned by this method is
3459 * created lazily on first use. Typically it won't ever get created.
3460 */
3461 Map<String, T> enumConstantDirectory() {
3462 Map<String, T> directory = enumConstantDirectory;
3463 if (directory == null) {
3464 T[] universe = getEnumConstantsShared();
3465 if (universe == null)
3466 throw new IllegalArgumentException(
3467 getName() + " is not an enum class");
3468 directory = HashMap.newHashMap(universe.length);
3469 for (T constant : universe) {
3470 directory.put(((Enum<?>)constant).name(), constant);
3471 }
3472 enumConstantDirectory = directory;
3473 }
3474 return directory;
3475 }
3476 private transient volatile Map<String, T> enumConstantDirectory;
3477
3478 /**
3479 * Casts an object to the class or interface represented
3480 * by this {@code Class} object.
3481 *
3482 * @param obj the object to be cast, may be {@code null}
3483 * @return the object after casting, or null if obj is null
3484 *
3485 * @throws ClassCastException if the object is not
3486 * null and is not assignable to the type T.
3487 *
3488 * @since 1.5
3489 */
3490 @SuppressWarnings("unchecked")
3491 @IntrinsicCandidate
3492 public T cast(Object obj) {
3493 if (obj != null && !isInstance(obj))
3494 throw new ClassCastException(cannotCastMsg(obj));
3495 return (T) obj;
3496 }
3497
3498 private String cannotCastMsg(Object obj) {
3499 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3500 }
3501
3502 /**
3503 * Casts this {@code Class} object to represent a subclass of the class
3504 * represented by the specified class object. Checks that the cast
3505 * is valid, and throws a {@code ClassCastException} if it is not. If
3506 * this method succeeds, it always returns a reference to this {@code Class} object.
3507 *
3508 * <p>This method is useful when a client needs to "narrow" the type of
3509 * a {@code Class} object to pass it to an API that restricts the
3510 * {@code Class} objects that it is willing to accept. A cast would
3511 * generate a compile-time warning, as the correctness of the cast
3512 * could not be checked at runtime (because generic types are implemented
3513 * by erasure).
3514 *
3515 * @param <U> the type to cast this {@code Class} object to
3516 * @param clazz the class of the type to cast this {@code Class} object to
3517 * @return this {@code Class} object, cast to represent a subclass of
3518 * the specified class object.
3519 * @throws ClassCastException if this {@code Class} object does not
3520 * represent a subclass of the specified class (here "subclass" includes
3521 * the class itself).
3522 * @since 1.5
3523 */
3524 @SuppressWarnings("unchecked")
3525 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
3526 if (clazz.isAssignableFrom(this))
3527 return (Class<? extends U>) this;
3528 else
3529 throw new ClassCastException(this.toString());
3530 }
3531
3532 /**
3533 * {@inheritDoc}
3534 * <p>Note that any annotation returned by this method is a
3535 * declaration annotation.
3536 *
3537 * @since 1.5
3538 */
3539 @Override
3540 @SuppressWarnings("unchecked")
3541 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
3542 Objects.requireNonNull(annotationClass);
3543
3544 return (A) annotationData().annotations.get(annotationClass);
3545 }
3546
3547 /**
3548 * {@inheritDoc}
3549 * @since 1.5
3550 */
3551 @Override
3552 public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
3553 return GenericDeclaration.super.isAnnotationPresent(annotationClass);
3554 }
3555
3556 /**
3557 * {@inheritDoc}
3558 * <p>Note that any annotations returned by this method are
3559 * declaration annotations.
3560 *
3561 * @since 1.8
3562 */
3563 @Override
3564 public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {
3565 Objects.requireNonNull(annotationClass);
3566
3567 AnnotationData annotationData = annotationData();
3568 return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations,
3569 this,
3570 annotationClass);
3571 }
3572
3573 /**
3574 * {@inheritDoc}
3575 * <p>Note that any annotations returned by this method are
3576 * declaration annotations.
3577 *
3578 * @since 1.5
3579 */
3580 @Override
3581 public Annotation[] getAnnotations() {
3582 return AnnotationParser.toArray(annotationData().annotations);
3583 }
3584
3585 /**
3586 * {@inheritDoc}
3587 * <p>Note that any annotation returned by this method is a
3588 * declaration annotation.
3589 *
3590 * @since 1.8
3591 */
3592 @Override
3593 @SuppressWarnings("unchecked")
3594 public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
3595 Objects.requireNonNull(annotationClass);
3596
3597 return (A) annotationData().declaredAnnotations.get(annotationClass);
3598 }
3599
3600 /**
3601 * {@inheritDoc}
3602 * <p>Note that any annotations returned by this method are
3603 * declaration annotations.
3604 *
3605 * @since 1.8
3606 */
3607 @Override
3608 public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {
3609 Objects.requireNonNull(annotationClass);
3610
3611 return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,
3612 annotationClass);
3613 }
3614
3615 /**
3616 * {@inheritDoc}
3617 * <p>Note that any annotations returned by this method are
3618 * declaration annotations.
3619 *
3620 * @since 1.5
3621 */
3622 @Override
3623 public Annotation[] getDeclaredAnnotations() {
3624 return AnnotationParser.toArray(annotationData().declaredAnnotations);
3625 }
3626
3627 // annotation data that might get invalidated when JVM TI RedefineClasses() is called
3628 private static class AnnotationData {
3629 final Map<Class<? extends Annotation>, Annotation> annotations;
3630 final Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
3631
3632 // Value of classRedefinedCount when we created this AnnotationData instance
3633 final int redefinedCount;
3634
3635 AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations,
3636 Map<Class<? extends Annotation>, Annotation> declaredAnnotations,
3637 int redefinedCount) {
3638 this.annotations = annotations;
3639 this.declaredAnnotations = declaredAnnotations;
3640 this.redefinedCount = redefinedCount;
3641 }
3642 }
3643
3644 // Annotations cache
3645 @SuppressWarnings("UnusedDeclaration")
3646 private transient volatile AnnotationData annotationData;
3647
3648 private AnnotationData annotationData() {
3649 while (true) { // retry loop
3650 AnnotationData annotationData = this.annotationData;
3651 int classRedefinedCount = this.classRedefinedCount;
3652 if (annotationData != null &&
3653 annotationData.redefinedCount == classRedefinedCount) {
3654 return annotationData;
3655 }
3656 // null or stale annotationData -> optimistically create new instance
3657 AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount);
3658 // try to install it
3659 if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) {
3660 // successfully installed new AnnotationData
3661 return newAnnotationData;
3662 }
3663 }
3664 }
3665
3666 private AnnotationData createAnnotationData(int classRedefinedCount) {
3667 Map<Class<? extends Annotation>, Annotation> declaredAnnotations =
3668 AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this);
3669 Class<?> superClass = getSuperclass();
3670 Map<Class<? extends Annotation>, Annotation> annotations = null;
3671 if (superClass != null) {
3672 Map<Class<? extends Annotation>, Annotation> superAnnotations =
3673 superClass.annotationData().annotations;
3674 for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) {
3675 Class<? extends Annotation> annotationClass = e.getKey();
3676 if (AnnotationType.getInstance(annotationClass).isInherited()) {
3677 if (annotations == null) { // lazy construction
3678 annotations = LinkedHashMap.newLinkedHashMap(Math.max(
3679 declaredAnnotations.size(),
3680 Math.min(12, declaredAnnotations.size() + superAnnotations.size())
3681 )
3682 );
3683 }
3684 annotations.put(annotationClass, e.getValue());
3685 }
3686 }
3687 }
3688 if (annotations == null) {
3689 // no inherited annotations -> share the Map with declaredAnnotations
3690 annotations = declaredAnnotations;
3691 } else {
3692 // at least one inherited annotation -> declared may override inherited
3693 annotations.putAll(declaredAnnotations);
3694 }
3695 return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount);
3696 }
3697
3698 // Annotation interfaces cache their internal (AnnotationType) form
3699
3700 @SuppressWarnings("UnusedDeclaration")
3701 private transient volatile AnnotationType annotationType;
3702
3703 boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {
3704 return Atomic.casAnnotationType(this, oldType, newType);
3705 }
3706
3707 AnnotationType getAnnotationType() {
3708 return annotationType;
3709 }
3710
3711 Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() {
3712 return annotationData().declaredAnnotations;
3713 }
3714
3715 /* Backing store of user-defined values pertaining to this class.
3716 * Maintained by the ClassValue class.
3717 */
3718 transient ClassValue.ClassValueMap classValueMap;
3719
3720 /**
3721 * Returns an {@code AnnotatedType} object that represents the use of a
3722 * type to specify the superclass of the entity represented by this {@code
3723 * Class} object. (The <em>use</em> of type Foo to specify the superclass
3724 * in '... extends Foo' is distinct from the <em>declaration</em> of class
3725 * Foo.)
3726 *
3727 * <p> If this {@code Class} object represents a class whose declaration
3728 * does not explicitly indicate an annotated superclass, then the return
3729 * value is an {@code AnnotatedType} object representing an element with no
3730 * annotations.
3731 *
3732 * <p> If this {@code Class} represents either the {@code Object} class, an
3733 * interface type, an array type, a primitive type, or void, the return
3734 * value is {@code null}.
3735 *
3736 * @return an object representing the superclass
3737 * @since 1.8
3738 */
3739 public AnnotatedType getAnnotatedSuperclass() {
3740 if (this == Object.class ||
3741 isInterface() ||
3742 isArray() ||
3743 isPrimitive() ||
3744 this == Void.TYPE) {
3745 return null;
3746 }
3747
3748 return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
3749 }
3750
3751 /**
3752 * Returns an array of {@code AnnotatedType} objects that represent the use
3753 * of types to specify superinterfaces of the entity represented by this
3754 * {@code Class} object. (The <em>use</em> of type Foo to specify a
3755 * superinterface in '... implements Foo' is distinct from the
3756 * <em>declaration</em> of interface Foo.)
3757 *
3758 * <p> If this {@code Class} object represents a class, the return value is
3759 * an array containing objects representing the uses of interface types to
3760 * specify interfaces implemented by the class. The order of the objects in
3761 * the array corresponds to the order of the interface types used in the
3762 * 'implements' clause of the declaration of this {@code Class} object.
3763 *
3764 * <p> If this {@code Class} object represents an interface, the return
3765 * value is an array containing objects representing the uses of interface
3766 * types to specify interfaces directly extended by the interface. The
3767 * order of the objects in the array corresponds to the order of the
3768 * interface types used in the 'extends' clause of the declaration of this
3769 * {@code Class} object.
3770 *
3771 * <p> If this {@code Class} object represents a class or interface whose
3772 * declaration does not explicitly indicate any annotated superinterfaces,
3773 * the return value is an array of length 0.
3774 *
3775 * <p> If this {@code Class} object represents either the {@code Object}
3776 * class, an array type, a primitive type, or void, the return value is an
3777 * array of length 0.
3778 *
3779 * @return an array representing the superinterfaces
3780 * @since 1.8
3781 */
3782 public AnnotatedType[] getAnnotatedInterfaces() {
3783 return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3784 }
3785
3786 private native Class<?> getNestHost0();
3787
3788 /**
3789 * Returns the nest host of the <a href=#nest>nest</a> to which the class
3790 * or interface represented by this {@code Class} object belongs.
3791 * Every class and interface belongs to exactly one nest.
3792 *
3793 * If the nest host of this class or interface has previously
3794 * been determined, then this method returns the nest host.
3795 * If the nest host of this class or interface has
3796 * not previously been determined, then this method determines the nest
3797 * host using the algorithm of JVMS 5.4.4, and returns it.
3798 *
3799 * Often, a class or interface belongs to a nest consisting only of itself,
3800 * in which case this method returns {@code this} to indicate that the class
3801 * or interface is the nest host.
3802 *
3803 * <p>If this {@code Class} object represents a primitive type, an array type,
3804 * or {@code void}, then this method returns {@code this},
3805 * indicating that the represented entity belongs to the nest consisting only of
3806 * itself, and is the nest host.
3807 *
3808 * @return the nest host of this class or interface
3809 *
3810 * @since 11
3811 * @jvms 4.7.28 The {@code NestHost} Attribute
3812 * @jvms 4.7.29 The {@code NestMembers} Attribute
3813 * @jvms 5.4.4 Access Control
3814 */
3815 public Class<?> getNestHost() {
3816 if (isPrimitive() || isArray()) {
3817 return this;
3818 }
3819 return getNestHost0();
3820 }
3821
3822 /**
3823 * Determines if the given {@code Class} is a nestmate of the
3824 * class or interface represented by this {@code Class} object.
3825 * Two classes or interfaces are nestmates
3826 * if they have the same {@linkplain #getNestHost() nest host}.
3827 *
3828 * @param c the class to check
3829 * @return {@code true} if this class and {@code c} are members of
3830 * the same nest; and {@code false} otherwise.
3831 *
3832 * @since 11
3833 */
3834 public boolean isNestmateOf(Class<?> c) {
3835 Objects.requireNonNull(c);
3836 if (this == c) {
3837 return true;
3838 }
3839 if (isPrimitive() || isArray() ||
3840 c.isPrimitive() || c.isArray()) {
3841 return false;
3842 }
3843
3844 return getNestHost() == c.getNestHost();
3845 }
3846
3847 private native Class<?>[] getNestMembers0();
3848
3849 /**
3850 * Returns an array containing {@code Class} objects representing all the
3851 * classes and interfaces that are members of the nest to which the class
3852 * or interface represented by this {@code Class} object belongs.
3853 *
3854 * First, this method obtains the {@linkplain #getNestHost() nest host},
3855 * {@code H}, of the nest to which the class or interface represented by
3856 * this {@code Class} object belongs. The zeroth element of the returned
3857 * array is {@code H}.
3858 *
3859 * Then, for each class or interface {@code C} which is recorded by {@code H}
3860 * as being a member of its nest, this method attempts to obtain the {@code Class}
3861 * object for {@code C} (using {@linkplain #getClassLoader() the defining class
3862 * loader} of the current {@code Class} object), and then obtains the
3863 * {@linkplain #getNestHost() nest host} of the nest to which {@code C} belongs.
3864 * The classes and interfaces which are recorded by {@code H} as being members
3865 * of its nest, and for which {@code H} can be determined as their nest host,
3866 * are indicated by subsequent elements of the returned array. The order of
3867 * such elements is unspecified. Duplicates are permitted.
3868 *
3869 * <p>If this {@code Class} object represents a primitive type, an array type,
3870 * or {@code void}, then this method returns a single-element array containing
3871 * {@code this}.
3872 *
3873 * @apiNote
3874 * The returned array includes only the nest members recorded in the {@code NestMembers}
3875 * attribute, and not any hidden classes that were added to the nest via
3876 * {@link MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
3877 * Lookup::defineHiddenClass}.
3878 *
3879 * @return an array of all classes and interfaces in the same nest as
3880 * this class or interface
3881 *
3882 * @since 11
3883 * @see #getNestHost()
3884 * @jvms 4.7.28 The {@code NestHost} Attribute
3885 * @jvms 4.7.29 The {@code NestMembers} Attribute
3886 */
3887 public Class<?>[] getNestMembers() {
3888 if (isPrimitive() || isArray()) {
3889 return new Class<?>[] { this };
3890 }
3891 Class<?>[] members = getNestMembers0();
3892 // Can't actually enable this due to bootstrapping issues
3893 // assert(members.length != 1 || members[0] == this); // expected invariant from VM
3894 return members;
3895 }
3896
3897 /**
3898 * Returns the descriptor string of the entity (class, interface, array class,
3899 * primitive type, or {@code void}) represented by this {@code Class} object.
3900 *
3901 * <p> If this {@code Class} object represents a class or interface,
3902 * not an array class, then:
3903 * <ul>
3904 * <li> If the class or interface is not {@linkplain Class#isHidden() hidden},
3905 * then the result is a field descriptor (JVMS {@jvms 4.3.2})
3906 * for the class or interface. Calling
3907 * {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor}
3908 * with the result descriptor string produces a {@link ClassDesc ClassDesc}
3909 * describing this class or interface.
3910 * <li> If the class or interface is {@linkplain Class#isHidden() hidden},
3911 * then the result is a string of the form:
3912 * <blockquote>
3913 * {@code "L" +} <em>N</em> {@code + "." + <suffix> + ";"}
3914 * </blockquote>
3915 * where <em>N</em> is the {@linkplain ClassLoader##binary-name binary name}
3916 * encoded in internal form indicated by the {@code class} file passed to
3917 * {@link MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
3918 * Lookup::defineHiddenClass}, and {@code <suffix>} is an unqualified name.
3919 * A hidden class or interface has no {@linkplain ClassDesc nominal descriptor}.
3920 * The result string is not a type descriptor.
3921 * </ul>
3922 *
3923 * <p> If this {@code Class} object represents an array class, then
3924 * the result is a string consisting of one or more '{@code [}' characters
3925 * representing the depth of the array nesting, followed by the
3926 * descriptor string of the element type.
3927 * <ul>
3928 * <li> If the element type is not a {@linkplain Class#isHidden() hidden} class
3929 * or interface, then this array class can be described nominally.
3930 * Calling {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor}
3931 * with the result descriptor string produces a {@link ClassDesc ClassDesc}
3932 * describing this array class.
3933 * <li> If the element type is a {@linkplain Class#isHidden() hidden} class or
3934 * interface, then this array class cannot be described nominally.
3935 * The result string is not a type descriptor.
3936 * </ul>
3937 *
3938 * <p> If this {@code Class} object represents a primitive type or
3939 * {@code void}, then the result is a field descriptor string which
3940 * is a one-letter code corresponding to a primitive type or {@code void}
3941 * ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}).
3942 *
3943 * @return the descriptor string for this {@code Class} object
3944 * @jvms 4.3.2 Field Descriptors
3945 * @since 12
3946 */
3947 @Override
3948 public String descriptorString() {
3949 if (isPrimitive())
3950 return Wrapper.forPrimitiveType(this).basicTypeString();
3951
3952 if (isArray()) {
3953 return "[".concat(componentType.descriptorString());
3954 } else if (isHidden()) {
3955 String name = getName();
3956 int index = name.indexOf('/');
3957 return new StringBuilder(name.length() + 2)
3958 .append('L')
3959 .append(name.substring(0, index).replace('.', '/'))
3960 .append('.')
3961 .append(name, index + 1, name.length())
3962 .append(';')
3963 .toString();
3964 } else {
3965 String name = getName().replace('.', '/');
3966 return StringConcatHelper.concat("L", name, ";");
3967 }
3968 }
3969
3970 /**
3971 * Returns the component type of this {@code Class}, if it describes
3972 * an array type, or {@code null} otherwise.
3973 *
3974 * @implSpec
3975 * Equivalent to {@link Class#getComponentType()}.
3976 *
3977 * @return a {@code Class} describing the component type, or {@code null}
3978 * if this {@code Class} does not describe an array type
3979 * @since 12
3980 */
3981 @Override
3982 public Class<?> componentType() {
3983 return getComponentType();
3984 }
3985
3986 /**
3987 * Returns a {@code Class} for an array type whose component type
3988 * is described by this {@linkplain Class}.
3989 *
3990 * @throws UnsupportedOperationException if this component type is {@linkplain
3991 * Void#TYPE void} or if the number of dimensions of the resulting array
3992 * type would exceed 255.
3993 * @return a {@code Class} describing the array type
3994 * @jvms 4.3.2 Field Descriptors
3995 * @jvms 4.4.1 The {@code CONSTANT_Class_info} Structure
3996 * @since 12
3997 */
3998 @Override
3999 public Class<?> arrayType() {
4000 try {
4001 return Array.newInstance(this, 0).getClass();
4002 } catch (IllegalArgumentException iae) {
4003 throw new UnsupportedOperationException(iae);
4004 }
4005 }
4006
4007 /**
4008 * Returns a nominal descriptor for this instance, if one can be
4009 * constructed, or an empty {@link Optional} if one cannot be.
4010 *
4011 * @return An {@link Optional} containing the resulting nominal descriptor,
4012 * or an empty {@link Optional} if one cannot be constructed.
4013 * @since 12
4014 */
4015 @Override
4016 public Optional<ClassDesc> describeConstable() {
4017 Class<?> c = isArray() ? elementType() : this;
4018 return c.isHidden() ? Optional.empty()
4019 : Optional.of(ConstantUtils.classDesc(this));
4020 }
4021
4022 /**
4023 * Returns {@code true} if and only if the underlying class is a hidden class.
4024 *
4025 * @return {@code true} if and only if this class is a hidden class.
4026 *
4027 * @since 15
4028 * @see MethodHandles.Lookup#defineHiddenClass
4029 * @see Class##hiddenClasses Hidden Classes
4030 */
4031 @IntrinsicCandidate
4032 public native boolean isHidden();
4033
4034 /**
4035 * Returns an array containing {@code Class} objects representing the
4036 * direct subinterfaces or subclasses permitted to extend or
4037 * implement this class or interface if it is sealed. The order of such elements
4038 * is unspecified. The array is empty if this sealed class or interface has no
4039 * permitted subclass. If this {@code Class} object represents a primitive type,
4040 * {@code void}, an array type, or a class or interface that is not sealed,
4041 * that is {@link #isSealed()} returns {@code false}, then this method returns {@code null}.
4042 * Conversely, if {@link #isSealed()} returns {@code true}, then this method
4043 * returns a non-null value.
4044 *
4045 * For each class or interface {@code C} which is recorded as a permitted
4046 * direct subinterface or subclass of this class or interface,
4047 * this method attempts to obtain the {@code Class}
4048 * object for {@code C} (using {@linkplain #getClassLoader() the defining class
4049 * loader} of the current {@code Class} object).
4050 * The {@code Class} objects which can be obtained and which are direct
4051 * subinterfaces or subclasses of this class or interface,
4052 * are indicated by elements of the returned array. If a {@code Class} object
4053 * cannot be obtained, it is silently ignored, and not included in the result
4054 * array.
4055 *
4056 * @return an array of {@code Class} objects of the permitted subclasses of this class
4057 * or interface, or {@code null} if this class or interface is not sealed.
4058 *
4059 * @jls 8.1 Class Declarations
4060 * @jls 9.1 Interface Declarations
4061 * @since 17
4062 */
4063 public Class<?>[] getPermittedSubclasses() {
4064 Class<?>[] subClasses;
4065 if (isArray() || isPrimitive() || (subClasses = getPermittedSubclasses0()) == null) {
4066 return null;
4067 }
4068 if (subClasses.length > 0) {
4069 if (Arrays.stream(subClasses).anyMatch(c -> !isDirectSubType(c))) {
4070 subClasses = Arrays.stream(subClasses)
4071 .filter(this::isDirectSubType)
4072 .toArray(s -> new Class<?>[s]);
4073 }
4074 }
4075 return subClasses;
4076 }
4077
4078 private boolean isDirectSubType(Class<?> c) {
4079 if (isInterface()) {
4080 for (Class<?> i : c.getInterfaces(/* cloneArray */ false)) {
4081 if (i == this) {
4082 return true;
4083 }
4084 }
4085 } else {
4086 return c.getSuperclass() == this;
4087 }
4088 return false;
4089 }
4090
4091 /**
4092 * Returns {@code true} if and only if this {@code Class} object represents
4093 * a sealed class or interface. If this {@code Class} object represents a
4094 * primitive type, {@code void}, or an array type, this method returns
4095 * {@code false}. A sealed class or interface has (possibly zero) permitted
4096 * subclasses; {@link #getPermittedSubclasses()} returns a non-null but
4097 * possibly empty value for a sealed class or interface.
4098 *
4099 * @return {@code true} if and only if this {@code Class} object represents
4100 * a sealed class or interface.
4101 *
4102 * @jls 8.1 Class Declarations
4103 * @jls 9.1 Interface Declarations
4104 * @since 17
4105 */
4106 public boolean isSealed() {
4107 if (isArray() || isPrimitive()) {
4108 return false;
4109 }
4110 return getPermittedSubclasses() != null;
4111 }
4112
4113 private native Class<?>[] getPermittedSubclasses0();
4114
4115 /*
4116 * Return the class's major and minor class file version packed into an int.
4117 * The high order 16 bits contain the class's minor version. The low order
4118 * 16 bits contain the class's major version.
4119 *
4120 * If the class is an array type then the class file version of its element
4121 * type is returned. If the class is a primitive type then the latest class
4122 * file major version is returned and zero is returned for the minor version.
4123 */
4124 int getClassFileVersion() {
4125 Class<?> c = isArray() ? elementType() : this;
4126 return c.getClassFileVersion0();
4127 }
4128
4129 private native int getClassFileVersion0();
4130
4131 /**
4132 * Return the access flags as they were in the class's bytecode, including
4133 * the original setting of ACC_SUPER.
4134 *
4135 * If this {@code Class} object represents a primitive type or
4136 * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
4137 * {@code FINAL}.
4138 * If this {@code Class} object represents an array type, return 0.
4139 */
4140 int getClassFileAccessFlags() {
4141 return classFileAccessFlags;
4142 }
4143
4144 // Validates the length of the class name and throws an exception if it exceeds the maximum allowed length.
4145 private static void validateClassNameLength(String name) throws ClassNotFoundException {
4146 if (!ModifiedUtf.isValidLengthInConstantPool(name)) {
4147 throw new ClassNotFoundException(
4148 "Class name length exceeds limit of "
4149 + ModifiedUtf.CONSTANT_POOL_UTF8_MAX_BYTES
4150 + ": " + name.substring(0,256) + "...");
4151 }
4152 }
4153 }