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