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