1 /*
2 * Copyright (c) 1994, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package java.lang;
27
28 import java.lang.annotation.Annotation;
29 import java.lang.constant.ClassDesc;
30 import java.lang.constant.ConstantDescs;
31 import java.lang.invoke.TypeDescriptor;
32 import java.lang.invoke.MethodHandles;
33 import java.lang.ref.SoftReference;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.io.ObjectStreamField;
37 import java.lang.reflect.AnnotatedElement;
38 import java.lang.reflect.AnnotatedType;
39 import java.lang.reflect.AccessFlag;
40 import java.lang.reflect.Array;
41 import java.lang.reflect.ClassFileFormatVersion;
42 import java.lang.reflect.Constructor;
43 import java.lang.reflect.Executable;
44 import java.lang.reflect.Field;
45 import java.lang.reflect.GenericArrayType;
46 import java.lang.reflect.GenericDeclaration;
47 import java.lang.reflect.GenericSignatureFormatError;
48 import java.lang.reflect.InvocationTargetException;
49 import java.lang.reflect.Member;
50 import java.lang.reflect.Method;
51 import java.lang.reflect.Modifier;
52 import java.lang.reflect.RecordComponent;
53 import java.lang.reflect.Type;
54 import java.lang.reflect.TypeVariable;
55 import java.lang.constant.Constable;
56 import java.net.URL;
57 import java.security.AllPermission;
58 import java.security.Permissions;
59 import java.security.ProtectionDomain;
60 import java.util.ArrayList;
61 import java.util.Arrays;
62 import java.util.Collection;
63 import java.util.HashMap;
64 import java.util.HashSet;
65 import java.util.LinkedHashMap;
66 import java.util.LinkedHashSet;
67 import java.util.List;
68 import java.util.Map;
69 import java.util.Objects;
70 import java.util.Optional;
71 import java.util.Set;
72 import java.util.stream.Collectors;
73
74 import jdk.internal.constant.ConstantUtils;
75 import jdk.internal.javac.PreviewFeature;
76 import jdk.internal.loader.BootLoader;
77 import jdk.internal.loader.BuiltinClassLoader;
78 import jdk.internal.misc.PreviewFeatures;
79 import jdk.internal.misc.Unsafe;
80 import jdk.internal.module.Resources;
81 import jdk.internal.reflect.CallerSensitive;
82 import jdk.internal.reflect.CallerSensitiveAdapter;
83 import jdk.internal.reflect.ConstantPool;
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 Modifier#IDENTITY} is set in the
643 * {@linkplain #getModifiers() class modifiers}.
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 Modifier#IDENTITY} is not set in the
665 * {@linkplain #getModifiers() class modifiers}.
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> its {@code identity} modifier is always true
1403 * </ul>
1404 * If this {@code Class} object represents a primitive type or
1405 * void, its {@code public}, {@code abstract}, and {@code final}
1406 * modifiers are always {@code true}.
1407 * For {@code Class} objects representing void, primitive types, and
1408 * arrays, the values of other modifiers are {@code false} other
1409 * than as specified above.
1410 *
1411 * <p> The modifier encodings are defined in section {@jvms 4.1}
1412 * of <cite>The Java Virtual Machine Specification</cite>.
1413 *
1414 * @return the {@code int} representing the modifiers for this class
1415 * @see java.lang.reflect.Modifier
1416 * @see #accessFlags()
1417 * @see <a
1418 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
1419 * programming language and JVM modeling in core reflection</a>
1420 * @since 1.1
1421 * @jls 8.1.1 Class Modifiers
1422 * @jls 9.1.1 Interface Modifiers
1423 * @jvms 4.1 The {@code ClassFile} Structure
1424 */
1425 public int getModifiers() { return modifiers; }
1426
1427 /**
1428 * {@return an unmodifiable set of the {@linkplain AccessFlag access
1429 * flags} for this class, possibly empty}
1430 * The {@code AccessFlags} may depend on the class file format version of the class.
1431 *
1432 * <p> If the underlying class is an array class:
1433 * <ul>
1434 * <li> its {@code PUBLIC}, {@code PRIVATE} and {@code PROTECTED}
1435 * access flags are the same as those of its component type
1436 * <li> its {@code ABSTRACT} and {@code FINAL} flags are present
1437 * <li> its {@code INTERFACE} flag is absent, even when the
1438 * component type is an interface
1439 * <li> its {@code identity} modifier is always true
1440 * </ul>
1441 * If this {@code Class} object represents a primitive type or
1442 * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
1443 * {@code FINAL}.
1444 * For {@code Class} objects representing void, primitive types, and
1445 * arrays, access flags are absent other than as specified above.
1446 *
1447 * @see #getModifiers()
1448 * @jvms 4.1 The ClassFile Structure
1449 * @jvms 4.7.6 The InnerClasses Attribute
1450 * @since 20
1451 */
1452 public Set<AccessFlag> accessFlags() {
1453 // Location.CLASS allows SUPER and AccessFlag.MODULE which
1454 // INNER_CLASS forbids. INNER_CLASS allows PRIVATE, PROTECTED,
1455 // and STATIC, which are not allowed on Location.CLASS.
1456 // Use getClassFileAccessFlags to expose SUPER status.
1457 // Arrays need to use PRIVATE/PROTECTED from its component modifiers.
1458 var location = (isMemberClass() || isLocalClass() ||
1459 isAnonymousClass() || isArray()) ?
1460 AccessFlag.Location.INNER_CLASS :
1461 AccessFlag.Location.CLASS;
1462 int accessFlags = location == AccessFlag.Location.CLASS ? getClassFileAccessFlags() : getModifiers();
1463 var reflectionFactory = getReflectionFactory();
1464 var ans = reflectionFactory.parseAccessFlags(accessFlags, location, this);
1465 if (PreviewFeatures.isEnabled() && reflectionFactory.classFileFormatVersion(this) != ClassFileFormatVersion.CURRENT_PREVIEW_FEATURES
1466 && isIdentity()) {
1467 var set = new HashSet<>(ans);
1468 set.add(AccessFlag.IDENTITY);
1469 return Set.copyOf(set);
1470 }
1471 return ans;
1472 }
1473
1474 /**
1475 * Gets the signers of this class.
1476 *
1477 * @return the signers of this class, or null if there are no signers. In
1478 * particular, this method returns null if this {@code Class} object represents
1479 * a primitive type or void.
1480 * @since 1.1
1481 */
1482
1483 public Object[] getSigners() {
1484 var signers = this.signers;
1485 return signers == null ? null : signers.clone();
1486 }
1487
1488 /**
1489 * Set the signers of this class.
1490 */
1491 void setSigners(Object[] signers) {
1492 if (!isPrimitive() && !isArray()) {
1493 this.signers = signers;
1494 }
1495 }
1496
1497 /**
1498 * If this {@code Class} object represents a local or anonymous
1499 * class within a method, returns a {@link
1500 * java.lang.reflect.Method Method} object representing the
1501 * immediately enclosing method of the underlying class. Returns
1502 * {@code null} otherwise.
1503 *
1504 * In particular, this method returns {@code null} if the underlying
1505 * class is a local or anonymous class immediately enclosed by a class or
1506 * interface declaration, instance initializer or static initializer.
1507 *
1508 * @return the immediately enclosing method of the underlying class, if
1509 * that class is a local or anonymous class; otherwise {@code null}.
1510 *
1511 * @since 1.5
1512 */
1513 public Method getEnclosingMethod() {
1514 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1515
1516 if (enclosingInfo == null)
1517 return null;
1518 else {
1519 if (!enclosingInfo.isMethod())
1520 return null;
1521
1522 List<Class<?>> types = BytecodeDescriptor.parseMethod(enclosingInfo.getDescriptor(), getClassLoader());
1523 Class<?> returnType = types.removeLast();
1524 Class<?>[] parameterClasses = types.toArray(EMPTY_CLASS_ARRAY);
1525
1526 final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1527 Method[] candidates = enclosingCandidate.privateGetDeclaredMethods(false);
1528
1529 /*
1530 * Loop over all declared methods; match method name,
1531 * number of and type of parameters, *and* return
1532 * type. Matching return type is also necessary
1533 * because of covariant returns, etc.
1534 */
1535 ReflectionFactory fact = getReflectionFactory();
1536 for (Method m : candidates) {
1537 if (m.getName().equals(enclosingInfo.getName()) &&
1538 arrayContentsEq(parameterClasses,
1539 fact.getExecutableSharedParameterTypes(m))) {
1540 // finally, check return type
1541 if (m.getReturnType().equals(returnType)) {
1542 return fact.copyMethod(m);
1543 }
1544 }
1545 }
1546
1547 throw new InternalError("Enclosing method not found");
1548 }
1549 }
1550
1551 private native Object[] getEnclosingMethod0();
1552
1553 private EnclosingMethodInfo getEnclosingMethodInfo() {
1554 Object[] enclosingInfo = getEnclosingMethod0();
1555 if (enclosingInfo == null)
1556 return null;
1557 else {
1558 return new EnclosingMethodInfo(enclosingInfo);
1559 }
1560 }
1561
1562 private static final class EnclosingMethodInfo {
1563 private final Class<?> enclosingClass;
1564 private final String name;
1565 private final String descriptor;
1566
1567 static void validate(Object[] enclosingInfo) {
1568 if (enclosingInfo.length != 3)
1569 throw new InternalError("Malformed enclosing method information");
1570 try {
1571 // The array is expected to have three elements:
1572
1573 // the immediately enclosing class
1574 Class<?> enclosingClass = (Class<?>)enclosingInfo[0];
1575 assert(enclosingClass != null);
1576
1577 // the immediately enclosing method or constructor's
1578 // name (can be null).
1579 String name = (String)enclosingInfo[1];
1580
1581 // the immediately enclosing method or constructor's
1582 // descriptor (null iff name is).
1583 String descriptor = (String)enclosingInfo[2];
1584 assert((name != null && descriptor != null) || name == descriptor);
1585 } catch (ClassCastException cce) {
1586 throw new InternalError("Invalid type in enclosing method information", cce);
1587 }
1588 }
1589
1590 EnclosingMethodInfo(Object[] enclosingInfo) {
1591 validate(enclosingInfo);
1592 this.enclosingClass = (Class<?>)enclosingInfo[0];
1593 this.name = (String)enclosingInfo[1];
1594 this.descriptor = (String)enclosingInfo[2];
1595 }
1596
1597 boolean isPartial() {
1598 return enclosingClass == null || name == null || descriptor == null;
1599 }
1600
1601 boolean isConstructor() { return !isPartial() && ConstantDescs.INIT_NAME.equals(name); }
1602
1603 boolean isMethod() { return !isPartial() && !isConstructor() && !ConstantDescs.CLASS_INIT_NAME.equals(name); }
1604
1605 Class<?> getEnclosingClass() { return enclosingClass; }
1606
1607 String getName() { return name; }
1608
1609 String getDescriptor() {
1610 // hotspot validates this descriptor to be either a field or method
1611 // descriptor as the "type" in a NameAndType in verification.
1612 // So this can still be a field descriptor
1613 if (descriptor.isEmpty() || descriptor.charAt(0) != '(') {
1614 throw new GenericSignatureFormatError("Bad method signature: " + descriptor);
1615 }
1616 return descriptor;
1617 }
1618 }
1619
1620 private static Class<?> toClass(Type o) {
1621 if (o instanceof GenericArrayType gat)
1622 return toClass(gat.getGenericComponentType()).arrayType();
1623 return (Class<?>)o;
1624 }
1625
1626 /**
1627 * If this {@code Class} object represents a local or anonymous
1628 * class within a constructor, returns a {@link
1629 * java.lang.reflect.Constructor Constructor} object representing
1630 * the immediately enclosing constructor of the underlying
1631 * class. Returns {@code null} otherwise. In particular, this
1632 * method returns {@code null} if the underlying class is a local
1633 * or anonymous class immediately enclosed by a class or
1634 * interface declaration, instance initializer or static initializer.
1635 *
1636 * @return the immediately enclosing constructor of the underlying class, if
1637 * that class is a local or anonymous class; otherwise {@code null}.
1638 *
1639 * @since 1.5
1640 */
1641 public Constructor<?> getEnclosingConstructor() {
1642 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1643
1644 if (enclosingInfo == null)
1645 return null;
1646 else {
1647 if (!enclosingInfo.isConstructor())
1648 return null;
1649
1650 List<Class<?>> types = BytecodeDescriptor.parseMethod(enclosingInfo.getDescriptor(), getClassLoader());
1651 types.removeLast();
1652 Class<?>[] parameterClasses = types.toArray(EMPTY_CLASS_ARRAY);
1653
1654 final Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
1655 Constructor<?>[] candidates = enclosingCandidate
1656 .privateGetDeclaredConstructors(false);
1657 /*
1658 * Loop over all declared constructors; match number
1659 * of and type of parameters.
1660 */
1661 ReflectionFactory fact = getReflectionFactory();
1662 for (Constructor<?> c : candidates) {
1663 if (arrayContentsEq(parameterClasses,
1664 fact.getExecutableSharedParameterTypes(c))) {
1665 return fact.copyConstructor(c);
1666 }
1667 }
1668
1669 throw new InternalError("Enclosing constructor not found");
1670 }
1671 }
1672
1673
1674 /**
1675 * If the class or interface represented by this {@code Class} object
1676 * is a member of another class, returns the {@code Class} object
1677 * representing the class in which it was declared. This method returns
1678 * null if this class or interface is not a member of any other class. If
1679 * this {@code Class} object represents an array class, a primitive
1680 * type, or void, then this method returns null.
1681 *
1682 * @return the declaring class for this class
1683 * @since 1.1
1684 */
1685 public Class<?> getDeclaringClass() {
1686 return getDeclaringClass0();
1687 }
1688
1689 private native Class<?> getDeclaringClass0();
1690
1691
1692 /**
1693 * Returns the immediately enclosing class of the underlying
1694 * class. If the underlying class is a top level class this
1695 * method returns {@code null}.
1696 * @return the immediately enclosing class of the underlying class
1697 * @since 1.5
1698 */
1699 public Class<?> getEnclosingClass() {
1700 // There are five kinds of classes (or interfaces):
1701 // a) Top level classes
1702 // b) Nested classes (static member classes)
1703 // c) Inner classes (non-static member classes)
1704 // d) Local classes (named classes declared within a method)
1705 // e) Anonymous classes
1706
1707
1708 // JVM Spec 4.7.7: A class must have an EnclosingMethod
1709 // attribute if and only if it is a local class or an
1710 // anonymous class.
1711 EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
1712 Class<?> enclosingCandidate;
1713
1714 if (enclosingInfo == null) {
1715 // This is a top level or a nested class or an inner class (a, b, or c)
1716 enclosingCandidate = getDeclaringClass0();
1717 } else {
1718 Class<?> enclosingClass = enclosingInfo.getEnclosingClass();
1719 // This is a local class or an anonymous class (d or e)
1720 if (enclosingClass == this || enclosingClass == null)
1721 throw new InternalError("Malformed enclosing method information");
1722 else
1723 enclosingCandidate = enclosingClass;
1724 }
1725 return enclosingCandidate;
1726 }
1727
1728 /**
1729 * Returns the simple name of the underlying class as given in the
1730 * source code. An empty string is returned if the underlying class is
1731 * {@linkplain #isAnonymousClass() anonymous}.
1732 * A {@linkplain #isSynthetic() synthetic class}, one not present
1733 * in source code, can have a non-empty name including special
1734 * characters, such as "{@code $}".
1735 *
1736 * <p>The simple name of an {@linkplain #isArray() array class} is the simple name of the
1737 * component type with "[]" appended. In particular the simple
1738 * name of an array class whose component type is anonymous is "[]".
1739 *
1740 * @return the simple name of the underlying class
1741 * @since 1.5
1742 */
1743 public String getSimpleName() {
1744 ReflectionData<T> rd = reflectionData();
1745 String simpleName = rd.simpleName;
1746 if (simpleName == null) {
1747 rd.simpleName = simpleName = getSimpleName0();
1748 }
1749 return simpleName;
1750 }
1751
1752 private String getSimpleName0() {
1753 if (isArray()) {
1754 return getComponentType().getSimpleName().concat("[]");
1755 }
1756 String simpleName = getSimpleBinaryName();
1757 if (simpleName == null) { // top level class
1758 simpleName = getName();
1759 simpleName = simpleName.substring(simpleName.lastIndexOf('.') + 1); // strip the package name
1760 }
1761 return simpleName;
1762 }
1763
1764 /**
1765 * Return an informative string for the name of this class or interface.
1766 *
1767 * @return an informative string for the name of this class or interface
1768 * @since 1.8
1769 */
1770 public String getTypeName() {
1771 if (isArray()) {
1772 try {
1773 Class<?> cl = this;
1774 int dimensions = 0;
1775 do {
1776 dimensions++;
1777 cl = cl.getComponentType();
1778 } while (cl.isArray());
1779 return cl.getName().concat("[]".repeat(dimensions));
1780 } catch (Throwable e) { /*FALLTHRU*/ }
1781 }
1782 return getName();
1783 }
1784
1785 /**
1786 * Returns the canonical name of the underlying class as
1787 * defined by <cite>The Java Language Specification</cite>.
1788 * Returns {@code null} if the underlying class does not have a canonical
1789 * name. Classes without canonical names include:
1790 * <ul>
1791 * <li>a {@linkplain #isLocalClass() local class}
1792 * <li>a {@linkplain #isAnonymousClass() anonymous class}
1793 * <li>a {@linkplain #isHidden() hidden class}
1794 * <li>an array whose component type does not have a canonical name</li>
1795 * </ul>
1796 *
1797 * The canonical name for a primitive class is the keyword for the
1798 * corresponding primitive type ({@code byte}, {@code short},
1799 * {@code char}, {@code int}, and so on).
1800 *
1801 * <p>An array type has a canonical name if and only if its
1802 * component type has a canonical name. When an array type has a
1803 * canonical name, it is equal to the canonical name of the
1804 * component type followed by "{@code []}".
1805 *
1806 * @return the canonical name of the underlying class if it exists, and
1807 * {@code null} otherwise.
1808 * @jls 6.7 Fully Qualified Names and Canonical Names
1809 * @since 1.5
1810 */
1811 public String getCanonicalName() {
1812 ReflectionData<T> rd = reflectionData();
1813 String canonicalName = rd.canonicalName;
1814 if (canonicalName == null) {
1815 rd.canonicalName = canonicalName = getCanonicalName0();
1816 }
1817 return canonicalName == ReflectionData.NULL_SENTINEL? null : canonicalName;
1818 }
1819
1820 private String getCanonicalName0() {
1821 if (isArray()) {
1822 String canonicalName = getComponentType().getCanonicalName();
1823 if (canonicalName != null)
1824 return canonicalName.concat("[]");
1825 else
1826 return ReflectionData.NULL_SENTINEL;
1827 }
1828 if (isHidden() || isLocalOrAnonymousClass())
1829 return ReflectionData.NULL_SENTINEL;
1830 Class<?> enclosingClass = getEnclosingClass();
1831 if (enclosingClass == null) { // top level class
1832 return getName();
1833 } else {
1834 String enclosingName = enclosingClass.getCanonicalName();
1835 if (enclosingName == null)
1836 return ReflectionData.NULL_SENTINEL;
1837 String simpleName = getSimpleName();
1838 return new StringBuilder(enclosingName.length() + simpleName.length() + 1)
1839 .append(enclosingName)
1840 .append('.')
1841 .append(simpleName)
1842 .toString();
1843 }
1844 }
1845
1846 /**
1847 * Returns {@code true} if and only if the underlying class
1848 * is an anonymous class.
1849 *
1850 * @apiNote
1851 * An anonymous class is not a {@linkplain #isHidden() hidden class}.
1852 *
1853 * @return {@code true} if and only if this class is an anonymous class.
1854 * @since 1.5
1855 * @jls 15.9.5 Anonymous Class Declarations
1856 */
1857 public boolean isAnonymousClass() {
1858 return !isArray() && isLocalOrAnonymousClass() &&
1859 getSimpleBinaryName0() == null;
1860 }
1861
1862 /**
1863 * Returns {@code true} if and only if the underlying class
1864 * is a local class.
1865 *
1866 * @return {@code true} if and only if this class is a local class.
1867 * @since 1.5
1868 * @jls 14.3 Local Class and Interface Declarations
1869 */
1870 public boolean isLocalClass() {
1871 return isLocalOrAnonymousClass() &&
1872 (isArray() || getSimpleBinaryName0() != null);
1873 }
1874
1875 /**
1876 * Returns {@code true} if and only if the underlying class
1877 * is a member class.
1878 *
1879 * @return {@code true} if and only if this class is a member class.
1880 * @since 1.5
1881 * @jls 8.5 Member Class and Interface Declarations
1882 */
1883 public boolean isMemberClass() {
1884 return !isLocalOrAnonymousClass() && getDeclaringClass0() != null;
1885 }
1886
1887 /**
1888 * Returns the "simple binary name" of the underlying class, i.e.,
1889 * the binary name without the leading enclosing class name.
1890 * Returns {@code null} if the underlying class is a top level
1891 * class.
1892 */
1893 private String getSimpleBinaryName() {
1894 if (isTopLevelClass())
1895 return null;
1896 String name = getSimpleBinaryName0();
1897 if (name == null) // anonymous class
1898 return "";
1899 return name;
1900 }
1901
1902 private native String getSimpleBinaryName0();
1903
1904 /**
1905 * Returns {@code true} if this is a top level class. Returns {@code false}
1906 * otherwise.
1907 */
1908 private boolean isTopLevelClass() {
1909 return !isLocalOrAnonymousClass() && getDeclaringClass0() == null;
1910 }
1911
1912 /**
1913 * Returns {@code true} if this is a local class or an anonymous
1914 * class. Returns {@code false} otherwise.
1915 */
1916 private boolean isLocalOrAnonymousClass() {
1917 // JVM Spec 4.7.7: A class must have an EnclosingMethod
1918 // attribute if and only if it is a local class or an
1919 // anonymous class.
1920 return hasEnclosingMethodInfo();
1921 }
1922
1923 private boolean hasEnclosingMethodInfo() {
1924 Object[] enclosingInfo = getEnclosingMethod0();
1925 if (enclosingInfo != null) {
1926 EnclosingMethodInfo.validate(enclosingInfo);
1927 return true;
1928 }
1929 return false;
1930 }
1931
1932 /**
1933 * Returns an array containing {@code Class} objects representing all
1934 * the public classes and interfaces that are members of the class
1935 * represented by this {@code Class} object. This includes public
1936 * class and interface members inherited from superclasses and public class
1937 * and interface members declared by the class. This method returns an
1938 * array of length 0 if this {@code Class} object has no public member
1939 * classes or interfaces. This method also returns an array of length 0 if
1940 * this {@code Class} object represents a primitive type, an array
1941 * class, or void.
1942 *
1943 * @return the array of {@code Class} objects representing the public
1944 * members of this class
1945 * @since 1.1
1946 */
1947 public Class<?>[] getClasses() {
1948 List<Class<?>> list = new ArrayList<>();
1949 Class<?> currentClass = Class.this;
1950 while (currentClass != null) {
1951 for (Class<?> m : currentClass.getDeclaredClasses()) {
1952 if (Modifier.isPublic(m.getModifiers())) {
1953 list.add(m);
1954 }
1955 }
1956 currentClass = currentClass.getSuperclass();
1957 }
1958 return list.toArray(EMPTY_CLASS_ARRAY);
1959 }
1960
1961
1962 /**
1963 * Returns an array containing {@code Field} objects reflecting all
1964 * the accessible public fields of the class or interface represented by
1965 * this {@code Class} object.
1966 *
1967 * <p> If this {@code Class} object represents a class or interface with
1968 * no accessible public fields, then this method returns an array of length
1969 * 0.
1970 *
1971 * <p> If this {@code Class} object represents a class, then this method
1972 * returns the public fields of the class and of all its superclasses and
1973 * superinterfaces.
1974 *
1975 * <p> If this {@code Class} object represents an interface, then this
1976 * method returns the fields of the interface and of all its
1977 * superinterfaces.
1978 *
1979 * <p> If this {@code Class} object represents an array type, a primitive
1980 * type, or void, then this method returns an array of length 0.
1981 *
1982 * <p> The elements in the returned array are not sorted and are not in any
1983 * particular order.
1984 *
1985 * @return the array of {@code Field} objects representing the
1986 * public fields
1987 *
1988 * @since 1.1
1989 * @jls 8.2 Class Members
1990 * @jls 8.3 Field Declarations
1991 */
1992 public Field[] getFields() {
1993 return copyFields(privateGetPublicFields());
1994 }
1995
1996
1997 /**
1998 * Returns an array containing {@code Method} objects reflecting all the
1999 * public methods of the class or interface represented by this {@code
2000 * Class} object, including those declared by the class or interface and
2001 * those inherited from superclasses and superinterfaces.
2002 *
2003 * <p> If this {@code Class} object represents an array type, then the
2004 * returned array has a {@code Method} object for each of the public
2005 * methods inherited by the array type from {@code Object}. It does not
2006 * contain a {@code Method} object for {@code clone()}.
2007 *
2008 * <p> If this {@code Class} object represents an interface then the
2009 * returned array does not contain any implicitly declared methods from
2010 * {@code Object}. Therefore, if no methods are explicitly declared in
2011 * this interface or any of its superinterfaces then the returned array
2012 * has length 0. (Note that a {@code Class} object which represents a class
2013 * always has public methods, inherited from {@code Object}.)
2014 *
2015 * <p> The returned array never contains methods with names {@value
2016 * ConstantDescs#INIT_NAME} or {@value ConstantDescs#CLASS_INIT_NAME}.
2017 *
2018 * <p> The elements in the returned array are not sorted and are not in any
2019 * particular order.
2020 *
2021 * <p> Generally, the result is computed as with the following 4 step algorithm.
2022 * Let C be the class or interface represented by this {@code Class} object:
2023 * <ol>
2024 * <li> A union of methods is composed of:
2025 * <ol type="a">
2026 * <li> C's declared public instance and static methods as returned by
2027 * {@link #getDeclaredMethods()} and filtered to include only public
2028 * methods.</li>
2029 * <li> If C is a class other than {@code Object}, then include the result
2030 * of invoking this algorithm recursively on the superclass of C.</li>
2031 * <li> Include the results of invoking this algorithm recursively on all
2032 * direct superinterfaces of C, but include only instance methods.</li>
2033 * </ol></li>
2034 * <li> Union from step 1 is partitioned into subsets of methods with same
2035 * signature (name, parameter types) and return type.</li>
2036 * <li> Within each such subset only the most specific methods are selected.
2037 * Let method M be a method from a set of methods with same signature
2038 * and return type. M is most specific if there is no such method
2039 * N != M from the same set, such that N is more specific than M.
2040 * N is more specific than M if:
2041 * <ol type="a">
2042 * <li> N is declared by a class and M is declared by an interface; or</li>
2043 * <li> N and M are both declared by classes or both by interfaces and
2044 * N's declaring type is the same as or a subtype of M's declaring type
2045 * (clearly, if M's and N's declaring types are the same type, then
2046 * M and N are the same method).</li>
2047 * </ol></li>
2048 * <li> The result of this algorithm is the union of all selected methods from
2049 * step 3.</li>
2050 * </ol>
2051 *
2052 * @apiNote There may be more than one method with a particular name
2053 * and parameter types in a class because while the Java language forbids a
2054 * class to declare multiple methods with the same signature but different
2055 * return types, the Java virtual machine does not. This
2056 * increased flexibility in the virtual machine can be used to
2057 * implement various language features. For example, covariant
2058 * returns can be implemented with {@linkplain
2059 * java.lang.reflect.Method#isBridge bridge methods}; the bridge
2060 * method and the overriding method would have the same
2061 * signature but different return types.
2062 *
2063 * @return the array of {@code Method} objects representing the
2064 * public methods of this class
2065 *
2066 * @jls 8.2 Class Members
2067 * @jls 8.4 Method Declarations
2068 * @since 1.1
2069 */
2070 public Method[] getMethods() {
2071 return copyMethods(privateGetPublicMethods());
2072 }
2073
2074
2075 /**
2076 * Returns an array containing {@code Constructor} objects reflecting
2077 * all the public constructors of the class represented by this
2078 * {@code Class} object. An array of length 0 is returned if the
2079 * class has no public constructors, or if the class is an array class, or
2080 * if the class reflects a primitive type or void.
2081 *
2082 * @apiNote
2083 * While this method returns an array of {@code
2084 * Constructor<T>} objects (that is an array of constructors from
2085 * this class), the return type of this method is {@code
2086 * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
2087 * might be expected. This less informative return type is
2088 * necessary since after being returned from this method, the
2089 * array could be modified to hold {@code Constructor} objects for
2090 * different classes, which would violate the type guarantees of
2091 * {@code Constructor<T>[]}.
2092 *
2093 * @return the array of {@code Constructor} objects representing the
2094 * public constructors of this class
2095 *
2096 * @see #getDeclaredConstructors()
2097 * @since 1.1
2098 */
2099 public Constructor<?>[] getConstructors() {
2100 return copyConstructors(privateGetDeclaredConstructors(true));
2101 }
2102
2103
2104 /**
2105 * Returns a {@code Field} object that reflects the specified public member
2106 * field of the class or interface represented by this {@code Class}
2107 * object. The {@code name} parameter is a {@code String} specifying the
2108 * simple name of the desired field.
2109 *
2110 * <p> The field to be reflected is determined by the algorithm that
2111 * follows. Let C be the class or interface represented by this {@code Class} object:
2112 *
2113 * <OL>
2114 * <LI> If C declares a public field with the name specified, that is the
2115 * field to be reflected.</LI>
2116 * <LI> If no field was found in step 1 above, this algorithm is applied
2117 * recursively to each direct superinterface of C. The direct
2118 * superinterfaces are searched in the order they were declared.</LI>
2119 * <LI> If no field was found in steps 1 and 2 above, and C has a
2120 * superclass S, then this algorithm is invoked recursively upon S.
2121 * If C has no superclass, then a {@code NoSuchFieldException}
2122 * is thrown.</LI>
2123 * </OL>
2124 *
2125 * <p> If this {@code Class} object represents an array type, then this
2126 * method does not find the {@code length} field of the array type.
2127 *
2128 * @param name the field name
2129 * @return the {@code Field} object of this class specified by
2130 * {@code name}
2131 * @throws NoSuchFieldException if a field with the specified name is
2132 * not found.
2133 *
2134 * @since 1.1
2135 * @jls 8.2 Class Members
2136 * @jls 8.3 Field Declarations
2137 */
2138 public Field getField(String name) throws NoSuchFieldException {
2139 Objects.requireNonNull(name);
2140 Field field = getField0(name);
2141 if (field == null) {
2142 throw new NoSuchFieldException(name);
2143 }
2144 return getReflectionFactory().copyField(field);
2145 }
2146
2147
2148 /**
2149 * Returns a {@code Method} object that reflects the specified public
2150 * member method of the class or interface represented by this
2151 * {@code Class} object. The {@code name} parameter is a
2152 * {@code String} specifying the simple name of the desired method. The
2153 * {@code parameterTypes} parameter is an array of {@code Class}
2154 * objects that identify the method's formal parameter types, in declared
2155 * order. If {@code parameterTypes} is {@code null}, it is
2156 * treated as if it were an empty array.
2157 *
2158 * <p> If this {@code Class} object represents an array type, then this
2159 * method finds any public method inherited by the array type from
2160 * {@code Object} except method {@code clone()}.
2161 *
2162 * <p> If this {@code Class} object represents an interface then this
2163 * method does not find any implicitly declared method from
2164 * {@code Object}. Therefore, if no methods are explicitly declared in
2165 * this interface or any of its superinterfaces, then this method does not
2166 * find any method.
2167 *
2168 * <p> This method does not find any method with name {@value
2169 * ConstantDescs#INIT_NAME} or {@value ConstantDescs#CLASS_INIT_NAME}.
2170 *
2171 * <p> Generally, the method to be reflected is determined by the 4 step
2172 * algorithm that follows.
2173 * Let C be the class or interface represented by this {@code Class} object:
2174 * <ol>
2175 * <li> A union of methods is composed of:
2176 * <ol type="a">
2177 * <li> C's declared public instance and static methods as returned by
2178 * {@link #getDeclaredMethods()} and filtered to include only public
2179 * methods that match given {@code name} and {@code parameterTypes}</li>
2180 * <li> If C is a class other than {@code Object}, then include the result
2181 * of invoking this algorithm recursively on the superclass of C.</li>
2182 * <li> Include the results of invoking this algorithm recursively on all
2183 * direct superinterfaces of C, but include only instance methods.</li>
2184 * </ol></li>
2185 * <li> This union is partitioned into subsets of methods with same
2186 * return type (the selection of methods from step 1 also guarantees that
2187 * they have the same method name and parameter types).</li>
2188 * <li> Within each such subset only the most specific methods are selected.
2189 * Let method M be a method from a set of methods with same VM
2190 * signature (return type, name, parameter types).
2191 * M is most specific if there is no such method N != M from the same
2192 * set, such that N is more specific than M. N is more specific than M
2193 * if:
2194 * <ol type="a">
2195 * <li> N is declared by a class and M is declared by an interface; or</li>
2196 * <li> N and M are both declared by classes or both by interfaces and
2197 * N's declaring type is the same as or a subtype of M's declaring type
2198 * (clearly, if M's and N's declaring types are the same type, then
2199 * M and N are the same method).</li>
2200 * </ol></li>
2201 * <li> The result of this algorithm is chosen arbitrarily from the methods
2202 * with most specific return type among all selected methods from step 3.
2203 * Let R be a return type of a method M from the set of all selected methods
2204 * from step 3. M is a method with most specific return type if there is
2205 * no such method N != M from the same set, having return type S != R,
2206 * such that S is a subtype of R as determined by
2207 * R.class.{@link #isAssignableFrom}(S.class).
2208 * </ol>
2209 *
2210 * @apiNote There may be more than one method with matching name and
2211 * parameter types in a class because while the Java language forbids a
2212 * class to declare multiple methods with the same signature but different
2213 * return types, the Java virtual machine does not. This
2214 * increased flexibility in the virtual machine can be used to
2215 * implement various language features. For example, covariant
2216 * returns can be implemented with {@linkplain
2217 * java.lang.reflect.Method#isBridge bridge methods}; the bridge
2218 * method and the overriding method would have the same
2219 * signature but different return types. This method would return the
2220 * overriding method as it would have a more specific return type.
2221 *
2222 * @param name the name of the method
2223 * @param parameterTypes the list of parameters, may be {@code null}
2224 * @return the {@code Method} object that matches the specified
2225 * {@code name} and {@code parameterTypes}
2226 * @throws NoSuchMethodException if a matching method is not found,
2227 * if {@code parameterTypes} contains {@code null},
2228 * or if the name is {@value ConstantDescs#INIT_NAME} or
2229 * {@value ConstantDescs#CLASS_INIT_NAME}
2230 *
2231 * @jls 8.2 Class Members
2232 * @jls 8.4 Method Declarations
2233 * @since 1.1
2234 */
2235 public Method getMethod(String name, Class<?>... parameterTypes)
2236 throws NoSuchMethodException {
2237 Objects.requireNonNull(name);
2238 Method method = getMethod0(name, parameterTypes);
2239 if (method == null) {
2240 throw new NoSuchMethodException(methodToString(name, parameterTypes));
2241 }
2242 return getReflectionFactory().copyMethod(method);
2243 }
2244
2245 /**
2246 * Returns a {@code Constructor} object that reflects the specified
2247 * public constructor of the class represented by this {@code Class}
2248 * object. The {@code parameterTypes} parameter is an array of
2249 * {@code Class} objects that identify the constructor's formal
2250 * parameter types, in declared order.
2251 *
2252 * If this {@code Class} object represents an inner class
2253 * declared in a non-static context, the formal parameter types
2254 * include the explicit enclosing instance as the first parameter.
2255 *
2256 * <p> The constructor to reflect is the public constructor of the class
2257 * represented by this {@code Class} object whose formal parameter
2258 * types match those specified by {@code parameterTypes}.
2259 *
2260 * @param parameterTypes the parameter array, may be {@code null}
2261 * @return the {@code Constructor} object of the public constructor that
2262 * matches the specified {@code parameterTypes}
2263 * @throws NoSuchMethodException if a matching constructor is not found,
2264 * if this {@code Class} object represents an interface, a primitive
2265 * type, an array class, or void, or if {@code parameterTypes}
2266 * contains {@code null}
2267 *
2268 * @see #getDeclaredConstructor(Class[])
2269 * @since 1.1
2270 */
2271 public Constructor<T> getConstructor(Class<?>... parameterTypes)
2272 throws NoSuchMethodException {
2273 return getReflectionFactory().copyConstructor(
2274 getConstructor0(parameterTypes, Member.PUBLIC));
2275 }
2276
2277
2278 /**
2279 * Returns an array of {@code Class} objects reflecting all the
2280 * classes and interfaces declared as members of the class represented by
2281 * this {@code Class} object. This includes public, protected, default
2282 * (package) access, and private classes and interfaces declared by the
2283 * class, but excludes inherited classes and interfaces. This method
2284 * returns an array of length 0 if the class declares no classes or
2285 * interfaces as members, or if this {@code Class} object represents a
2286 * primitive type, an array class, or void.
2287 *
2288 * @return the array of {@code Class} objects representing all the
2289 * declared members of this class
2290 *
2291 * @since 1.1
2292 * @jls 8.5 Member Class and Interface Declarations
2293 */
2294 public Class<?>[] getDeclaredClasses() {
2295 return getDeclaredClasses0();
2296 }
2297
2298
2299 /**
2300 * Returns an array of {@code Field} objects reflecting all the fields
2301 * declared by the class or interface represented by this
2302 * {@code Class} object. This includes public, protected, default
2303 * (package) access, and private fields, but excludes inherited fields.
2304 *
2305 * <p> If this {@code Class} object represents a class or interface with no
2306 * declared fields, then this method returns an array of length 0.
2307 *
2308 * <p> If this {@code Class} object represents an array type, a primitive
2309 * type, or void, then this method returns an array of length 0.
2310 *
2311 * <p> The elements in the returned array are not sorted and are not in any
2312 * particular order.
2313 *
2314 * @return the array of {@code Field} objects representing all the
2315 * declared fields of this class
2316 *
2317 * @since 1.1
2318 * @jls 8.2 Class Members
2319 * @jls 8.3 Field Declarations
2320 */
2321 public Field[] getDeclaredFields() {
2322 return copyFields(privateGetDeclaredFields(false));
2323 }
2324
2325 /**
2326 * Returns an array of {@code RecordComponent} objects representing all the
2327 * record components of this record class, or {@code null} if this class is
2328 * not a record class.
2329 *
2330 * <p> The components are returned in the same order that they are declared
2331 * in the record header. The array is empty if this record class has no
2332 * components. If the class is not a record class, that is {@link
2333 * #isRecord()} returns {@code false}, then this method returns {@code null}.
2334 * Conversely, if {@link #isRecord()} returns {@code true}, then this method
2335 * returns a non-null value.
2336 *
2337 * @apiNote
2338 * <p> The following method can be used to find the record canonical constructor:
2339 *
2340 * {@snippet lang="java" :
2341 * static <T extends Record> Constructor<T> getCanonicalConstructor(Class<T> cls)
2342 * throws NoSuchMethodException {
2343 * Class<?>[] paramTypes =
2344 * Arrays.stream(cls.getRecordComponents())
2345 * .map(RecordComponent::getType)
2346 * .toArray(Class<?>[]::new);
2347 * return cls.getDeclaredConstructor(paramTypes);
2348 * }}
2349 *
2350 * @return An array of {@code RecordComponent} objects representing all the
2351 * record components of this record class, or {@code null} if this
2352 * class is not a record class
2353 *
2354 * @jls 8.10 Record Classes
2355 * @since 16
2356 */
2357 public RecordComponent[] getRecordComponents() {
2358 if (!isRecord()) {
2359 return null;
2360 }
2361 return getRecordComponents0();
2362 }
2363
2364 /**
2365 * Returns an array containing {@code Method} objects reflecting all the
2366 * declared methods of the class or interface represented by this {@code
2367 * Class} object, including public, protected, default (package)
2368 * access, and private methods, but excluding inherited methods.
2369 * The declared methods may include methods <em>not</em> in the
2370 * source of the class or interface, including {@linkplain
2371 * Method#isBridge bridge methods} and other {@linkplain
2372 * Executable#isSynthetic synthetic} methods added by compilers.
2373 *
2374 * <p> If this {@code Class} object represents a class or interface that
2375 * has multiple declared methods with the same name and parameter types,
2376 * but different return types, then the returned array has a {@code Method}
2377 * object for each such method.
2378 *
2379 * <p> If this {@code Class} object represents a class or interface that
2380 * has a class initialization method {@value ConstantDescs#CLASS_INIT_NAME},
2381 * then the returned array does <em>not</em> have a corresponding {@code
2382 * Method} object.
2383 *
2384 * <p> If this {@code Class} object represents a class or interface with no
2385 * declared methods, then the returned array has length 0.
2386 *
2387 * <p> If this {@code Class} object represents an array type, a primitive
2388 * type, or void, then the returned array has length 0.
2389 *
2390 * <p> The elements in the returned array are not sorted and are not in any
2391 * particular order.
2392 *
2393 * @return the array of {@code Method} objects representing all the
2394 * declared methods of this class
2395 *
2396 * @jls 8.2 Class Members
2397 * @jls 8.4 Method Declarations
2398 * @see <a
2399 * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">Java
2400 * programming language and JVM modeling in core reflection</a>
2401 * @since 1.1
2402 */
2403 public Method[] getDeclaredMethods() {
2404 return copyMethods(privateGetDeclaredMethods(false));
2405 }
2406
2407 /**
2408 * Returns an array of {@code Constructor} objects reflecting all the
2409 * constructors implicitly or explicitly declared by the class represented by this
2410 * {@code Class} object. These are public, protected, default
2411 * (package) access, and private constructors. The elements in the array
2412 * returned are not sorted and are not in any particular order. If the
2413 * class has a default constructor (JLS {@jls 8.8.9}), it is included in the returned array.
2414 * If a record class has a canonical constructor (JLS {@jls
2415 * 8.10.4.1}, {@jls 8.10.4.2}), it is included in the returned array.
2416 *
2417 * This method returns an array of length 0 if this {@code Class}
2418 * object represents an interface, a primitive type, an array class, or
2419 * void.
2420 *
2421 * @return the array of {@code Constructor} objects representing all the
2422 * declared constructors of this class
2423 *
2424 * @since 1.1
2425 * @see #getConstructors()
2426 * @jls 8.8 Constructor Declarations
2427 */
2428 public Constructor<?>[] getDeclaredConstructors() {
2429 return copyConstructors(privateGetDeclaredConstructors(false));
2430 }
2431
2432
2433 /**
2434 * Returns a {@code Field} object that reflects the specified declared
2435 * field of the class or interface represented by this {@code Class}
2436 * object. The {@code name} parameter is a {@code String} that specifies
2437 * the simple name of the desired field.
2438 *
2439 * <p> If this {@code Class} object represents an array type, then this
2440 * method does not find the {@code length} field of the array type.
2441 *
2442 * @param name the name of the field
2443 * @return the {@code Field} object for the specified field in this
2444 * class
2445 * @throws NoSuchFieldException if a field with the specified name is
2446 * not found.
2447 *
2448 * @since 1.1
2449 * @jls 8.2 Class Members
2450 * @jls 8.3 Field Declarations
2451 */
2452 public Field getDeclaredField(String name) throws NoSuchFieldException {
2453 Objects.requireNonNull(name);
2454 Field field = searchFields(privateGetDeclaredFields(false), name);
2455 if (field == null) {
2456 throw new NoSuchFieldException(name);
2457 }
2458 return getReflectionFactory().copyField(field);
2459 }
2460
2461
2462 /**
2463 * Returns a {@code Method} object that reflects the specified
2464 * declared method of the class or interface represented by this
2465 * {@code Class} object. The {@code name} parameter is a
2466 * {@code String} that specifies the simple name of the desired
2467 * method, and the {@code parameterTypes} parameter is an array of
2468 * {@code Class} objects that identify the method's formal parameter
2469 * types, in declared order. If more than one method with the same
2470 * parameter types is declared in a class, and one of these methods has a
2471 * return type that is more specific than any of the others, that method is
2472 * returned; otherwise one of the methods is chosen arbitrarily. If the
2473 * name is {@value ConstantDescs#INIT_NAME} or {@value
2474 * ConstantDescs#CLASS_INIT_NAME} a {@code NoSuchMethodException}
2475 * is raised.
2476 *
2477 * <p> If this {@code Class} object represents an array type, then this
2478 * method does not find the {@code clone()} method.
2479 *
2480 * @param name the name of the method
2481 * @param parameterTypes the parameter array, may be {@code null}
2482 * @return the {@code Method} object for the method of this class
2483 * matching the specified name and parameters
2484 * @throws NoSuchMethodException if a matching method is not found,
2485 * if {@code parameterTypes} contains {@code null},
2486 * or if the name is {@value ConstantDescs#INIT_NAME} or
2487 * {@value ConstantDescs#CLASS_INIT_NAME}
2488 *
2489 * @jls 8.2 Class Members
2490 * @jls 8.4 Method Declarations
2491 * @since 1.1
2492 */
2493 public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
2494 throws NoSuchMethodException {
2495 Objects.requireNonNull(name);
2496 Method method = searchMethods(privateGetDeclaredMethods(false), name, parameterTypes);
2497 if (method == null) {
2498 throw new NoSuchMethodException(methodToString(name, parameterTypes));
2499 }
2500 return getReflectionFactory().copyMethod(method);
2501 }
2502
2503 /**
2504 * Returns the list of {@code Method} objects for the declared public
2505 * methods of this class or interface that have the specified method name
2506 * and parameter types.
2507 *
2508 * @param name the name of the method
2509 * @param parameterTypes the parameter array
2510 * @return the list of {@code Method} objects for the public methods of
2511 * this class matching the specified name and parameters
2512 */
2513 List<Method> getDeclaredPublicMethods(String name, Class<?>... parameterTypes) {
2514 Method[] methods = privateGetDeclaredMethods(/* publicOnly */ true);
2515 ReflectionFactory factory = getReflectionFactory();
2516 List<Method> result = new ArrayList<>();
2517 for (Method method : methods) {
2518 if (method.getName().equals(name)
2519 && Arrays.equals(
2520 factory.getExecutableSharedParameterTypes(method),
2521 parameterTypes)) {
2522 result.add(factory.copyMethod(method));
2523 }
2524 }
2525 return result;
2526 }
2527
2528 /**
2529 * Returns the most specific {@code Method} object of this class, super class or
2530 * interface that have the specified method name and parameter types.
2531 *
2532 * @param publicOnly true if only public methods are examined, otherwise all methods
2533 * @param name the name of the method
2534 * @param parameterTypes the parameter array
2535 * @return the {@code Method} object for the method found from this class matching
2536 * the specified name and parameters, or null if not found
2537 */
2538 Method findMethod(boolean publicOnly, String name, Class<?>... parameterTypes) {
2539 PublicMethods.MethodList res = getMethodsRecursive(name, parameterTypes, true, publicOnly);
2540 return res == null ? null : getReflectionFactory().copyMethod(res.getMostSpecific());
2541 }
2542
2543 /**
2544 * Returns a {@code Constructor} object that reflects the specified
2545 * constructor of the class represented by this
2546 * {@code Class} object. The {@code parameterTypes} parameter is
2547 * an array of {@code Class} objects that identify the constructor's
2548 * formal parameter types, in declared order.
2549 *
2550 * If this {@code Class} object represents an inner class
2551 * declared in a non-static context, the formal parameter types
2552 * include the explicit enclosing instance as the first parameter.
2553 *
2554 * @param parameterTypes the parameter array, may be {@code null}
2555 * @return The {@code Constructor} object for the constructor with the
2556 * specified parameter list
2557 * @throws NoSuchMethodException if a matching constructor is not found,
2558 * if this {@code Class} object represents an interface, a
2559 * primitive type, an array class, or void, or if
2560 * {@code parameterTypes} contains {@code null}
2561 *
2562 * @see #getConstructor(Class[])
2563 * @since 1.1
2564 */
2565 public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
2566 throws NoSuchMethodException {
2567 return getReflectionFactory().copyConstructor(
2568 getConstructor0(parameterTypes, Member.DECLARED));
2569 }
2570
2571 /**
2572 * Finds a resource with a given name.
2573 *
2574 * <p> If this class is in a named {@link Module Module} then this method
2575 * will attempt to find the resource in the module. This is done by
2576 * delegating to the module's class loader {@link
2577 * ClassLoader#findResource(String,String) findResource(String,String)}
2578 * method, invoking it with the module name and the absolute name of the
2579 * resource. Resources in named modules are subject to the rules for
2580 * encapsulation specified in the {@code Module} {@link
2581 * Module#getResourceAsStream getResourceAsStream} method and so this
2582 * method returns {@code null} when the resource is a
2583 * non-"{@code .class}" resource in a package that is not open to the
2584 * caller's module.
2585 *
2586 * <p> Otherwise, if this class is not in a named module then the rules for
2587 * searching resources associated with a given class are implemented by the
2588 * defining {@linkplain ClassLoader class loader} of the class. This method
2589 * delegates to this {@code Class} object's class loader.
2590 * If this {@code Class} object was loaded by the bootstrap class loader,
2591 * the method delegates to {@link ClassLoader#getSystemResourceAsStream}.
2592 *
2593 * <p> Before delegation, an absolute resource name is constructed from the
2594 * given resource name using this algorithm:
2595 *
2596 * <ul>
2597 *
2598 * <li> If the {@code name} begins with a {@code '/'}
2599 * (<code>'\u002f'</code>), then the absolute name of the resource is the
2600 * portion of the {@code name} following the {@code '/'}.
2601 *
2602 * <li> Otherwise, the absolute name is of the following form:
2603 *
2604 * <blockquote>
2605 * {@code modified_package_name/name}
2606 * </blockquote>
2607 *
2608 * <p> Where the {@code modified_package_name} is the package name of this
2609 * object with {@code '/'} substituted for {@code '.'}
2610 * (<code>'\u002e'</code>).
2611 *
2612 * </ul>
2613 *
2614 * @param name name of the desired resource
2615 * @return A {@link java.io.InputStream} object; {@code null} if no
2616 * resource with this name is found, or the resource is in a package
2617 * that is not {@linkplain Module#isOpen(String, Module) open} to at
2618 * least the caller module.
2619 *
2620 * @see Module#getResourceAsStream(String)
2621 * @since 1.1
2622 */
2623 @CallerSensitive
2624 public InputStream getResourceAsStream(String name) {
2625 name = resolveName(name);
2626
2627 Module thisModule = getModule();
2628 if (thisModule.isNamed()) {
2629 // check if resource can be located by caller
2630 if (Resources.canEncapsulate(name)
2631 && !isOpenToCaller(name, Reflection.getCallerClass())) {
2632 return null;
2633 }
2634
2635 // resource not encapsulated or in package open to caller
2636 String mn = thisModule.getName();
2637 ClassLoader cl = classLoader;
2638 try {
2639
2640 // special-case built-in class loaders to avoid the
2641 // need for a URL connection
2642 if (cl == null) {
2643 return BootLoader.findResourceAsStream(mn, name);
2644 } else if (cl instanceof BuiltinClassLoader bcl) {
2645 return bcl.findResourceAsStream(mn, name);
2646 } else {
2647 URL url = cl.findResource(mn, name);
2648 return (url != null) ? url.openStream() : null;
2649 }
2650
2651 } catch (IOException | SecurityException e) {
2652 return null;
2653 }
2654 }
2655
2656 // unnamed module
2657 ClassLoader cl = classLoader;
2658 if (cl == null) {
2659 return ClassLoader.getSystemResourceAsStream(name);
2660 } else {
2661 return cl.getResourceAsStream(name);
2662 }
2663 }
2664
2665 /**
2666 * Finds a resource with a given name.
2667 *
2668 * <p> If this class is in a named {@link Module Module} then this method
2669 * will attempt to find the resource in the module. This is done by
2670 * delegating to the module's class loader {@link
2671 * ClassLoader#findResource(String,String) findResource(String,String)}
2672 * method, invoking it with the module name and the absolute name of the
2673 * resource. Resources in named modules are subject to the rules for
2674 * encapsulation specified in the {@code Module} {@link
2675 * Module#getResourceAsStream getResourceAsStream} method and so this
2676 * method returns {@code null} when the resource is a
2677 * non-"{@code .class}" resource in a package that is not open to the
2678 * caller's module.
2679 *
2680 * <p> Otherwise, if this class is not in a named module then the rules for
2681 * searching resources associated with a given class are implemented by the
2682 * defining {@linkplain ClassLoader class loader} of the class. This method
2683 * delegates to this {@code Class} object's class loader.
2684 * If this {@code Class} object was loaded by the bootstrap class loader,
2685 * the method delegates to {@link ClassLoader#getSystemResource}.
2686 *
2687 * <p> Before delegation, an absolute resource name is constructed from the
2688 * given resource name using this algorithm:
2689 *
2690 * <ul>
2691 *
2692 * <li> If the {@code name} begins with a {@code '/'}
2693 * (<code>'\u002f'</code>), then the absolute name of the resource is the
2694 * portion of the {@code name} following the {@code '/'}.
2695 *
2696 * <li> Otherwise, the absolute name is of the following form:
2697 *
2698 * <blockquote>
2699 * {@code modified_package_name/name}
2700 * </blockquote>
2701 *
2702 * <p> Where the {@code modified_package_name} is the package name of this
2703 * object with {@code '/'} substituted for {@code '.'}
2704 * (<code>'\u002e'</code>).
2705 *
2706 * </ul>
2707 *
2708 * @param name name of the desired resource
2709 * @return A {@link java.net.URL} object; {@code null} if no resource with
2710 * this name is found, the resource cannot be located by a URL, or the
2711 * resource is in a package that is not
2712 * {@linkplain Module#isOpen(String, Module) open} to at least the caller
2713 * module.
2714 * @since 1.1
2715 */
2716 @CallerSensitive
2717 public URL getResource(String name) {
2718 name = resolveName(name);
2719
2720 Module thisModule = getModule();
2721 if (thisModule.isNamed()) {
2722 // check if resource can be located by caller
2723 if (Resources.canEncapsulate(name)
2724 && !isOpenToCaller(name, Reflection.getCallerClass())) {
2725 return null;
2726 }
2727
2728 // resource not encapsulated or in package open to caller
2729 String mn = thisModule.getName();
2730 ClassLoader cl = classLoader;
2731 try {
2732 if (cl == null) {
2733 return BootLoader.findResource(mn, name);
2734 } else {
2735 return cl.findResource(mn, name);
2736 }
2737 } catch (IOException ioe) {
2738 return null;
2739 }
2740 }
2741
2742 // unnamed module
2743 ClassLoader cl = classLoader;
2744 if (cl == null) {
2745 return ClassLoader.getSystemResource(name);
2746 } else {
2747 return cl.getResource(name);
2748 }
2749 }
2750
2751 /**
2752 * Returns true if a resource with the given name can be located by the
2753 * given caller. All resources in a module can be located by code in
2754 * the module. For other callers, then the package needs to be open to
2755 * the caller.
2756 */
2757 private boolean isOpenToCaller(String name, Class<?> caller) {
2758 // assert getModule().isNamed();
2759 Module thisModule = getModule();
2760 Module callerModule = (caller != null) ? caller.getModule() : null;
2761 if (callerModule != thisModule) {
2762 String pn = Resources.toPackageName(name);
2763 if (thisModule.getDescriptor().packages().contains(pn)) {
2764 if (callerModule == null) {
2765 // no caller, return true if the package is open to all modules
2766 return thisModule.isOpen(pn);
2767 }
2768 if (!thisModule.isOpen(pn, callerModule)) {
2769 // package not open to caller
2770 return false;
2771 }
2772 }
2773 }
2774 return true;
2775 }
2776
2777 private transient final ProtectionDomain protectionDomain;
2778
2779 /** Holder for the protection domain returned when the internal domain is null */
2780 private static class Holder {
2781 private static final ProtectionDomain allPermDomain;
2782 static {
2783 Permissions perms = new Permissions();
2784 perms.add(new AllPermission());
2785 allPermDomain = new ProtectionDomain(null, perms);
2786 }
2787 }
2788
2789 /**
2790 * Returns the {@code ProtectionDomain} of this class.
2791 *
2792 * @return the ProtectionDomain of this class
2793 *
2794 * @see java.security.ProtectionDomain
2795 * @since 1.2
2796 */
2797 public ProtectionDomain getProtectionDomain() {
2798 if (protectionDomain == null) {
2799 return Holder.allPermDomain;
2800 } else {
2801 return protectionDomain;
2802 }
2803 }
2804
2805 /*
2806 * Returns the Class object for the named primitive type. Type parameter T
2807 * avoids redundant casts for trusted code.
2808 */
2809 static native <T> Class<T> getPrimitiveClass(String name);
2810
2811 /**
2812 * Add a package name prefix if the name is not absolute. Remove leading "/"
2813 * if name is absolute
2814 */
2815 private String resolveName(String name) {
2816 if (!name.startsWith("/")) {
2817 String baseName = getPackageName();
2818 if (!baseName.isEmpty()) {
2819 int len = baseName.length() + 1 + name.length();
2820 StringBuilder sb = new StringBuilder(len);
2821 name = sb.append(baseName.replace('.', '/'))
2822 .append('/')
2823 .append(name)
2824 .toString();
2825 }
2826 } else {
2827 name = name.substring(1);
2828 }
2829 return name;
2830 }
2831
2832 /**
2833 * Atomic operations support.
2834 */
2835 private static class Atomic {
2836 // initialize Unsafe machinery here, since we need to call Class.class instance method
2837 // and have to avoid calling it in the static initializer of the Class class...
2838 private static final Unsafe unsafe = Unsafe.getUnsafe();
2839 // offset of Class.reflectionData instance field
2840 private static final long reflectionDataOffset
2841 = unsafe.objectFieldOffset(Class.class, "reflectionData");
2842 // offset of Class.annotationType instance field
2843 private static final long annotationTypeOffset
2844 = unsafe.objectFieldOffset(Class.class, "annotationType");
2845 // offset of Class.annotationData instance field
2846 private static final long annotationDataOffset
2847 = unsafe.objectFieldOffset(Class.class, "annotationData");
2848
2849 static <T> boolean casReflectionData(Class<?> clazz,
2850 SoftReference<ReflectionData<T>> oldData,
2851 SoftReference<ReflectionData<T>> newData) {
2852 return unsafe.compareAndSetReference(clazz, reflectionDataOffset, oldData, newData);
2853 }
2854
2855 static boolean casAnnotationType(Class<?> clazz,
2856 AnnotationType oldType,
2857 AnnotationType newType) {
2858 return unsafe.compareAndSetReference(clazz, annotationTypeOffset, oldType, newType);
2859 }
2860
2861 static boolean casAnnotationData(Class<?> clazz,
2862 AnnotationData oldData,
2863 AnnotationData newData) {
2864 return unsafe.compareAndSetReference(clazz, annotationDataOffset, oldData, newData);
2865 }
2866 }
2867
2868 /**
2869 * Reflection support.
2870 */
2871
2872 // Reflection data caches various derived names and reflective members. Cached
2873 // values may be invalidated when JVM TI RedefineClasses() is called
2874 private static class ReflectionData<T> {
2875 volatile Field[] declaredFields;
2876 volatile Field[] publicFields;
2877 volatile Method[] declaredMethods;
2878 volatile Method[] publicMethods;
2879 volatile Constructor<T>[] declaredConstructors;
2880 volatile Constructor<T>[] publicConstructors;
2881 // Intermediate results for getFields and getMethods
2882 volatile Field[] declaredPublicFields;
2883 volatile Method[] declaredPublicMethods;
2884 volatile Class<?>[] interfaces;
2885
2886 // Cached names
2887 String simpleName;
2888 String canonicalName;
2889 static final String NULL_SENTINEL = new String();
2890
2891 // Value of classRedefinedCount when we created this ReflectionData instance
2892 final int redefinedCount;
2893
2894 ReflectionData(int redefinedCount) {
2895 this.redefinedCount = redefinedCount;
2896 }
2897 }
2898
2899 private transient volatile SoftReference<ReflectionData<T>> reflectionData;
2900
2901 // Incremented by the VM on each call to JVM TI RedefineClasses()
2902 // that redefines this class or a superclass.
2903 private transient volatile int classRedefinedCount;
2904
2905 // Lazily create and cache ReflectionData
2906 private ReflectionData<T> reflectionData() {
2907 SoftReference<ReflectionData<T>> reflectionData = this.reflectionData;
2908 int classRedefinedCount = this.classRedefinedCount;
2909 ReflectionData<T> rd;
2910 if (reflectionData != null &&
2911 (rd = reflectionData.get()) != null &&
2912 rd.redefinedCount == classRedefinedCount) {
2913 return rd;
2914 }
2915 // else no SoftReference or cleared SoftReference or stale ReflectionData
2916 // -> create and replace new instance
2917 return newReflectionData(reflectionData, classRedefinedCount);
2918 }
2919
2920 private ReflectionData<T> newReflectionData(SoftReference<ReflectionData<T>> oldReflectionData,
2921 int classRedefinedCount) {
2922 while (true) {
2923 ReflectionData<T> rd = new ReflectionData<>(classRedefinedCount);
2924 // try to CAS it...
2925 if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) {
2926 return rd;
2927 }
2928 // else retry
2929 oldReflectionData = this.reflectionData;
2930 classRedefinedCount = this.classRedefinedCount;
2931 if (oldReflectionData != null &&
2932 (rd = oldReflectionData.get()) != null &&
2933 rd.redefinedCount == classRedefinedCount) {
2934 return rd;
2935 }
2936 }
2937 }
2938
2939 // Generic signature handling
2940 private native String getGenericSignature0();
2941
2942 // Generic info repository; lazily initialized
2943 private transient volatile ClassRepository genericInfo;
2944
2945 // accessor for factory
2946 private GenericsFactory getFactory() {
2947 // create scope and factory
2948 return CoreReflectionFactory.make(this, ClassScope.make(this));
2949 }
2950
2951 // accessor for generic info repository;
2952 // generic info is lazily initialized
2953 private ClassRepository getGenericInfo() {
2954 ClassRepository genericInfo = this.genericInfo;
2955 if (genericInfo == null) {
2956 String signature = getGenericSignature0();
2957 if (signature == null) {
2958 genericInfo = ClassRepository.NONE;
2959 } else {
2960 genericInfo = ClassRepository.make(signature, getFactory());
2961 }
2962 this.genericInfo = genericInfo;
2963 }
2964 return (genericInfo != ClassRepository.NONE) ? genericInfo : null;
2965 }
2966
2967 // Annotations handling
2968 native byte[] getRawAnnotations();
2969 // Since 1.8
2970 native byte[] getRawTypeAnnotations();
2971 static byte[] getExecutableTypeAnnotationBytes(Executable ex) {
2972 return getReflectionFactory().getExecutableTypeAnnotationBytes(ex);
2973 }
2974
2975 native ConstantPool getConstantPool();
2976
2977 //
2978 //
2979 // java.lang.reflect.Field handling
2980 //
2981 //
2982
2983 // Returns an array of "root" fields. These Field objects must NOT
2984 // be propagated to the outside world, but must instead be copied
2985 // via ReflectionFactory.copyField.
2986 private Field[] privateGetDeclaredFields(boolean publicOnly) {
2987 Field[] res;
2988 ReflectionData<T> rd = reflectionData();
2989 res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;
2990 if (res != null) return res;
2991 // No cached value available; request value from VM
2992 res = Reflection.filterFields(this, getDeclaredFields0(publicOnly));
2993 if (publicOnly) {
2994 rd.declaredPublicFields = res;
2995 } else {
2996 rd.declaredFields = res;
2997 }
2998 return res;
2999 }
3000
3001 // Returns an array of "root" fields. These Field objects must NOT
3002 // be propagated to the outside world, but must instead be copied
3003 // via ReflectionFactory.copyField.
3004 private Field[] privateGetPublicFields() {
3005 Field[] res;
3006 ReflectionData<T> rd = reflectionData();
3007 res = rd.publicFields;
3008 if (res != null) return res;
3009
3010 // Use a linked hash set to ensure order is preserved and
3011 // fields from common super interfaces are not duplicated
3012 LinkedHashSet<Field> fields = new LinkedHashSet<>();
3013
3014 // Local fields
3015 addAll(fields, privateGetDeclaredFields(true));
3016
3017 // Direct superinterfaces, recursively
3018 for (Class<?> si : getInterfaces(/* cloneArray */ false)) {
3019 addAll(fields, si.privateGetPublicFields());
3020 }
3021
3022 // Direct superclass, recursively
3023 Class<?> sc = getSuperclass();
3024 if (sc != null) {
3025 addAll(fields, sc.privateGetPublicFields());
3026 }
3027
3028 res = fields.toArray(new Field[0]);
3029 rd.publicFields = res;
3030 return res;
3031 }
3032
3033 private static void addAll(Collection<Field> c, Field[] o) {
3034 for (Field f : o) {
3035 c.add(f);
3036 }
3037 }
3038
3039
3040 //
3041 //
3042 // java.lang.reflect.Constructor handling
3043 //
3044 //
3045
3046 // Returns an array of "root" constructors. These Constructor
3047 // objects must NOT be propagated to the outside world, but must
3048 // instead be copied via ReflectionFactory.copyConstructor.
3049 private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly) {
3050 Constructor<T>[] res;
3051 ReflectionData<T> rd = reflectionData();
3052 res = publicOnly ? rd.publicConstructors : rd.declaredConstructors;
3053 if (res != null) return res;
3054 // No cached value available; request value from VM
3055 if (isInterface()) {
3056 @SuppressWarnings("unchecked")
3057 Constructor<T>[] temporaryRes = (Constructor<T>[]) new Constructor<?>[0];
3058 res = temporaryRes;
3059 } else {
3060 res = getDeclaredConstructors0(publicOnly);
3061 }
3062 if (publicOnly) {
3063 rd.publicConstructors = res;
3064 } else {
3065 rd.declaredConstructors = res;
3066 }
3067 return res;
3068 }
3069
3070 //
3071 //
3072 // java.lang.reflect.Method handling
3073 //
3074 //
3075
3076 // Returns an array of "root" methods. These Method objects must NOT
3077 // be propagated to the outside world, but must instead be copied
3078 // via ReflectionFactory.copyMethod.
3079 private Method[] privateGetDeclaredMethods(boolean publicOnly) {
3080 Method[] res;
3081 ReflectionData<T> rd = reflectionData();
3082 res = publicOnly ? rd.declaredPublicMethods : rd.declaredMethods;
3083 if (res != null) return res;
3084 // No cached value available; request value from VM
3085 res = Reflection.filterMethods(this, getDeclaredMethods0(publicOnly));
3086 if (publicOnly) {
3087 rd.declaredPublicMethods = res;
3088 } else {
3089 rd.declaredMethods = res;
3090 }
3091 return res;
3092 }
3093
3094 // Returns an array of "root" methods. These Method objects must NOT
3095 // be propagated to the outside world, but must instead be copied
3096 // via ReflectionFactory.copyMethod.
3097 private Method[] privateGetPublicMethods() {
3098 Method[] res;
3099 ReflectionData<T> rd = reflectionData();
3100 res = rd.publicMethods;
3101 if (res != null) return res;
3102
3103 // No cached value available; compute value recursively.
3104 // Start by fetching public declared methods...
3105 PublicMethods pms = new PublicMethods();
3106 for (Method m : privateGetDeclaredMethods(/* publicOnly */ true)) {
3107 pms.merge(m);
3108 }
3109 // ...then recur over superclass methods...
3110 Class<?> sc = getSuperclass();
3111 if (sc != null) {
3112 for (Method m : sc.privateGetPublicMethods()) {
3113 pms.merge(m);
3114 }
3115 }
3116 // ...and finally over direct superinterfaces.
3117 for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
3118 for (Method m : intf.privateGetPublicMethods()) {
3119 // static interface methods are not inherited
3120 if (!Modifier.isStatic(m.getModifiers())) {
3121 pms.merge(m);
3122 }
3123 }
3124 }
3125
3126 res = pms.toArray();
3127 rd.publicMethods = res;
3128 return res;
3129 }
3130
3131
3132 //
3133 // Helpers for fetchers of one field, method, or constructor
3134 //
3135
3136 // This method does not copy the returned Field object!
3137 private static Field searchFields(Field[] fields, String name) {
3138 for (Field field : fields) {
3139 if (field.getName().equals(name)) {
3140 return field;
3141 }
3142 }
3143 return null;
3144 }
3145
3146 // Returns a "root" Field object. This Field object must NOT
3147 // be propagated to the outside world, but must instead be copied
3148 // via ReflectionFactory.copyField.
3149 private Field getField0(String name) {
3150 // Note: the intent is that the search algorithm this routine
3151 // uses be equivalent to the ordering imposed by
3152 // privateGetPublicFields(). It fetches only the declared
3153 // public fields for each class, however, to reduce the number
3154 // of Field objects which have to be created for the common
3155 // case where the field being requested is declared in the
3156 // class which is being queried.
3157 Field res;
3158 // Search declared public fields
3159 if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {
3160 return res;
3161 }
3162 // Direct superinterfaces, recursively
3163 Class<?>[] interfaces = getInterfaces(/* cloneArray */ false);
3164 for (Class<?> c : interfaces) {
3165 if ((res = c.getField0(name)) != null) {
3166 return res;
3167 }
3168 }
3169 // Direct superclass, recursively
3170 if (!isInterface()) {
3171 Class<?> c = getSuperclass();
3172 if (c != null) {
3173 if ((res = c.getField0(name)) != null) {
3174 return res;
3175 }
3176 }
3177 }
3178 return null;
3179 }
3180
3181 // This method does not copy the returned Method object!
3182 private static Method searchMethods(Method[] methods,
3183 String name,
3184 Class<?>[] parameterTypes)
3185 {
3186 ReflectionFactory fact = getReflectionFactory();
3187 Method res = null;
3188 for (Method m : methods) {
3189 if (m.getName().equals(name)
3190 && arrayContentsEq(parameterTypes,
3191 fact.getExecutableSharedParameterTypes(m))
3192 && (res == null
3193 || (res.getReturnType() != m.getReturnType()
3194 && res.getReturnType().isAssignableFrom(m.getReturnType()))))
3195 res = m;
3196 }
3197 return res;
3198 }
3199
3200 private static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
3201
3202 // Returns a "root" Method object. This Method object must NOT
3203 // be propagated to the outside world, but must instead be copied
3204 // via ReflectionFactory.copyMethod.
3205 private Method getMethod0(String name, Class<?>[] parameterTypes) {
3206 PublicMethods.MethodList res = getMethodsRecursive(
3207 name,
3208 parameterTypes == null ? EMPTY_CLASS_ARRAY : parameterTypes,
3209 /* includeStatic */ true, /* publicOnly */ true);
3210 return res == null ? null : res.getMostSpecific();
3211 }
3212
3213 // Returns a list of "root" Method objects. These Method objects must NOT
3214 // be propagated to the outside world, but must instead be copied
3215 // via ReflectionFactory.copyMethod.
3216 private PublicMethods.MethodList getMethodsRecursive(String name,
3217 Class<?>[] parameterTypes,
3218 boolean includeStatic,
3219 boolean publicOnly) {
3220 // 1st check declared methods
3221 Method[] methods = privateGetDeclaredMethods(publicOnly);
3222 PublicMethods.MethodList res = PublicMethods.MethodList
3223 .filter(methods, name, parameterTypes, includeStatic);
3224 // if there is at least one match among declared methods, we need not
3225 // search any further as such match surely overrides matching methods
3226 // declared in superclass(es) or interface(s).
3227 if (res != null) {
3228 return res;
3229 }
3230
3231 // if there was no match among declared methods,
3232 // we must consult the superclass (if any) recursively...
3233 Class<?> sc = getSuperclass();
3234 if (sc != null) {
3235 res = sc.getMethodsRecursive(name, parameterTypes, includeStatic, publicOnly);
3236 }
3237
3238 // ...and coalesce the superclass methods with methods obtained
3239 // from directly implemented interfaces excluding static methods...
3240 for (Class<?> intf : getInterfaces(/* cloneArray */ false)) {
3241 res = PublicMethods.MethodList.merge(
3242 res, intf.getMethodsRecursive(name, parameterTypes, /* includeStatic */ false, publicOnly));
3243 }
3244
3245 return res;
3246 }
3247
3248 // Returns a "root" Constructor object. This Constructor object must NOT
3249 // be propagated to the outside world, but must instead be copied
3250 // via ReflectionFactory.copyConstructor.
3251 private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
3252 int which) throws NoSuchMethodException
3253 {
3254 ReflectionFactory fact = getReflectionFactory();
3255 Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
3256 for (Constructor<T> constructor : constructors) {
3257 if (arrayContentsEq(parameterTypes,
3258 fact.getExecutableSharedParameterTypes(constructor))) {
3259 return constructor;
3260 }
3261 }
3262 throw new NoSuchMethodException(methodToString("<init>", parameterTypes));
3263 }
3264
3265 //
3266 // Other helpers and base implementation
3267 //
3268
3269 private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
3270 if (a1 == null) {
3271 return a2 == null || a2.length == 0;
3272 }
3273
3274 if (a2 == null) {
3275 return a1.length == 0;
3276 }
3277
3278 if (a1.length != a2.length) {
3279 return false;
3280 }
3281
3282 for (int i = 0; i < a1.length; i++) {
3283 if (a1[i] != a2[i]) {
3284 return false;
3285 }
3286 }
3287
3288 return true;
3289 }
3290
3291 private static Field[] copyFields(Field[] arg) {
3292 Field[] out = new Field[arg.length];
3293 ReflectionFactory fact = getReflectionFactory();
3294 for (int i = 0; i < arg.length; i++) {
3295 out[i] = fact.copyField(arg[i]);
3296 }
3297 return out;
3298 }
3299
3300 private static Method[] copyMethods(Method[] arg) {
3301 Method[] out = new Method[arg.length];
3302 ReflectionFactory fact = getReflectionFactory();
3303 for (int i = 0; i < arg.length; i++) {
3304 out[i] = fact.copyMethod(arg[i]);
3305 }
3306 return out;
3307 }
3308
3309 private static <U> Constructor<U>[] copyConstructors(Constructor<U>[] arg) {
3310 Constructor<U>[] out = arg.clone();
3311 ReflectionFactory fact = getReflectionFactory();
3312 for (int i = 0; i < out.length; i++) {
3313 out[i] = fact.copyConstructor(out[i]);
3314 }
3315 return out;
3316 }
3317
3318 private native Field[] getDeclaredFields0(boolean publicOnly);
3319 private native Method[] getDeclaredMethods0(boolean publicOnly);
3320 private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
3321 private native Class<?>[] getDeclaredClasses0();
3322
3323 /*
3324 * Returns an array containing the components of the Record attribute,
3325 * or null if the attribute is not present.
3326 *
3327 * Note that this method returns non-null array on a class with
3328 * the Record attribute even if this class is not a record.
3329 */
3330 private native RecordComponent[] getRecordComponents0();
3331 private native boolean isRecord0();
3332
3333 /**
3334 * Helper method to get the method name from arguments.
3335 */
3336 private String methodToString(String name, Class<?>[] argTypes) {
3337 return getName() + '.' + name +
3338 ((argTypes == null || argTypes.length == 0) ?
3339 "()" :
3340 Arrays.stream(argTypes)
3341 .map(c -> c == null ? "null" : c.getName())
3342 .collect(Collectors.joining(",", "(", ")")));
3343 }
3344
3345 /** use serialVersionUID from JDK 1.1 for interoperability */
3346 @java.io.Serial
3347 private static final long serialVersionUID = 3206093459760846163L;
3348
3349
3350 /**
3351 * Class Class is special cased within the Serialization Stream Protocol.
3352 *
3353 * A Class instance is written initially into an ObjectOutputStream in the
3354 * following format:
3355 * <pre>
3356 * {@code TC_CLASS} ClassDescriptor
3357 * A ClassDescriptor is a special cased serialization of
3358 * a {@code java.io.ObjectStreamClass} instance.
3359 * </pre>
3360 * A new handle is generated for the initial time the class descriptor
3361 * is written into the stream. Future references to the class descriptor
3362 * are written as references to the initial class descriptor instance.
3363 *
3364 * @see java.io.ObjectStreamClass
3365 */
3366 @java.io.Serial
3367 private static final ObjectStreamField[] serialPersistentFields =
3368 new ObjectStreamField[0];
3369
3370
3371 /**
3372 * Returns the assertion status that would be assigned to this
3373 * class if it were to be initialized at the time this method is invoked.
3374 * If this class has had its assertion status set, the most recent
3375 * setting will be returned; otherwise, if any package default assertion
3376 * status pertains to this class, the most recent setting for the most
3377 * specific pertinent package default assertion status is returned;
3378 * otherwise, if this class is not a system class (i.e., it has a
3379 * class loader) its class loader's default assertion status is returned;
3380 * otherwise, the system class default assertion status is returned.
3381 *
3382 * @apiNote
3383 * Few programmers will have any need for this method; it is provided
3384 * for the benefit of the JDK itself. (It allows a class to determine at
3385 * the time that it is initialized whether assertions should be enabled.)
3386 * Note that this method is not guaranteed to return the actual
3387 * assertion status that was (or will be) associated with the specified
3388 * class when it was (or will be) initialized.
3389 *
3390 * @return the desired assertion status of the specified class.
3391 * @see java.lang.ClassLoader#setClassAssertionStatus
3392 * @see java.lang.ClassLoader#setPackageAssertionStatus
3393 * @see java.lang.ClassLoader#setDefaultAssertionStatus
3394 * @since 1.4
3395 */
3396 public boolean desiredAssertionStatus() {
3397 ClassLoader loader = classLoader;
3398 // If the loader is null this is a system class, so ask the VM
3399 if (loader == null)
3400 return desiredAssertionStatus0(this);
3401
3402 // If the classloader has been initialized with the assertion
3403 // directives, ask it. Otherwise, ask the VM.
3404 synchronized(loader.assertionLock) {
3405 if (loader.classAssertionStatus != null) {
3406 return loader.desiredAssertionStatus(getName());
3407 }
3408 }
3409 return desiredAssertionStatus0(this);
3410 }
3411
3412 // Retrieves the desired assertion status of this class from the VM
3413 private static native boolean desiredAssertionStatus0(Class<?> clazz);
3414
3415 /**
3416 * Returns true if and only if this class was declared as an enum in the
3417 * source code.
3418 *
3419 * Note that {@link java.lang.Enum} is not itself an enum class.
3420 *
3421 * Also note that if an enum constant is declared with a class body,
3422 * the class of that enum constant object is an anonymous class
3423 * and <em>not</em> the class of the declaring enum class. The
3424 * {@link Enum#getDeclaringClass} method of an enum constant can
3425 * be used to get the class of the enum class declaring the
3426 * constant.
3427 *
3428 * @return true if and only if this class was declared as an enum in the
3429 * source code
3430 * @since 1.5
3431 * @jls 8.9.1 Enum Constants
3432 */
3433 public boolean isEnum() {
3434 // An enum must both directly extend java.lang.Enum and have
3435 // the ENUM bit set; classes for specialized enum constants
3436 // don't do the former.
3437 return (this.getModifiers() & ENUM) != 0 &&
3438 this.getSuperclass() == java.lang.Enum.class;
3439 }
3440
3441 /**
3442 * Returns {@code true} if and only if this class is a record class.
3443 *
3444 * <p> The {@linkplain #getSuperclass() direct superclass} of a record
3445 * class is {@code java.lang.Record}. A record class is {@linkplain
3446 * Modifier#FINAL final}. A record class has (possibly zero) record
3447 * components; {@link #getRecordComponents()} returns a non-null but
3448 * possibly empty value for a record.
3449 *
3450 * <p> Note that class {@link Record} is not a record class and thus
3451 * invoking this method on class {@code Record} returns {@code false}.
3452 *
3453 * @return true if and only if this class is a record class, otherwise false
3454 * @jls 8.10 Record Classes
3455 * @since 16
3456 */
3457 public boolean isRecord() {
3458 // this superclass and final modifier check is not strictly necessary
3459 // they are intrinsified and serve as a fast-path check
3460 return getSuperclass() == java.lang.Record.class &&
3461 (this.getModifiers() & Modifier.FINAL) != 0 &&
3462 isRecord0();
3463 }
3464
3465 // Fetches the factory for reflective objects
3466 private static ReflectionFactory getReflectionFactory() {
3467 var factory = reflectionFactory;
3468 if (factory != null) {
3469 return factory;
3470 }
3471 return reflectionFactory = ReflectionFactory.getReflectionFactory();
3472 }
3473 private static ReflectionFactory reflectionFactory;
3474
3475 /**
3476 * When CDS is enabled, the Class class may be aot-initialized. However,
3477 * we can't archive reflectionFactory, so we reset it to null, so it
3478 * will be allocated again at runtime.
3479 */
3480 private static void resetArchivedStates() {
3481 reflectionFactory = null;
3482 }
3483
3484 /**
3485 * Returns the elements of this enum class or null if this
3486 * Class object does not represent an enum class.
3487 *
3488 * @return an array containing the values comprising the enum class
3489 * represented by this {@code Class} object in the order they're
3490 * declared, or null if this {@code Class} object does not
3491 * represent an enum class
3492 * @since 1.5
3493 * @jls 8.9.1 Enum Constants
3494 */
3495 public T[] getEnumConstants() {
3496 T[] values = getEnumConstantsShared();
3497 return (values != null) ? values.clone() : null;
3498 }
3499
3500 /**
3501 * Returns the elements of this enum class or null if this
3502 * Class object does not represent an enum class;
3503 * identical to getEnumConstants except that the result is
3504 * uncloned, cached, and shared by all callers.
3505 */
3506 T[] getEnumConstantsShared() {
3507 T[] constants = enumConstants;
3508 if (constants == null) {
3509 if (!isEnum()) return null;
3510 try {
3511 final Method values = getMethod("values");
3512 values.setAccessible(true);
3513 @SuppressWarnings("unchecked")
3514 T[] temporaryConstants = (T[])values.invoke(null);
3515 enumConstants = constants = temporaryConstants;
3516 }
3517 // These can happen when users concoct enum-like classes
3518 // that don't comply with the enum spec.
3519 catch (InvocationTargetException | NoSuchMethodException |
3520 IllegalAccessException | NullPointerException |
3521 ClassCastException ex) { return null; }
3522 }
3523 return constants;
3524 }
3525 private transient volatile T[] enumConstants;
3526
3527 /**
3528 * Returns a map from simple name to enum constant. This package-private
3529 * method is used internally by Enum to implement
3530 * {@code public static <T extends Enum<T>> T valueOf(Class<T>, String)}
3531 * efficiently. Note that the map is returned by this method is
3532 * created lazily on first use. Typically it won't ever get created.
3533 */
3534 Map<String, T> enumConstantDirectory() {
3535 Map<String, T> directory = enumConstantDirectory;
3536 if (directory == null) {
3537 T[] universe = getEnumConstantsShared();
3538 if (universe == null)
3539 throw new IllegalArgumentException(
3540 getName() + " is not an enum class");
3541 directory = HashMap.newHashMap(universe.length);
3542 for (T constant : universe) {
3543 directory.put(((Enum<?>)constant).name(), constant);
3544 }
3545 enumConstantDirectory = directory;
3546 }
3547 return directory;
3548 }
3549 private transient volatile Map<String, T> enumConstantDirectory;
3550
3551 /**
3552 * Casts an object to the class or interface represented
3553 * by this {@code Class} object.
3554 *
3555 * @param obj the object to be cast, may be {@code null}
3556 * @return the object after casting, or null if obj is null
3557 *
3558 * @throws ClassCastException if the object is not
3559 * null and is not assignable to the type T.
3560 *
3561 * @since 1.5
3562 */
3563 @SuppressWarnings("unchecked")
3564 @IntrinsicCandidate
3565 public T cast(Object obj) {
3566 if (obj != null && !isInstance(obj))
3567 throw new ClassCastException(cannotCastMsg(obj));
3568 return (T) obj;
3569 }
3570
3571 private String cannotCastMsg(Object obj) {
3572 return "Cannot cast " + obj.getClass().getName() + " to " + getName();
3573 }
3574
3575 /**
3576 * Casts this {@code Class} object to represent a subclass of the class
3577 * represented by the specified class object. Checks that the cast
3578 * is valid, and throws a {@code ClassCastException} if it is not. If
3579 * this method succeeds, it always returns a reference to this {@code Class} object.
3580 *
3581 * <p>This method is useful when a client needs to "narrow" the type of
3582 * a {@code Class} object to pass it to an API that restricts the
3583 * {@code Class} objects that it is willing to accept. A cast would
3584 * generate a compile-time warning, as the correctness of the cast
3585 * could not be checked at runtime (because generic types are implemented
3586 * by erasure).
3587 *
3588 * @param <U> the type to cast this {@code Class} object to
3589 * @param clazz the class of the type to cast this {@code Class} object to
3590 * @return this {@code Class} object, cast to represent a subclass of
3591 * the specified class object.
3592 * @throws ClassCastException if this {@code Class} object does not
3593 * represent a subclass of the specified class (here "subclass" includes
3594 * the class itself).
3595 * @since 1.5
3596 */
3597 @SuppressWarnings("unchecked")
3598 public <U> Class<? extends U> asSubclass(Class<U> clazz) {
3599 if (clazz.isAssignableFrom(this))
3600 return (Class<? extends U>) this;
3601 else
3602 throw new ClassCastException(this.toString());
3603 }
3604
3605 /**
3606 * {@inheritDoc}
3607 * <p>Note that any annotation returned by this method is a
3608 * declaration annotation.
3609 *
3610 * @since 1.5
3611 */
3612 @Override
3613 @SuppressWarnings("unchecked")
3614 public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
3615 Objects.requireNonNull(annotationClass);
3616
3617 return (A) annotationData().annotations.get(annotationClass);
3618 }
3619
3620 /**
3621 * {@inheritDoc}
3622 * @since 1.5
3623 */
3624 @Override
3625 public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
3626 return GenericDeclaration.super.isAnnotationPresent(annotationClass);
3627 }
3628
3629 /**
3630 * {@inheritDoc}
3631 * <p>Note that any annotations returned by this method are
3632 * declaration annotations.
3633 *
3634 * @since 1.8
3635 */
3636 @Override
3637 public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass) {
3638 Objects.requireNonNull(annotationClass);
3639
3640 AnnotationData annotationData = annotationData();
3641 return AnnotationSupport.getAssociatedAnnotations(annotationData.declaredAnnotations,
3642 this,
3643 annotationClass);
3644 }
3645
3646 /**
3647 * {@inheritDoc}
3648 * <p>Note that any annotations returned by this method are
3649 * declaration annotations.
3650 *
3651 * @since 1.5
3652 */
3653 @Override
3654 public Annotation[] getAnnotations() {
3655 return AnnotationParser.toArray(annotationData().annotations);
3656 }
3657
3658 /**
3659 * {@inheritDoc}
3660 * <p>Note that any annotation returned by this method is a
3661 * declaration annotation.
3662 *
3663 * @since 1.8
3664 */
3665 @Override
3666 @SuppressWarnings("unchecked")
3667 public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
3668 Objects.requireNonNull(annotationClass);
3669
3670 return (A) annotationData().declaredAnnotations.get(annotationClass);
3671 }
3672
3673 /**
3674 * {@inheritDoc}
3675 * <p>Note that any annotations returned by this method are
3676 * declaration annotations.
3677 *
3678 * @since 1.8
3679 */
3680 @Override
3681 public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass) {
3682 Objects.requireNonNull(annotationClass);
3683
3684 return AnnotationSupport.getDirectlyAndIndirectlyPresent(annotationData().declaredAnnotations,
3685 annotationClass);
3686 }
3687
3688 /**
3689 * {@inheritDoc}
3690 * <p>Note that any annotations returned by this method are
3691 * declaration annotations.
3692 *
3693 * @since 1.5
3694 */
3695 @Override
3696 public Annotation[] getDeclaredAnnotations() {
3697 return AnnotationParser.toArray(annotationData().declaredAnnotations);
3698 }
3699
3700 // annotation data that might get invalidated when JVM TI RedefineClasses() is called
3701 private static class AnnotationData {
3702 final Map<Class<? extends Annotation>, Annotation> annotations;
3703 final Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
3704
3705 // Value of classRedefinedCount when we created this AnnotationData instance
3706 final int redefinedCount;
3707
3708 AnnotationData(Map<Class<? extends Annotation>, Annotation> annotations,
3709 Map<Class<? extends Annotation>, Annotation> declaredAnnotations,
3710 int redefinedCount) {
3711 this.annotations = annotations;
3712 this.declaredAnnotations = declaredAnnotations;
3713 this.redefinedCount = redefinedCount;
3714 }
3715 }
3716
3717 // Annotations cache
3718 @SuppressWarnings("UnusedDeclaration")
3719 private transient volatile AnnotationData annotationData;
3720
3721 private AnnotationData annotationData() {
3722 while (true) { // retry loop
3723 AnnotationData annotationData = this.annotationData;
3724 int classRedefinedCount = this.classRedefinedCount;
3725 if (annotationData != null &&
3726 annotationData.redefinedCount == classRedefinedCount) {
3727 return annotationData;
3728 }
3729 // null or stale annotationData -> optimistically create new instance
3730 AnnotationData newAnnotationData = createAnnotationData(classRedefinedCount);
3731 // try to install it
3732 if (Atomic.casAnnotationData(this, annotationData, newAnnotationData)) {
3733 // successfully installed new AnnotationData
3734 return newAnnotationData;
3735 }
3736 }
3737 }
3738
3739 private AnnotationData createAnnotationData(int classRedefinedCount) {
3740 Map<Class<? extends Annotation>, Annotation> declaredAnnotations =
3741 AnnotationParser.parseAnnotations(getRawAnnotations(), getConstantPool(), this);
3742 Class<?> superClass = getSuperclass();
3743 Map<Class<? extends Annotation>, Annotation> annotations = null;
3744 if (superClass != null) {
3745 Map<Class<? extends Annotation>, Annotation> superAnnotations =
3746 superClass.annotationData().annotations;
3747 for (Map.Entry<Class<? extends Annotation>, Annotation> e : superAnnotations.entrySet()) {
3748 Class<? extends Annotation> annotationClass = e.getKey();
3749 if (AnnotationType.getInstance(annotationClass).isInherited()) {
3750 if (annotations == null) { // lazy construction
3751 annotations = LinkedHashMap.newLinkedHashMap(Math.max(
3752 declaredAnnotations.size(),
3753 Math.min(12, declaredAnnotations.size() + superAnnotations.size())
3754 )
3755 );
3756 }
3757 annotations.put(annotationClass, e.getValue());
3758 }
3759 }
3760 }
3761 if (annotations == null) {
3762 // no inherited annotations -> share the Map with declaredAnnotations
3763 annotations = declaredAnnotations;
3764 } else {
3765 // at least one inherited annotation -> declared may override inherited
3766 annotations.putAll(declaredAnnotations);
3767 }
3768 return new AnnotationData(annotations, declaredAnnotations, classRedefinedCount);
3769 }
3770
3771 // Annotation interfaces cache their internal (AnnotationType) form
3772
3773 @SuppressWarnings("UnusedDeclaration")
3774 private transient volatile AnnotationType annotationType;
3775
3776 boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) {
3777 return Atomic.casAnnotationType(this, oldType, newType);
3778 }
3779
3780 AnnotationType getAnnotationType() {
3781 return annotationType;
3782 }
3783
3784 Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap() {
3785 return annotationData().declaredAnnotations;
3786 }
3787
3788 /* Backing store of user-defined values pertaining to this class.
3789 * Maintained by the ClassValue class.
3790 */
3791 transient ClassValue.ClassValueMap classValueMap;
3792
3793 /**
3794 * Returns an {@code AnnotatedType} object that represents the use of a
3795 * type to specify the superclass of the entity represented by this {@code
3796 * Class} object. (The <em>use</em> of type Foo to specify the superclass
3797 * in '... extends Foo' is distinct from the <em>declaration</em> of class
3798 * Foo.)
3799 *
3800 * <p> If this {@code Class} object represents a class whose declaration
3801 * does not explicitly indicate an annotated superclass, then the return
3802 * value is an {@code AnnotatedType} object representing an element with no
3803 * annotations.
3804 *
3805 * <p> If this {@code Class} represents either the {@code Object} class, an
3806 * interface type, an array type, a primitive type, or void, the return
3807 * value is {@code null}.
3808 *
3809 * @return an object representing the superclass
3810 * @since 1.8
3811 */
3812 public AnnotatedType getAnnotatedSuperclass() {
3813 if (this == Object.class ||
3814 isInterface() ||
3815 isArray() ||
3816 isPrimitive() ||
3817 this == Void.TYPE) {
3818 return null;
3819 }
3820
3821 return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
3822 }
3823
3824 /**
3825 * Returns an array of {@code AnnotatedType} objects that represent the use
3826 * of types to specify superinterfaces of the entity represented by this
3827 * {@code Class} object. (The <em>use</em> of type Foo to specify a
3828 * superinterface in '... implements Foo' is distinct from the
3829 * <em>declaration</em> of interface Foo.)
3830 *
3831 * <p> If this {@code Class} object represents a class, the return value is
3832 * an array containing objects representing the uses of interface types to
3833 * specify interfaces implemented by the class. The order of the objects in
3834 * the array corresponds to the order of the interface types used in the
3835 * 'implements' clause of the declaration of this {@code Class} object.
3836 *
3837 * <p> If this {@code Class} object represents an interface, the return
3838 * value is an array containing objects representing the uses of interface
3839 * types to specify interfaces directly extended by the interface. The
3840 * order of the objects in the array corresponds to the order of the
3841 * interface types used in the 'extends' clause of the declaration of this
3842 * {@code Class} object.
3843 *
3844 * <p> If this {@code Class} object represents a class or interface whose
3845 * declaration does not explicitly indicate any annotated superinterfaces,
3846 * the return value is an array of length 0.
3847 *
3848 * <p> If this {@code Class} object represents either the {@code Object}
3849 * class, an array type, a primitive type, or void, the return value is an
3850 * array of length 0.
3851 *
3852 * @return an array representing the superinterfaces
3853 * @since 1.8
3854 */
3855 public AnnotatedType[] getAnnotatedInterfaces() {
3856 return TypeAnnotationParser.buildAnnotatedInterfaces(getRawTypeAnnotations(), getConstantPool(), this);
3857 }
3858
3859 private native Class<?> getNestHost0();
3860
3861 /**
3862 * Returns the nest host of the <a href=#nest>nest</a> to which the class
3863 * or interface represented by this {@code Class} object belongs.
3864 * Every class and interface belongs to exactly one nest.
3865 *
3866 * If the nest host of this class or interface has previously
3867 * been determined, then this method returns the nest host.
3868 * If the nest host of this class or interface has
3869 * not previously been determined, then this method determines the nest
3870 * host using the algorithm of JVMS 5.4.4, and returns it.
3871 *
3872 * Often, a class or interface belongs to a nest consisting only of itself,
3873 * in which case this method returns {@code this} to indicate that the class
3874 * or interface is the nest host.
3875 *
3876 * <p>If this {@code Class} object represents a primitive type, an array type,
3877 * or {@code void}, then this method returns {@code this},
3878 * indicating that the represented entity belongs to the nest consisting only of
3879 * itself, and is the nest host.
3880 *
3881 * @return the nest host of this class or interface
3882 *
3883 * @since 11
3884 * @jvms 4.7.28 The {@code NestHost} Attribute
3885 * @jvms 4.7.29 The {@code NestMembers} Attribute
3886 * @jvms 5.4.4 Access Control
3887 */
3888 public Class<?> getNestHost() {
3889 if (isPrimitive() || isArray()) {
3890 return this;
3891 }
3892 return getNestHost0();
3893 }
3894
3895 /**
3896 * Determines if the given {@code Class} is a nestmate of the
3897 * class or interface represented by this {@code Class} object.
3898 * Two classes or interfaces are nestmates
3899 * if they have the same {@linkplain #getNestHost() nest host}.
3900 *
3901 * @param c the class to check
3902 * @return {@code true} if this class and {@code c} are members of
3903 * the same nest; and {@code false} otherwise.
3904 *
3905 * @since 11
3906 */
3907 public boolean isNestmateOf(Class<?> c) {
3908 Objects.requireNonNull(c);
3909 if (this == c) {
3910 return true;
3911 }
3912 if (isPrimitive() || isArray() ||
3913 c.isPrimitive() || c.isArray()) {
3914 return false;
3915 }
3916
3917 return getNestHost() == c.getNestHost();
3918 }
3919
3920 private native Class<?>[] getNestMembers0();
3921
3922 /**
3923 * Returns an array containing {@code Class} objects representing all the
3924 * classes and interfaces that are members of the nest to which the class
3925 * or interface represented by this {@code Class} object belongs.
3926 *
3927 * First, this method obtains the {@linkplain #getNestHost() nest host},
3928 * {@code H}, of the nest to which the class or interface represented by
3929 * this {@code Class} object belongs. The zeroth element of the returned
3930 * array is {@code H}.
3931 *
3932 * Then, for each class or interface {@code C} which is recorded by {@code H}
3933 * as being a member of its nest, this method attempts to obtain the {@code Class}
3934 * object for {@code C} (using {@linkplain #getClassLoader() the defining class
3935 * loader} of the current {@code Class} object), and then obtains the
3936 * {@linkplain #getNestHost() nest host} of the nest to which {@code C} belongs.
3937 * The classes and interfaces which are recorded by {@code H} as being members
3938 * of its nest, and for which {@code H} can be determined as their nest host,
3939 * are indicated by subsequent elements of the returned array. The order of
3940 * such elements is unspecified. Duplicates are permitted.
3941 *
3942 * <p>If this {@code Class} object represents a primitive type, an array type,
3943 * or {@code void}, then this method returns a single-element array containing
3944 * {@code this}.
3945 *
3946 * @apiNote
3947 * The returned array includes only the nest members recorded in the {@code NestMembers}
3948 * attribute, and not any hidden classes that were added to the nest via
3949 * {@link MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
3950 * Lookup::defineHiddenClass}.
3951 *
3952 * @return an array of all classes and interfaces in the same nest as
3953 * this class or interface
3954 *
3955 * @since 11
3956 * @see #getNestHost()
3957 * @jvms 4.7.28 The {@code NestHost} Attribute
3958 * @jvms 4.7.29 The {@code NestMembers} Attribute
3959 */
3960 public Class<?>[] getNestMembers() {
3961 if (isPrimitive() || isArray()) {
3962 return new Class<?>[] { this };
3963 }
3964 Class<?>[] members = getNestMembers0();
3965 // Can't actually enable this due to bootstrapping issues
3966 // assert(members.length != 1 || members[0] == this); // expected invariant from VM
3967 return members;
3968 }
3969
3970 /**
3971 * Returns the descriptor string of the entity (class, interface, array class,
3972 * primitive type, or {@code void}) represented by this {@code Class} object.
3973 *
3974 * <p> If this {@code Class} object represents a class or interface,
3975 * not an array class, then:
3976 * <ul>
3977 * <li> If the class or interface is not {@linkplain Class#isHidden() hidden},
3978 * then the result is a field descriptor (JVMS {@jvms 4.3.2})
3979 * for the class or interface. Calling
3980 * {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor}
3981 * with the result descriptor string produces a {@link ClassDesc ClassDesc}
3982 * describing this class or interface.
3983 * <li> If the class or interface is {@linkplain Class#isHidden() hidden},
3984 * then the result is a string of the form:
3985 * <blockquote>
3986 * {@code "L" +} <em>N</em> {@code + "." + <suffix> + ";"}
3987 * </blockquote>
3988 * where <em>N</em> is the {@linkplain ClassLoader##binary-name binary name}
3989 * encoded in internal form indicated by the {@code class} file passed to
3990 * {@link MethodHandles.Lookup#defineHiddenClass(byte[], boolean, MethodHandles.Lookup.ClassOption...)
3991 * Lookup::defineHiddenClass}, and {@code <suffix>} is an unqualified name.
3992 * A hidden class or interface has no {@linkplain ClassDesc nominal descriptor}.
3993 * The result string is not a type descriptor.
3994 * </ul>
3995 *
3996 * <p> If this {@code Class} object represents an array class, then
3997 * the result is a string consisting of one or more '{@code [}' characters
3998 * representing the depth of the array nesting, followed by the
3999 * descriptor string of the element type.
4000 * <ul>
4001 * <li> If the element type is not a {@linkplain Class#isHidden() hidden} class
4002 * or interface, then this array class can be described nominally.
4003 * Calling {@link ClassDesc#ofDescriptor(String) ClassDesc::ofDescriptor}
4004 * with the result descriptor string produces a {@link ClassDesc ClassDesc}
4005 * describing this array class.
4006 * <li> If the element type is a {@linkplain Class#isHidden() hidden} class or
4007 * interface, then this array class cannot be described nominally.
4008 * The result string is not a type descriptor.
4009 * </ul>
4010 *
4011 * <p> If this {@code Class} object represents a primitive type or
4012 * {@code void}, then the result is a field descriptor string which
4013 * is a one-letter code corresponding to a primitive type or {@code void}
4014 * ({@code "B", "C", "D", "F", "I", "J", "S", "Z", "V"}) (JVMS {@jvms 4.3.2}).
4015 *
4016 * @return the descriptor string for this {@code Class} object
4017 * @jvms 4.3.2 Field Descriptors
4018 * @since 12
4019 */
4020 @Override
4021 public String descriptorString() {
4022 if (isPrimitive())
4023 return Wrapper.forPrimitiveType(this).basicTypeString();
4024
4025 if (isArray()) {
4026 return "[".concat(componentType.descriptorString());
4027 } else if (isHidden()) {
4028 String name = getName();
4029 int index = name.indexOf('/');
4030 return new StringBuilder(name.length() + 2)
4031 .append('L')
4032 .append(name.substring(0, index).replace('.', '/'))
4033 .append('.')
4034 .append(name, index + 1, name.length())
4035 .append(';')
4036 .toString();
4037 } else {
4038 String name = getName().replace('.', '/');
4039 return StringConcatHelper.concat("L", name, ";");
4040 }
4041 }
4042
4043 /**
4044 * Returns the component type of this {@code Class}, if it describes
4045 * an array type, or {@code null} otherwise.
4046 *
4047 * @implSpec
4048 * Equivalent to {@link Class#getComponentType()}.
4049 *
4050 * @return a {@code Class} describing the component type, or {@code null}
4051 * if this {@code Class} does not describe an array type
4052 * @since 12
4053 */
4054 @Override
4055 public Class<?> componentType() {
4056 return getComponentType();
4057 }
4058
4059 /**
4060 * Returns a {@code Class} for an array type whose component type
4061 * is described by this {@linkplain Class}.
4062 *
4063 * @throws UnsupportedOperationException if this component type is {@linkplain
4064 * Void#TYPE void} or if the number of dimensions of the resulting array
4065 * type would exceed 255.
4066 * @return a {@code Class} describing the array type
4067 * @jvms 4.3.2 Field Descriptors
4068 * @jvms 4.4.1 The {@code CONSTANT_Class_info} Structure
4069 * @since 12
4070 */
4071 @Override
4072 public Class<?> arrayType() {
4073 try {
4074 return Array.newInstance(this, 0).getClass();
4075 } catch (IllegalArgumentException iae) {
4076 throw new UnsupportedOperationException(iae);
4077 }
4078 }
4079
4080 /**
4081 * Returns a nominal descriptor for this instance, if one can be
4082 * constructed, or an empty {@link Optional} if one cannot be.
4083 *
4084 * @return An {@link Optional} containing the resulting nominal descriptor,
4085 * or an empty {@link Optional} if one cannot be constructed.
4086 * @since 12
4087 */
4088 @Override
4089 public Optional<ClassDesc> describeConstable() {
4090 Class<?> c = isArray() ? elementType() : this;
4091 return c.isHidden() ? Optional.empty()
4092 : Optional.of(ConstantUtils.classDesc(this));
4093 }
4094
4095 /**
4096 * Returns {@code true} if and only if the underlying class is a hidden class.
4097 *
4098 * @return {@code true} if and only if this class is a hidden class.
4099 *
4100 * @since 15
4101 * @see MethodHandles.Lookup#defineHiddenClass
4102 * @see Class##hiddenClasses Hidden Classes
4103 */
4104 @IntrinsicCandidate
4105 public native boolean isHidden();
4106
4107 /**
4108 * Returns an array containing {@code Class} objects representing the
4109 * direct subinterfaces or subclasses permitted to extend or
4110 * implement this class or interface if it is sealed. The order of such elements
4111 * is unspecified. The array is empty if this sealed class or interface has no
4112 * permitted subclass. If this {@code Class} object represents a primitive type,
4113 * {@code void}, an array type, or a class or interface that is not sealed,
4114 * that is {@link #isSealed()} returns {@code false}, then this method returns {@code null}.
4115 * Conversely, if {@link #isSealed()} returns {@code true}, then this method
4116 * returns a non-null value.
4117 *
4118 * For each class or interface {@code C} which is recorded as a permitted
4119 * direct subinterface or subclass of this class or interface,
4120 * this method attempts to obtain the {@code Class}
4121 * object for {@code C} (using {@linkplain #getClassLoader() the defining class
4122 * loader} of the current {@code Class} object).
4123 * The {@code Class} objects which can be obtained and which are direct
4124 * subinterfaces or subclasses of this class or interface,
4125 * are indicated by elements of the returned array. If a {@code Class} object
4126 * cannot be obtained, it is silently ignored, and not included in the result
4127 * array.
4128 *
4129 * @return an array of {@code Class} objects of the permitted subclasses of this class
4130 * or interface, or {@code null} if this class or interface is not sealed.
4131 *
4132 * @jls 8.1 Class Declarations
4133 * @jls 9.1 Interface Declarations
4134 * @since 17
4135 */
4136 public Class<?>[] getPermittedSubclasses() {
4137 Class<?>[] subClasses;
4138 if (isArray() || isPrimitive() || (subClasses = getPermittedSubclasses0()) == null) {
4139 return null;
4140 }
4141 if (subClasses.length > 0) {
4142 if (Arrays.stream(subClasses).anyMatch(c -> !isDirectSubType(c))) {
4143 subClasses = Arrays.stream(subClasses)
4144 .filter(this::isDirectSubType)
4145 .toArray(s -> new Class<?>[s]);
4146 }
4147 }
4148 return subClasses;
4149 }
4150
4151 private boolean isDirectSubType(Class<?> c) {
4152 if (isInterface()) {
4153 for (Class<?> i : c.getInterfaces(/* cloneArray */ false)) {
4154 if (i == this) {
4155 return true;
4156 }
4157 }
4158 } else {
4159 return c.getSuperclass() == this;
4160 }
4161 return false;
4162 }
4163
4164 /**
4165 * Returns {@code true} if and only if this {@code Class} object represents
4166 * a sealed class or interface. If this {@code Class} object represents a
4167 * primitive type, {@code void}, or an array type, this method returns
4168 * {@code false}. A sealed class or interface has (possibly zero) permitted
4169 * subclasses; {@link #getPermittedSubclasses()} returns a non-null but
4170 * possibly empty value for a sealed class or interface.
4171 *
4172 * @return {@code true} if and only if this {@code Class} object represents
4173 * a sealed class or interface.
4174 *
4175 * @jls 8.1 Class Declarations
4176 * @jls 9.1 Interface Declarations
4177 * @since 17
4178 */
4179 public boolean isSealed() {
4180 if (isArray() || isPrimitive()) {
4181 return false;
4182 }
4183 return getPermittedSubclasses() != null;
4184 }
4185
4186 private native Class<?>[] getPermittedSubclasses0();
4187
4188 /*
4189 * Return the class's major and minor class file version packed into an int.
4190 * The high order 16 bits contain the class's minor version. The low order
4191 * 16 bits contain the class's major version.
4192 *
4193 * If the class is an array type then the class file version of its element
4194 * type is returned. If the class is a primitive type then the latest class
4195 * file major version is returned and zero is returned for the minor version.
4196 */
4197 /* package-private */
4198 int getClassFileVersion() {
4199 Class<?> c = isArray() ? elementType() : this;
4200 return c.getClassFileVersion0();
4201 }
4202
4203 private native int getClassFileVersion0();
4204
4205 /**
4206 * Return the access flags as they were in the class's bytecode, including
4207 * the original setting of ACC_SUPER.
4208 *
4209 * If this {@code Class} object represents a primitive type or
4210 * void, the flags are {@code PUBLIC}, {@code ABSTRACT}, and
4211 * {@code FINAL}.
4212 * If this {@code Class} object represents an array type, return 0.
4213 */
4214 int getClassFileAccessFlags() {
4215 return classFileAccessFlags;
4216 }
4217
4218 // Validates the length of the class name and throws an exception if it exceeds the maximum allowed length.
4219 private static void validateClassNameLength(String name) throws ClassNotFoundException {
4220 if (!ModifiedUtf.isValidLengthInConstantPool(name)) {
4221 throw new ClassNotFoundException(
4222 "Class name length exceeds limit of "
4223 + ModifiedUtf.CONSTANT_POOL_UTF8_MAX_BYTES
4224 + ": " + name.substring(0,256) + "...");
4225 }
4226 }
4227 }