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