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