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