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