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