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